diff --git a/.github/workflows/beta.yml b/.github/workflows/beta.yml
index 5ae76d4..76ff2a9 100644
--- a/.github/workflows/beta.yml
+++ b/.github/workflows/beta.yml
@@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- board: [esp32dev, esp32-s3, esp32-c3, esp32-c6, esp32-solo1]
+ board: [esp32, esp32-s3, esp32-c3, esp32-c6, esp32-h2, esp32-solo1]
build: [release, debug]
env:
BOARD: ${{ matrix.board }}
@@ -23,11 +23,6 @@ jobs:
run: |
# remove dash character
export VARIANT=${VARIANT//-/}
-
- if [ "$VARIANT" = "esp32dev" ]; then
- VARIANT="esp32"
- fi
-
echo "VARIANT=${VARIANT}" | tee -a ${GITHUB_ENV}
- uses: actions/checkout@v4
with:
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1dc3ea5..f6ad16f 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -18,7 +18,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- board: [esp32dev, esp32-s3, esp32-c3, esp32-c6, esp32-solo1]
+ board: [esp32, esp32-s3, esp32-c3, esp32-c6, esp32-h2, esp32-solo1]
build: [release, debug]
env:
BOARD: ${{ matrix.board }}
@@ -29,11 +29,6 @@ jobs:
run: |
# remove dash character
export VARIANT=${VARIANT//-/}
-
- if [ "$VARIANT" = "esp32dev" ]; then
- VARIANT="esp32"
- fi
-
echo "VARIANT=${VARIANT}" | tee -a ${GITHUB_ENV}
- uses: actions/checkout@v4
with:
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
index 09c197a..4a00ebb 100644
--- a/.github/workflows/nightly.yml
+++ b/.github/workflows/nightly.yml
@@ -34,7 +34,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- board: [esp32dev, esp32-s3, esp32-c3, esp32-c6, esp32-solo1]
+ board: [esp32, esp32-s3, esp32-c3, esp32-c6, esp32-h2, esp32-solo1]
build: [release, debug]
env:
BOARD: ${{ matrix.board }}
@@ -45,11 +45,6 @@ jobs:
run: |
# remove dash character
export VARIANT=${VARIANT//-/}
-
- if [ "$VARIANT" = "esp32dev" ]; then
- VARIANT="esp32"
- fi
-
echo "VARIANT=${VARIANT}" | tee -a ${GITHUB_ENV}
- uses: actions/checkout@v4
with:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8c4c0b9..b8a2eb1 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- board: [esp32dev, esp32-s3, esp32-c3, esp32-c6, esp32-solo1]
+ board: [esp32, esp32-s3, esp32-c3, esp32-c6, esp32-h2, esp32-solo1]
build: [release, debug]
env:
BOARD: ${{ matrix.board }}
@@ -23,11 +23,6 @@ jobs:
run: |
# remove dash character
export VARIANT=${VARIANT//-/}
-
- if [ "$VARIANT" = "esp32dev" ]; then
- VARIANT="esp32"
- fi
-
echo "VARIANT=${VARIANT}" | tee -a ${GITHUB_ENV}
- uses: actions/checkout@v4
with:
diff --git a/Docker/README.md b/Docker/README.md
index 5727b8a..140d733 100644
--- a/Docker/README.md
+++ b/Docker/README.md
@@ -2,7 +2,7 @@
You can build this project using Docker. Just run the following commands in the console:
-## Build with PlatformIO (will build for the ESP32, ESP32-S3, ESP32-C3, ESP32-C6 and ESP32-Solo1)
+## Build with PlatformIO (will build for the ESP32, ESP32-S3, ESP32-C3, ESP32-C6, ESP32-H2 and ESP32-Solo1)
```console
git clone https://github.com/technyon/nuki_hub --recursive
cd nuki_hub/Docker
diff --git a/Makefile b/Makefile
index 6b3070f..c9a48b5 100644
--- a/Makefile
+++ b/Makefile
@@ -22,9 +22,6 @@ debug: $(DEBUG_BOARDS)
all: release updater debug
# Alias
-.PHONY: esp32
-esp32: esp32dev
-
esp%:
@echo "Building $@"
pio run --environment $@
diff --git a/README.md b/README.md
index fce2513..4c7f7fa 100644
--- a/README.md
+++ b/README.md
@@ -18,11 +18,10 @@ Feel free to join us on Discord: https://discord.gg/9nPq85bP4p
- Nuki Hub is compiled against all ESP32 models with Wi-Fi and Bluetooh Low Energy (BLE) which are supported by ESP-IDF 5.1.4 and Arduino Core 3.0.4.
- Tested stable builds are provided for the ESP32, ESP32-S3 and ESP32-C3.
- Untested builds are provided for the ESP32-Solo1.
-- Support for the ESP32-C6 is experimental. There could be more frequent crashes than on other ESP32 devices and connections with the Nuki device could be slower than on other ESP32 devices.
+- Support for the ESP32-C6 and ESP32-H2 is experimental. There could be more frequent crashes than on other ESP32 devices and connections with the Nuki device could be slower than on other ESP32 devices.
Not supported ESP32 devices:
- The ESP32-S2 has no BLE and as such can't run Nuki Hub.
-- The ESP32-H2 has no Wi-FI and Nuki Hub is not compiled against this target because of this (at this time).
Supported Nuki devices:
- Nuki Smart Lock 1.0
@@ -36,7 +35,7 @@ Feel free to join us on Discord: https://discord.gg/9nPq85bP4p
- Nuki Keypad 2.0
Supported Ethernet devices:
-As an alternative to Wi-Fi (which is available on any supported ESP32), the following ESP32 modules with wired ethernet are supported:
+As an alternative to Wi-Fi (which is available on any supported ESP32), the following ESP32 modules with built-in wired ethernet are supported:
- [Olimex ESP32-POE](https://www.olimex.com/Products/IoT/ESP32/ESP32-POE/open-source-hardware)
- [Olimex ESP32-POE-ISO](https://www.olimex.com/Products/IoT/ESP32/ESP32-POE-ISO/open-source-hardware)
- [WT32-ETH01](http://en.wireless-tag.com/product-item-2.html)
@@ -45,6 +44,9 @@ As an alternative to Wi-Fi (which is available on any supported ESP32), the foll
- [LilyGO-T-ETH-POE](https://github.com/Xinyuan-LilyGO/LilyGO-T-ETH-POE)
- [GL-S10 (Revisions 2.1, 2.3 / 1.0 is not supported)](https://www.gl-inet.com/products/gl-s10/)
+In principle all ESP32 (and variants) devices with built-in ethernet port are supported, but might require additional setup using the "Custom LAN setup" option.
+See the "[Connecting via Ethernet](#connecting-via-ethernet-optional)" section for more information.
+
## Support Nuki Hub development
If you haven't ordered your Nuki product yet, you can support me by using my referrer code when placing your order:
@@ -76,7 +78,7 @@ In a browser navigate to the IP address assigned to the ESP32 via DHCP (often fo
Next click on "Edit" below "MQTT and Network Configuration" and enter the address and port (usually 1883) of your MQTT broker and a username and a password if required by your MQTT broker.
The firmware supports SSL encryption for MQTT, however most people and especially home users don't use this.
-In that case leave all fields starting with "MQTT SSL" blank. Otherwise see the "[MQTT Encryption](#mqtt-encryption-optional-wi-fi-and-lan8720-only)" section of this README.
+In that case leave all fields starting with "MQTT SSL" blank. Otherwise see the "[MQTT Encryption](#mqtt-encryption-optional)" section of this README.
## Pairing with a Nuki Lock or Opener
@@ -114,9 +116,9 @@ In a browser navigate to the IP address assigned to the ESP32.
- Home Assistant discovery topic: Set to the Home Assistant auto discovery topic, leave empty to disable auto discovery. Usually "homeassistant" unless you manually changed this setting on the Home Assistant side.
- Home Assistant device configuration URL: When using Home Assistant discovery the link to the Nuki Hub Web Configuration will be published to Home Assistant. By default when this setting is left empty this will link to the current IP of the Nuki Hub. When using a reverse proxy to access the Web Configuration you can set a custom URL here.
- Set Nuki Opener Lock/Unlock action in Home Assistant to Continuous mode (Opener only): By default the lock entity in Home Assistant will enable Ring-to-Open (RTO) when unlocking and disable RTO when locking. By enabling this setting this behaviour will change and now unlocking will enable Continuous Mode and locking will disable Continuous Mode, for more information see the "[Home Assistant Discovery](#home-assistant-discovery-optional)" section of this README.
-- MQTT SSL CA Certificate: Optionally set to the CA SSL certificate of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional-wi-fi-and-lan8720-only)" section of this README.
-- MQTT SSL Client Certificate: Optionally set to the Client SSL certificate of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional-wi-fi-and-lan8720-only)" section of this README.
-- MQTT SSL Client Key: Optionally set to the Client SSL key of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional-wi-fi-and-lan8720-only)" section of this README.
+- MQTT SSL CA Certificate: Optionally set to the CA SSL certificate of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional)" section of this README.
+- MQTT SSL Client Certificate: Optionally set to the Client SSL certificate of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional)" section of this README.
+- MQTT SSL Client Key: Optionally set to the Client SSL key of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional)" section of this README.
- Network hardware: "Wi-Fi only" by default, set to one of the specified ethernet modules if available, see the "Supported Ethernet devices" and "[Connecting via Ethernet](#connecting-via-ethernet-optional)" section of this README.
- Disable fallback to Wi-Fi / Wi-Fi config portal: By default the Nuki Hub will fallback to Wi-Fi and open the Wi-Fi configuration portal when the network connection fails. Enable this setting to disable this fallback.
- Connect to AP with the best signal in an environment with multiple APs with the same SSID: Enable to perform a scan for the Access Point with the best signal strenght for the specified SSID in a multi AP/Mesh environment.
@@ -302,7 +304,7 @@ In a browser navigate to the IP address assigned to the ESP32.
### Maintanence
-- maintenance/networkDevice: Set to the name of the network device that is used by the ESP. When using Wi-Fi will be set to "Built-in Wi-Fi". If using Ethernet will be set to "Wiznet W5500", "Olimex (LAN8720)", "WT32-ETH01", "M5STACK PoESP32 Unit", "LilyGO T-ETH-POE" or "GL-S10".
+- maintenance/networkDevice: Set to the name of the network device that is used by the ESP. When using Wi-Fi will be set to "Built-in Wi-Fi". If using Ethernet will be set to "Wiznet W5500", "ETH01-Evo", "Olimex (LAN8720)", "WT32-ETH01", "M5STACK PoESP32 Unit", "LilyGO T-ETH-POE" or "GL-S10".
- maintenance/reset: Set to 1 to trigger a reboot of the ESP. Auto-resets to 0.
- maintenance/update: Set to 1 to auto update Nuki Hub to the latest version from GitHub. Requires the setting "Allow updating using MQTT" to be enabled. Auto-resets to 0.
- maintenance/mqttConnectionState: Last Will and Testament (LWT) topic. "online" when Nuki Hub is connected to the MQTT broker, "offline" if Nuki Hub is not connected to the MQTT broker.
@@ -441,7 +443,7 @@ Updating to version 9.00 requires a change to the partition table of the ESP32.<
Please follow the instructions for the [First time installation](#first-time-installation) once when updating to Nuki Hub 9.00 from an earlier version.
Your settings will not be affected when updating using the above instructions (do not select erase device when updating using Webflash).
-## MQTT Encryption (optional; Wi-Fi and LAN8720 only)
+## MQTT Encryption (optional)
The communication via MQTT can be SSL encrypted.
To enable SSL encryption, supply the necessary information in the MQTT Configuration page.
@@ -607,28 +609,27 @@ To enable GPIO control, go the the "GPIO Configuration" page where each GPIO can
## Connecting via Ethernet (Optional)
-If you prefer to connect to the MQTT Broker via Ethernet instead of Wi-Fi, you either use one of the supported ESP32 modules (see about section above),
-or wire a seperate Wiznet W5x00 Module (W5100, W5200, W5500 are supported). To use a supported module, flash the firmware, connect via Wi-Fi and
-select the correct network hardware in the "MQTT and Network Configuration" section.
+If you prefer to connect to via Ethernet instead of Wi-Fi, you either use one of the supported ESP32 modules with built-in ethernet (see "[Supported devices](#supported-devices)" section)
+or wire a seperate SPI Ethernet module.
+Currently the Wiznet W5x00 Module (W5100, W5200, W5500), DN9051 and KSZ8851SNL chips are supported.
+To use a supported module, flash the firmware, connect via Wi-Fi and select the correct network hardware in the "MQTT and Network Configuration" section.
To wire an external W5x00 module to the ESP, use this wiring scheme:
-- Connect W5x00 to ESP32 SPI0:
- - W5x00 SCK to GPIO18
- - W5x00 MISO to GPIO19
- - W5x00 MOSI to GPIO23
- - W5x00 CS/SS to GPIO5
-- Optionally connect:
- - W5x00 reset to GPIO33
+- Connect W5x00 to ESP32 SPI:
+ - W5x00 SCK to GPIO 8
+ - W5x00 MISO to GPIO 9
+ - W5x00 MOSI to GPIO 10
+ - W5x00 CS/SS to GPIO 5
+ Optional:
+ - W5x00 RST to GPIO 4
+ - W5x00 INT/IRQ to GPIO 3
Now connect via Wi-Fi and change the network hardware to "Generic W5500".
-If the W5500 hwardware isn't detected, Wi-Fi is used as a fallback.
+
+If Ethernet hwardware isn't detected, Wi-Fi is used as a fallback, unless this is disabled in the settings.
-Note: Encrypted MQTT is only available for Wi-Fi and LAN8720 modules, W5x00 modules don't support encryption
-(that leaves Olimex, WT32-ETH01 and M5Stack PoESP32 Unit if encryption is desired).
-Note: LAN8720 modules are only supported on the ESP32, not on the ESP32-S3, ESP32-C3 or ESP-C6
-
-If encryption is needed, Olimex is the easiest option, since it has USB for flashing onboard.
+Note: LAN8720 modules are only supported on the ESP32 and ESP32-Solo1, not on the ESP32-S3, ESP32-C3 or ESP-C6
## Troubleshooting
@@ -716,7 +717,7 @@ source .venv/bin/activate
git clone https://github.com/technyon/nuki_hub --recursive
cd nuki_hub
-# install tools platformio and esptool
+# install tools platformio and esptool
make deps
# build all binary boards
diff --git a/clion/CMakeLists.txt b/clion/CMakeLists.txt
index 9999a1f..1ce88d9 100644
--- a/clion/CMakeLists.txt
+++ b/clion/CMakeLists.txt
@@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.16.0)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(nukihub)
+add_compile_definitions(CONFIG_IDF_TARGET_ESP32)
+
set(SRCFILES
../src/Config.h
../src/NukiDeviceId.cpp
@@ -12,18 +14,17 @@ set(SRCFILES
../src/NukiNetworkOpener.cpp
../src/networkDevices/NetworkDevice.h
../src/networkDevices/NetworkDevice.cpp
+ ../src/networkDevices/LAN8720Definitions.h
+ ../src/networkDevices/DM9051Definitions.h
+ ../src/networkDevices/W5500Definitions.h
../src/networkDevices/WifiDevice.cpp
- ../src/networkDevices/W5500Device.cpp
- ../src/networkDevices/EthLan8720Device.cpp
- ../src/networkDevices/ClientSyncW5500.cpp
- ../src/networkDevices/espMqttClientW5500.cpp
+ ../src/networkDevices/EthernetDevice.cpp
../src/networkDevices/IPConfiguration.cpp
../src/LockActionResult.h
../src/QueryCommand.h
../src/NukiWrapper.cpp
../src/NukiOpenerWrapper.cpp
../src/MqttTopics.h
- ../src/Ota.cpp
../src/WebCfgServerConstants.h
../src/WebCfgServer.cpp
../src/PresenceDetection.cpp
@@ -59,10 +60,8 @@ file(GLOB_RECURSE SRCFILESREC
lib/NimBLE-Arduino/src/*.c
lib/NimBLE-Arduino/src/*.cpp
lib/NimBLE-Arduino/src/*.h
- lib/WebServer/src/*.cpp
- lib/WebServer/src/*.h
- lib/Ethernet/src/*.cpp
- lib/Ethernet/src/*.h
+ lib/ESP Async WebServer/src/*.cpp
+ lib/ESP Async WebServer/src/*.h
lib/espMqttClient/src/*.cpp
lib/espMqttClient/src/*.h
lib/espMqttClient/src/Packets/*.cpp
diff --git a/lib/ESP Async WebServer/CMakeLists.txt b/lib/ESPAsyncWebServer/CMakeLists.txt
similarity index 100%
rename from lib/ESP Async WebServer/CMakeLists.txt
rename to lib/ESPAsyncWebServer/CMakeLists.txt
diff --git a/lib/ESP Async WebServer/LICENSE b/lib/ESPAsyncWebServer/LICENSE
similarity index 100%
rename from lib/ESP Async WebServer/LICENSE
rename to lib/ESPAsyncWebServer/LICENSE
diff --git a/lib/ESP Async WebServer/README.md b/lib/ESPAsyncWebServer/README.md
similarity index 99%
rename from lib/ESP Async WebServer/README.md
rename to lib/ESPAsyncWebServer/README.md
index 19ab602..6ca1d1e 100644
--- a/lib/ESP Async WebServer/README.md
+++ b/lib/ESPAsyncWebServer/README.md
@@ -14,7 +14,7 @@ This fork is based on [yubox-node-org/ESPAsyncWebServer](https://github.com/yubo
**WARNING** The library name was changed from `ESP Async WebServer` to `ESPAsyncWebServer` as per the Arduino Lint recommendations.
```
-mathieucarbou/ESPAsyncWebServer @ 3.1.2
+mathieucarbou/ESPAsyncWebServer @ 3.1.5
```
Dependency:
diff --git a/lib/ESP Async WebServer/docs/_config.yml b/lib/ESPAsyncWebServer/docs/_config.yml
similarity index 100%
rename from lib/ESP Async WebServer/docs/_config.yml
rename to lib/ESPAsyncWebServer/docs/_config.yml
diff --git a/lib/ESP Async WebServer/docs/index.md b/lib/ESPAsyncWebServer/docs/index.md
similarity index 99%
rename from lib/ESP Async WebServer/docs/index.md
rename to lib/ESPAsyncWebServer/docs/index.md
index 19ab602..6ca1d1e 100644
--- a/lib/ESP Async WebServer/docs/index.md
+++ b/lib/ESPAsyncWebServer/docs/index.md
@@ -14,7 +14,7 @@ This fork is based on [yubox-node-org/ESPAsyncWebServer](https://github.com/yubo
**WARNING** The library name was changed from `ESP Async WebServer` to `ESPAsyncWebServer` as per the Arduino Lint recommendations.
```
-mathieucarbou/ESPAsyncWebServer @ 3.1.2
+mathieucarbou/ESPAsyncWebServer @ 3.1.5
```
Dependency:
diff --git a/lib/ESP Async WebServer/examples/CaptivePortal/CaptivePortal.ino b/lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino
similarity index 100%
rename from lib/ESP Async WebServer/examples/CaptivePortal/CaptivePortal.ino
rename to lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino
diff --git a/lib/ESP Async WebServer/examples/Draft/Draft.ino b/lib/ESPAsyncWebServer/examples/Draft/Draft.ino
similarity index 100%
rename from lib/ESP Async WebServer/examples/Draft/Draft.ino
rename to lib/ESPAsyncWebServer/examples/Draft/Draft.ino
diff --git a/lib/ESP Async WebServer/examples/Filters/Filters.ino b/lib/ESPAsyncWebServer/examples/Filters/Filters.ino
similarity index 100%
rename from lib/ESP Async WebServer/examples/Filters/Filters.ino
rename to lib/ESPAsyncWebServer/examples/Filters/Filters.ino
diff --git a/lib/ESP Async WebServer/examples/SimpleServer/SimpleServer.ino b/lib/ESPAsyncWebServer/examples/SimpleServer/SimpleServer.ino
similarity index 100%
rename from lib/ESP Async WebServer/examples/SimpleServer/SimpleServer.ino
rename to lib/ESPAsyncWebServer/examples/SimpleServer/SimpleServer.ino
diff --git a/lib/ESP Async WebServer/examples/StreamFiles/StreamConcat.h b/lib/ESPAsyncWebServer/examples/StreamFiles/StreamConcat.h
similarity index 100%
rename from lib/ESP Async WebServer/examples/StreamFiles/StreamConcat.h
rename to lib/ESPAsyncWebServer/examples/StreamFiles/StreamConcat.h
diff --git a/lib/ESP Async WebServer/examples/StreamFiles/StreamFiles.ino b/lib/ESPAsyncWebServer/examples/StreamFiles/StreamFiles.ino
similarity index 100%
rename from lib/ESP Async WebServer/examples/StreamFiles/StreamFiles.ino
rename to lib/ESPAsyncWebServer/examples/StreamFiles/StreamFiles.ino
diff --git a/lib/ESP Async WebServer/examples/StreamFiles/StreamString.h b/lib/ESPAsyncWebServer/examples/StreamFiles/StreamString.h
similarity index 100%
rename from lib/ESP Async WebServer/examples/StreamFiles/StreamString.h
rename to lib/ESPAsyncWebServer/examples/StreamFiles/StreamString.h
diff --git a/lib/ESP Async WebServer/examples/issues/Issue14/Issue14.ino b/lib/ESPAsyncWebServer/examples/issues/Issue14/Issue14.ino
similarity index 100%
rename from lib/ESP Async WebServer/examples/issues/Issue14/Issue14.ino
rename to lib/ESPAsyncWebServer/examples/issues/Issue14/Issue14.ino
diff --git a/lib/ESP Async WebServer/library.json b/lib/ESPAsyncWebServer/library.json
similarity index 98%
rename from lib/ESP Async WebServer/library.json
rename to lib/ESPAsyncWebServer/library.json
index e2c7953..eb946c6 100644
--- a/lib/ESP Async WebServer/library.json
+++ b/lib/ESPAsyncWebServer/library.json
@@ -1,6 +1,6 @@
{
"name": "ESPAsyncWebServer",
- "version": "3.1.2",
+ "version": "3.1.5",
"description": "Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040. Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc.",
"keywords": "http,async,websocket,webserver",
"homepage": "https://github.com/mathieucarbou/ESPAsyncWebServer",
diff --git a/lib/ESP Async WebServer/library.properties b/lib/ESPAsyncWebServer/library.properties
similarity index 96%
rename from lib/ESP Async WebServer/library.properties
rename to lib/ESPAsyncWebServer/library.properties
index 8c610fd..3036044 100644
--- a/lib/ESP Async WebServer/library.properties
+++ b/lib/ESPAsyncWebServer/library.properties
@@ -1,5 +1,5 @@
name=ESPAsyncWebServer
-version=3.1.2
+version=3.1.5
author=Me-No-Dev
maintainer=Mathieu Carbou
sentence=Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040
diff --git a/lib/ESP Async WebServer/platformio.ini b/lib/ESPAsyncWebServer/platformio.ini
similarity index 88%
rename from lib/ESP Async WebServer/platformio.ini
rename to lib/ESPAsyncWebServer/platformio.ini
index e621af8..6f68d0d 100644
--- a/lib/ESP Async WebServer/platformio.ini
+++ b/lib/ESPAsyncWebServer/platformio.ini
@@ -30,7 +30,7 @@ lib_deps =
mathieucarbou/AsyncTCP @ 3.2.4
[env:arduino-2]
-platform = espressif32@6.7.0
+platform = espressif32@6.8.1
board = esp32dev
lib_deps =
bblanchon/ArduinoJson @ 7.1.0
@@ -39,8 +39,8 @@ lib_deps =
[env:arduino-3]
platform = espressif32
platform_packages=
- platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.3
- platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.3/esp32-arduino-libs-3.0.3.zip
+ platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.4
+ platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.4/esp32-arduino-libs-3.0.4.zip
board = esp32dev
lib_deps =
bblanchon/ArduinoJson @ 7.1.0
@@ -66,14 +66,14 @@ lib_deps =
khoih-prog/AsyncTCP_RP2040W @ 1.2.0
[env:pioarduino-esp32dev]
-platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip
+platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.04/platform-espressif32.zip
board = esp32dev
lib_deps =
bblanchon/ArduinoJson @ 7.1.0
- mathieucarbou/AsyncTCP @ 3.2.3
+ mathieucarbou/AsyncTCP @ 3.2.4
[env:pioarduino-c6]
-platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip
+platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.04/platform-espressif32.zip
board = esp32-c6-devkitc-1
lib_deps =
bblanchon/ArduinoJson @ 7.1.0
diff --git a/lib/ESP Async WebServer/src/AsyncEventSource.cpp b/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp
similarity index 100%
rename from lib/ESP Async WebServer/src/AsyncEventSource.cpp
rename to lib/ESPAsyncWebServer/src/AsyncEventSource.cpp
diff --git a/lib/ESP Async WebServer/src/AsyncEventSource.h b/lib/ESPAsyncWebServer/src/AsyncEventSource.h
similarity index 100%
rename from lib/ESP Async WebServer/src/AsyncEventSource.h
rename to lib/ESPAsyncWebServer/src/AsyncEventSource.h
diff --git a/lib/ESP Async WebServer/src/AsyncJson.h b/lib/ESPAsyncWebServer/src/AsyncJson.h
similarity index 100%
rename from lib/ESP Async WebServer/src/AsyncJson.h
rename to lib/ESPAsyncWebServer/src/AsyncJson.h
diff --git a/lib/ESP Async WebServer/src/AsyncMessagePack.h b/lib/ESPAsyncWebServer/src/AsyncMessagePack.h
similarity index 100%
rename from lib/ESP Async WebServer/src/AsyncMessagePack.h
rename to lib/ESPAsyncWebServer/src/AsyncMessagePack.h
diff --git a/lib/ESP Async WebServer/src/AsyncWebSocket.cpp b/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp
similarity index 100%
rename from lib/ESP Async WebServer/src/AsyncWebSocket.cpp
rename to lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp
diff --git a/lib/ESP Async WebServer/src/AsyncWebSocket.h b/lib/ESPAsyncWebServer/src/AsyncWebSocket.h
similarity index 98%
rename from lib/ESP Async WebServer/src/AsyncWebSocket.h
rename to lib/ESPAsyncWebServer/src/AsyncWebSocket.h
index ee7bde1..34256a7 100644
--- a/lib/ESP Async WebServer/src/AsyncWebSocket.h
+++ b/lib/ESPAsyncWebServer/src/AsyncWebSocket.h
@@ -230,18 +230,12 @@ class AsyncWebSocketClient {
size_t queueLen() const;
size_t printf(const char* format, ...) __attribute__((format(printf, 2, 3)));
-#ifndef ESP32
- size_t printf_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3)));
-#endif
void text(AsyncWebSocketSharedBuffer buffer);
void text(const uint8_t* message, size_t len);
void text(const char* message, size_t len);
void text(const char* message);
void text(const String& message);
-#ifndef ESP32
- void text(const __FlashStringHelper* message);
-#endif // ESP32
void text(AsyncWebSocketMessageBuffer* buffer);
void binary(AsyncWebSocketSharedBuffer buffer);
@@ -249,9 +243,6 @@ class AsyncWebSocketClient {
void binary(const char* message, size_t len);
void binary(const char* message);
void binary(const String& message);
-#ifndef ESP32
- void binary(const __FlashStringHelper* message, size_t len);
-#endif // ESP32
void binary(AsyncWebSocketMessageBuffer* buffer);
bool canSend() const;
@@ -263,6 +254,12 @@ class AsyncWebSocketClient {
void _onTimeout(uint32_t time);
void _onDisconnect();
void _onData(void* pbuf, size_t plen);
+
+#ifdef ESP8266
+ size_t printf_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3)));
+ void text(const __FlashStringHelper* message);
+ void binary(const __FlashStringHelper* message, size_t len);
+#endif
};
using AwsHandshakeHandler = std::function;
@@ -308,17 +305,11 @@ class AsyncWebSocket : public AsyncWebHandler {
void text(uint32_t id, const String& message);
void text(uint32_t id, AsyncWebSocketMessageBuffer* buffer);
void text(uint32_t id, AsyncWebSocketSharedBuffer buffer);
-#ifdef ESP8266
- void text(uint32_t id, const __FlashStringHelper* message);
-#endif // ESP8266
void textAll(const uint8_t* message, size_t len);
void textAll(const char* message, size_t len);
void textAll(const char* message);
void textAll(const String& message);
-#ifdef ESP8266
- void textAll(const __FlashStringHelper* message);
-#endif // ESP8266
void textAll(AsyncWebSocketMessageBuffer* buffer);
void textAll(AsyncWebSocketSharedBuffer buffer);
@@ -326,9 +317,6 @@ class AsyncWebSocket : public AsyncWebHandler {
void binary(uint32_t id, const char* message, size_t len);
void binary(uint32_t id, const char* message);
void binary(uint32_t id, const String& message);
-#ifdef ESP8266
- void binary(uint32_t id, const __FlashStringHelper* message, size_t len);
-#endif // ESP8266
void binary(uint32_t id, AsyncWebSocketMessageBuffer* buffer);
void binary(uint32_t id, AsyncWebSocketSharedBuffer buffer);
@@ -336,9 +324,6 @@ class AsyncWebSocket : public AsyncWebHandler {
void binaryAll(const char* message, size_t len);
void binaryAll(const char* message);
void binaryAll(const String& message);
-#ifdef ESP8266
- void binaryAll(const __FlashStringHelper* message, size_t len);
-#endif // ESP8266
void binaryAll(AsyncWebSocketMessageBuffer* buffer);
void binaryAll(AsyncWebSocketSharedBuffer buffer);
@@ -346,6 +331,10 @@ class AsyncWebSocket : public AsyncWebHandler {
size_t printfAll(const char* format, ...) __attribute__((format(printf, 2, 3)));
#ifdef ESP8266
+ void text(uint32_t id, const __FlashStringHelper* message);
+ void textAll(const __FlashStringHelper* message);
+ void binary(uint32_t id, const __FlashStringHelper* message, size_t len);
+ void binaryAll(const __FlashStringHelper* message, size_t len);
size_t printf_P(uint32_t id, PGM_P formatP, ...) __attribute__((format(printf, 3, 4)));
size_t printfAll_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3)));
#endif
diff --git a/lib/ESP Async WebServer/src/ChunkPrint.h b/lib/ESPAsyncWebServer/src/ChunkPrint.h
similarity index 100%
rename from lib/ESP Async WebServer/src/ChunkPrint.h
rename to lib/ESPAsyncWebServer/src/ChunkPrint.h
diff --git a/lib/ESP Async WebServer/src/ESPAsyncWebServer.h b/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h
similarity index 78%
rename from lib/ESP Async WebServer/src/ESPAsyncWebServer.h
rename to lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h
index f729f7e..de08bc0 100644
--- a/lib/ESP Async WebServer/src/ESPAsyncWebServer.h
+++ b/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h
@@ -35,20 +35,20 @@
#include
#include
#elif defined(TARGET_RP2040)
- #include
#include
- #include
#include
+ #include
+ #include
#else
#error Platform not supported
#endif
#include "literals.h"
-#define ASYNCWEBSERVER_VERSION "3.1.2"
+#define ASYNCWEBSERVER_VERSION "3.1.5"
#define ASYNCWEBSERVER_VERSION_MAJOR 3
#define ASYNCWEBSERVER_VERSION_MINOR 1
-#define ASYNCWEBSERVER_VERSION_REVISION 2
+#define ASYNCWEBSERVER_VERSION_REVISION 5
#define ASYNCWEBSERVER_FORK_mathieucarbou
#ifdef ASYNCWEBSERVER_REGEX
@@ -68,20 +68,20 @@ class AsyncStaticWebHandler;
class AsyncCallbackWebHandler;
class AsyncResponseStream;
-#if defined (TARGET_RP2040)
- typedef enum http_method WebRequestMethod;
+#if defined(TARGET_RP2040)
+typedef enum http_method WebRequestMethod;
#else
#ifndef WEBSERVER_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,
- } WebRequestMethod;
+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,
+} WebRequestMethod;
#endif
#endif
@@ -138,6 +138,7 @@ class AsyncWebHeader {
AsyncWebHeader() = default;
AsyncWebHeader(const AsyncWebHeader&) = default;
+ AsyncWebHeader(const char* name, const char* value) : _name(name), _value(value) {}
AsyncWebHeader(const String& name, const String& value) : _name(name), _value(value) {}
AsyncWebHeader(const String& data) {
if (!data)
@@ -153,7 +154,14 @@ class AsyncWebHeader {
const String& name() const { return _name; }
const String& value() const { return _value; }
- String toString() const { return _name + (char)0x3a + (char)0x20 /*": "*/ + _value + asyncsrv::T_rn; }
+ String toString() const {
+ String str = _name;
+ str.concat((char)0x3a);
+ str.concat((char)0x20);
+ str.concat(_value);
+ str.concat(asyncsrv::T_rn);
+ return str;
+ }
};
/*
@@ -293,14 +301,37 @@ class AsyncWebServerRequest {
void redirect(const String& url) { return redirect(url.c_str()); };
void send(AsyncWebServerResponse* response);
- void send(int code, const String& contentType = String(), const String& content = String());
- void send(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr);
- void send(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr);
- void send(FS& fs, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr);
- void send(File content, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr);
- void send(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr);
- void send(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
- void sendChunked(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+
+ void send(int code, const char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, callback)); }
+ void send(int code, const String& contentType, const String& content = emptyString, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, callback)); }
+
+ void send(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, len, callback)); }
+ void send(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, len, callback)); }
+
+ void send(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) {
+ if (fs.exists(path) || (!download && fs.exists(path + asyncsrv::T__gz))) {
+ send(beginResponse(fs, path, contentType, download, callback));
+ } else
+ send(404);
+ }
+ void send(FS& fs, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { send(fs, path, contentType.c_str(), download, callback); }
+
+ void send(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) {
+ if (content) {
+ send(beginResponse(content, path, contentType, download, callback));
+ } else
+ send(404);
+ }
+ void send(File content, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { send(content, path, contentType.c_str(), download, callback); }
+
+ void send(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(stream, contentType, len, callback)); }
+ void send(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(stream, contentType, len, callback)); }
+
+ void send(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginResponse(contentType, len, callback, templateCallback)); }
+ void send(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginResponse(contentType, len, callback, templateCallback)); }
+
+ void sendChunked(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginChunkedResponse(contentType, callback, templateCallback)); }
+ void sendChunked(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginChunkedResponse(contentType, callback, templateCallback)); }
[[deprecated("Replaced by send(...)")]]
void send_P(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) {
@@ -311,16 +342,33 @@ class AsyncWebServerRequest {
send(code, contentType, content, callback);
}
- AsyncWebServerResponse* beginResponse(int code, const String& contentType = String(), const String& content = String());
- AsyncWebServerResponse* beginResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr);
- AsyncWebServerResponse* beginResponse(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr);
- AsyncWebServerResponse* beginResponse(FS& fs, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr);
- AsyncWebServerResponse* beginResponse(File content, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr);
- AsyncWebServerResponse* beginResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr);
- AsyncWebServerResponse* beginResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
- AsyncWebServerResponse* beginChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
- AsyncResponseStream* beginResponseStream(const String& contentType, size_t bufferSize = 1460);
+#ifdef ESP8266
+ void send(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, callback)); }
+#endif
+ AsyncWebServerResponse* beginResponse(int code, const char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr);
+ AsyncWebServerResponse* beginResponse(int code, const String& contentType, const String& content = emptyString, AwsTemplateProcessor callback = nullptr) { return beginResponse(code, contentType.c_str(), content.c_str(), callback); }
+
+ AsyncWebServerResponse* beginResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr);
+ AsyncWebServerResponse* beginResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { return beginResponse(code, contentType.c_str(), content, len, callback); }
+
+ AsyncWebServerResponse* beginResponse(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
+ AsyncWebServerResponse* beginResponse(FS& fs, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { return beginResponse(fs, path, contentType.c_str(), download, callback); }
+
+ AsyncWebServerResponse* beginResponse(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
+ AsyncWebServerResponse* beginResponse(File content, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { return beginResponse(content, path, contentType.c_str(), download, callback); }
+
+ AsyncWebServerResponse* beginResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr);
+ AsyncWebServerResponse* beginResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) { return beginResponse(stream, contentType.c_str(), len, callback); }
+
+ AsyncWebServerResponse* beginResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+ AsyncWebServerResponse* beginResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { return beginResponse(contentType.c_str(), len, callback, templateCallback); }
+
+ AsyncWebServerResponse* beginChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+ AsyncWebServerResponse* beginChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+
+ AsyncResponseStream* beginResponseStream(const char* contentType, size_t bufferSize = 1460);
+ AsyncResponseStream* beginResponseStream(const String& contentType, size_t bufferSize = 1460) { return beginResponseStream(contentType.c_str(), bufferSize); }
[[deprecated("Replaced by beginResponse(...)")]]
AsyncWebServerResponse* beginResponse_P(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) {
@@ -331,6 +379,10 @@ class AsyncWebServerRequest {
return beginResponse(code, contentType, content, callback);
}
+#ifdef ESP8266
+ AsyncWebServerResponse* beginResponse(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr);
+#endif
+
size_t headers() const; // get header count
// check if header exists
@@ -348,7 +400,8 @@ class AsyncWebServerRequest {
const AsyncWebHeader* getHeader(size_t num) const;
size_t params() const; // get arguments count
- bool hasParam(const String& name, bool post = false, bool file = false) const;
+ bool hasParam(const char* name, bool post = false, bool file = false) const;
+ bool hasParam(const String& name, bool post = false, bool file = false) const { return hasParam(name.c_str(), post, file); };
#ifdef ESP8266
bool hasParam(const __FlashStringHelper* data, bool post = false, bool file = false) const { return hasParam(String(data).c_str(), post, file); };
#endif
@@ -526,8 +579,10 @@ class AsyncWebServerResponse {
virtual ~AsyncWebServerResponse();
virtual void setCode(int code);
virtual void setContentLength(size_t len);
- virtual void setContentType(const String& type);
- virtual void addHeader(const String& name, const String& value);
+ void setContentType(const String& type) { setContentType(type.c_str()); }
+ virtual void setContentType(const char* type);
+ virtual void addHeader(const char* name, const char* value);
+ void addHeader(const String& name, const String& value) { addHeader(name.c_str(), value.c_str()); }
virtual String _assembleHead(uint8_t version);
virtual bool _started() const;
virtual bool _finished() const;
diff --git a/lib/ESP Async WebServer/src/WebAuthentication.cpp b/lib/ESPAsyncWebServer/src/WebAuthentication.cpp
similarity index 100%
rename from lib/ESP Async WebServer/src/WebAuthentication.cpp
rename to lib/ESPAsyncWebServer/src/WebAuthentication.cpp
diff --git a/lib/ESP Async WebServer/src/WebAuthentication.h b/lib/ESPAsyncWebServer/src/WebAuthentication.h
similarity index 100%
rename from lib/ESP Async WebServer/src/WebAuthentication.h
rename to lib/ESPAsyncWebServer/src/WebAuthentication.h
diff --git a/lib/ESP Async WebServer/src/WebHandlerImpl.h b/lib/ESPAsyncWebServer/src/WebHandlerImpl.h
similarity index 100%
rename from lib/ESP Async WebServer/src/WebHandlerImpl.h
rename to lib/ESPAsyncWebServer/src/WebHandlerImpl.h
diff --git a/lib/ESP Async WebServer/src/WebHandlers.cpp b/lib/ESPAsyncWebServer/src/WebHandlers.cpp
similarity index 96%
rename from lib/ESP Async WebServer/src/WebHandlers.cpp
rename to lib/ESPAsyncWebServer/src/WebHandlers.cpp
index 580ceba..d904a39 100644
--- a/lib/ESP Async WebServer/src/WebHandlers.cpp
+++ b/lib/ESPAsyncWebServer/src/WebHandlers.cpp
@@ -231,16 +231,16 @@ void AsyncStaticWebHandler::handleRequest(AsyncWebServerRequest* request) {
} else if (_cache_control.length() && request->hasHeader(T_INM) && request->header(T_INM).equals(etag)) {
request->_tempFile.close();
AsyncWebServerResponse* response = new AsyncBasicResponse(304); // Not modified
- response->addHeader(T_Cache_Control, _cache_control);
- response->addHeader(T_ETag, etag);
+ response->addHeader(T_Cache_Control, _cache_control.c_str());
+ response->addHeader(T_ETag, etag.c_str());
request->send(response);
} else {
AsyncWebServerResponse* response = new AsyncFileResponse(request->_tempFile, filename, String(), false, _callback);
if (_last_modified.length())
- response->addHeader(T_Last_Modified, _last_modified);
+ response->addHeader(T_Last_Modified, _last_modified.c_str());
if (_cache_control.length()) {
- response->addHeader(T_Cache_Control, _cache_control);
- response->addHeader(T_ETag, etag);
+ response->addHeader(T_Cache_Control, _cache_control.c_str());
+ response->addHeader(T_ETag, etag.c_str());
}
request->send(response);
}
diff --git a/lib/ESP Async WebServer/src/WebRequest.cpp b/lib/ESPAsyncWebServer/src/WebRequest.cpp
similarity index 90%
rename from lib/ESP Async WebServer/src/WebRequest.cpp
rename to lib/ESPAsyncWebServer/src/WebRequest.cpp
index f0d6bdf..95fda7e 100644
--- a/lib/ESP Async WebServer/src/WebRequest.cpp
+++ b/lib/ESPAsyncWebServer/src/WebRequest.cpp
@@ -274,7 +274,7 @@ bool AsyncWebServerRequest::_parseReqHead() {
if (!_temp.startsWith(T_HTTP_1_0))
_version = 1;
- _temp = String();
+ _temp = emptyString;
return true;
}
@@ -307,7 +307,7 @@ bool AsyncWebServerRequest::_parseReqHeader() {
if (name.equalsIgnoreCase(T_UPGRADE) && value.equalsIgnoreCase(T_WS)) {
// WebSocket request can be uniquely identified by header: [Upgrade: websocket]
_reqconntype = RCT_WS;
- } else if (name.equalsIgnoreCase(T_ACCEPT)){
+ } else if (name.equalsIgnoreCase(T_ACCEPT)) {
String lowcase(value);
lowcase.toLowerCase();
#ifndef ESP8266
@@ -327,7 +327,7 @@ bool AsyncWebServerRequest::_parseReqHeader() {
_temp.clear();
#else
// Ancient PRI core does not have String::clear() method 8-()
- _temp = String();
+ _temp = emptyString;
#endif
return true;
}
@@ -345,10 +345,10 @@ void AsyncWebServerRequest::_parsePlainPostChar(uint8_t data) {
_params.emplace_back(urlDecode(name), urlDecode(value), true);
#ifndef TARGET_RP2040
- _temp.clear();
+ _temp.clear();
#else
- // Ancient PRI core does not have String::clear() method 8-()
- _temp = String();
+ // Ancient PRI core does not have String::clear() method 8-()
+ _temp = emptyString;
#endif
}
}
@@ -390,10 +390,10 @@ void AsyncWebServerRequest::_parseMultipartPostByte(uint8_t data, bool last) {
if (!_parsedLength) {
_multiParseState = EXPECT_BOUNDARY;
- _temp = String();
- _itemName = String();
- _itemFilename = String();
- _itemType = String();
+ _temp = emptyString;
+ _itemName = emptyString;
+ _itemFilename = emptyString;
+ _itemType = emptyString;
}
if (_multiParseState == WAIT_FOR_RETURN1) {
@@ -450,13 +450,13 @@ void AsyncWebServerRequest::_parseMultipartPostByte(uint8_t data, bool last) {
_itemIsFile = true;
}
}
- _temp = String();
+ _temp = emptyString;
} else {
_multiParseState = WAIT_FOR_RETURN1;
// value starts from here
_itemSize = 0;
_itemStartIndex = _parsedLength;
- _itemValue = String();
+ _itemValue = emptyString;
if (_itemIsFile) {
if (_itemBuffer)
free(_itemBuffer);
@@ -654,9 +654,9 @@ size_t AsyncWebServerRequest::params() const {
return _params.size();
}
-bool AsyncWebServerRequest::hasParam(const String& name, bool post, bool file) const {
+bool AsyncWebServerRequest::hasParam(const char* name, bool post, bool file) const {
for (const auto& p : _params) {
- if (p.name() == name && p.isPost() == post && p.isFile() == file) {
+ if (p.name().equals(name) && p.isPost() == post && p.isFile() == file) {
return true;
}
}
@@ -689,48 +689,52 @@ void AsyncWebServerRequest::addInterestingHeader(const char* name) {
_interestingHeaders.emplace_back(name);
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& contentType, const String& content) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const char* contentType, const char* content, AwsTemplateProcessor callback) {
+ if (callback)
+ return new AsyncProgmemResponse(code, contentType, (const uint8_t*)content, strlen(content), callback);
return new AsyncBasicResponse(code, contentType, content);
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) {
return new AsyncProgmemResponse(code, contentType, content, len, callback);
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback) {
- return new AsyncProgmemResponse(code, contentType, (const uint8_t*)content, strlen_P(content), callback);
-}
-
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(FS& fs, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(FS& fs, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) {
if (fs.exists(path) || (!download && fs.exists(path + T__gz)))
return new AsyncFileResponse(fs, path, contentType, download, callback);
return NULL;
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(File content, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(File content, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) {
if (content == true)
return new AsyncFileResponse(content, path, contentType, download, callback);
return NULL;
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback) {
return new AsyncStreamResponse(stream, contentType, len, callback);
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) {
return new AsyncCallbackResponse(contentType, len, callback, templateCallback);
}
-AsyncWebServerResponse* AsyncWebServerRequest::beginChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) {
+AsyncWebServerResponse* AsyncWebServerRequest::beginChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) {
if (_version)
return new AsyncChunkedResponse(contentType, callback, templateCallback);
return new AsyncCallbackResponse(contentType, 0, callback, templateCallback);
}
-AsyncResponseStream* AsyncWebServerRequest::beginResponseStream(const String& contentType, size_t bufferSize) {
+AsyncResponseStream* AsyncWebServerRequest::beginResponseStream(const char* contentType, size_t bufferSize) {
return new AsyncResponseStream(contentType, bufferSize);
}
+#ifdef ESP8266
+AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback) {
+ return new AsyncProgmemResponse(code, contentType, (const uint8_t*)content, strlen_P(content), callback);
+}
+#endif
+
void AsyncWebServerRequest::send(AsyncWebServerResponse* response) {
_response = response;
if (_response == NULL) {
@@ -748,44 +752,6 @@ void AsyncWebServerRequest::send(AsyncWebServerResponse* response) {
}
}
-void AsyncWebServerRequest::send(int code, const String& contentType, const String& content) {
- send(beginResponse(code, contentType, content));
-}
-
-void AsyncWebServerRequest::send(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) {
- send(beginResponse(code, contentType, content, len, callback));
-}
-
-void AsyncWebServerRequest::send(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback) {
- send(beginResponse(code, contentType, content, callback));
-}
-
-void AsyncWebServerRequest::send(FS& fs, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) {
- if (fs.exists(path) || (!download && fs.exists(path + T__gz))) {
- send(beginResponse(fs, path, contentType, download, callback));
- } else
- send(404);
-}
-
-void AsyncWebServerRequest::send(File content, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) {
- if (content == true) {
- send(beginResponse(content, path, contentType, download, callback));
- } else
- send(404);
-}
-
-void AsyncWebServerRequest::send(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback) {
- send(beginResponse(stream, contentType, len, callback));
-}
-
-void AsyncWebServerRequest::send(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) {
- send(beginResponse(contentType, len, callback, templateCallback));
-}
-
-void AsyncWebServerRequest::sendChunked(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) {
- send(beginChunkedResponse(contentType, callback, templateCallback));
-}
-
void AsyncWebServerRequest::redirect(const char* url) {
AsyncWebServerResponse* response = beginResponse(302);
response->addHeader(T_LOCATION, url);
@@ -834,11 +800,11 @@ void AsyncWebServerRequest::requestAuthentication(const char* realm, bool isDige
String header(T_BASIC_REALM);
header.concat(realm);
header += '"';
- r->addHeader(T_WWW_AUTH, header);
+ r->addHeader(T_WWW_AUTH, header.c_str());
} else {
String header(T_DIGEST_);
header.concat(requestDigestAuthentication(realm));
- r->addHeader(T_WWW_AUTH, header);
+ r->addHeader(T_WWW_AUTH, header.c_str());
}
send(r);
}
@@ -949,7 +915,7 @@ const char* AsyncWebServerRequest::methodToString() const {
return T_OPTIONS;
return T_UNKNOWN;
}
-#else // ESP8266
+#else // ESP8266
const __FlashStringHelper* AsyncWebServerRequest::methodToString() const {
if (_method == HTTP_ANY)
return FPSTR(T_ANY);
@@ -988,7 +954,7 @@ const char* AsyncWebServerRequest::requestedConnTypeToString() const {
return T_ERROR;
}
}
-#else // ESP8266
+#else // ESP8266
const __FlashStringHelper* AsyncWebServerRequest::requestedConnTypeToString() const {
switch (_reqconntype) {
case RCT_NOT_USED:
diff --git a/lib/ESP Async WebServer/src/WebResponseImpl.h b/lib/ESPAsyncWebServer/src/WebResponseImpl.h
similarity index 71%
rename from lib/ESP Async WebServer/src/WebResponseImpl.h
rename to lib/ESPAsyncWebServer/src/WebResponseImpl.h
index 26ec223..a6f71bb 100644
--- a/lib/ESP Async WebServer/src/WebResponseImpl.h
+++ b/lib/ESPAsyncWebServer/src/WebResponseImpl.h
@@ -28,6 +28,7 @@
#endif
#include
#include
+#include "literals.h"
// It is possible to restore these defines, but one can use _min and _max instead. Or std::min, std::max.
@@ -36,7 +37,8 @@ class AsyncBasicResponse : public AsyncWebServerResponse {
String _content;
public:
- AsyncBasicResponse(int code, const String& contentType = String(), const String& content = String());
+ explicit AsyncBasicResponse(int code, const char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty);
+ AsyncBasicResponse(int code, const String& contentType, const String& content = emptyString) : AsyncBasicResponse(code, contentType.c_str(), content.c_str()) {}
void _respond(AsyncWebServerRequest* request);
size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time);
bool _sourceValid() const { return true; }
@@ -76,11 +78,13 @@ class AsyncFileResponse : public AsyncAbstractResponse {
private:
File _content;
String _path;
- void _setContentType(const String& path);
+ void _setContentTypeFromPath(const String& path);
public:
- AsyncFileResponse(FS& fs, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr);
- AsyncFileResponse(File content, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr);
+ AsyncFileResponse(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
+ AsyncFileResponse(FS& fs, const String& path, const String& contentType, bool download = false, AwsTemplateProcessor callback = nullptr) : AsyncFileResponse(fs, path, contentType.c_str(), download, callback) {}
+ AsyncFileResponse(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
+ AsyncFileResponse(File content, const String& path, const String& contentType, bool download = false, AwsTemplateProcessor callack = nullptr) : AsyncFileResponse(content, path, contentType.c_str(), download, callack) {}
~AsyncFileResponse();
bool _sourceValid() const { return !!(_content); }
virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override;
@@ -91,7 +95,8 @@ class AsyncStreamResponse : public AsyncAbstractResponse {
Stream* _content;
public:
- AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr);
+ AsyncStreamResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr);
+ AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) : AsyncStreamResponse(stream, contentType.c_str(), len, callback) {}
bool _sourceValid() const { return !!(_content); }
virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override;
};
@@ -102,7 +107,8 @@ class AsyncCallbackResponse : public AsyncAbstractResponse {
size_t _filledLength;
public:
- AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+ AsyncCallbackResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+ AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) : AsyncCallbackResponse(contentType.c_str(), len, callback, templateCallback) {}
bool _sourceValid() const { return !!(_content); }
virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override;
};
@@ -113,7 +119,8 @@ class AsyncChunkedResponse : public AsyncAbstractResponse {
size_t _filledLength;
public:
- AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+ AsyncChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
+ AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) : AsyncChunkedResponse(contentType.c_str(), callback, templateCallback) {}
bool _sourceValid() const { return !!(_content); }
virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override;
};
@@ -124,7 +131,8 @@ class AsyncProgmemResponse : public AsyncAbstractResponse {
size_t _readLength;
public:
- AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr);
+ AsyncProgmemResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr);
+ AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) : AsyncProgmemResponse(code, contentType.c_str(), content, len, callback) {}
bool _sourceValid() const { return true; }
virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override;
};
@@ -136,7 +144,8 @@ class AsyncResponseStream : public AsyncAbstractResponse, public Print {
std::unique_ptr _content;
public:
- AsyncResponseStream(const String& contentType, size_t bufferSize);
+ AsyncResponseStream(const char* contentType, size_t bufferSize);
+ AsyncResponseStream(const String& contentType, size_t bufferSize) : AsyncResponseStream(contentType.c_str(), bufferSize) {}
~AsyncResponseStream();
bool _sourceValid() const { return (_state < RESPONSE_END); }
virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override;
diff --git a/lib/ESP Async WebServer/src/WebResponses.cpp b/lib/ESPAsyncWebServer/src/WebResponses.cpp
similarity index 94%
rename from lib/ESP Async WebServer/src/WebResponses.cpp
rename to lib/ESPAsyncWebServer/src/WebResponses.cpp
index 86aa947..f1994b1 100644
--- a/lib/ESP Async WebServer/src/WebResponses.cpp
+++ b/lib/ESPAsyncWebServer/src/WebResponses.cpp
@@ -234,12 +234,12 @@ void AsyncWebServerResponse::setContentLength(size_t len) {
_contentLength = len;
}
-void AsyncWebServerResponse::setContentType(const String& type) {
+void AsyncWebServerResponse::setContentType(const char* type) {
if (_state == RESPONSE_SETUP)
_contentType = type;
}
-void AsyncWebServerResponse::addHeader(const String& name, const String& value) {
+void AsyncWebServerResponse::addHeader(const char* name, const char* value) {
_headers.emplace_back(name, value);
}
@@ -298,7 +298,7 @@ size_t AsyncWebServerResponse::_ack(AsyncWebServerRequest* request, size_t len,
/*
* String/Code Response
* */
-AsyncBasicResponse::AsyncBasicResponse(int code, const String& contentType, const String& content) {
+AsyncBasicResponse::AsyncBasicResponse(int code, const char* contentType, const char* content) {
_code = code;
_content = content;
_contentType = contentType;
@@ -353,7 +353,7 @@ size_t AsyncBasicResponse::_ack(AsyncWebServerRequest* request, size_t len, uint
// we can fit in this packet
if (space > available) {
_writtenLength += request->client()->write(_content.c_str(), available);
- _content = String();
+ _content = emptyString;
_state = RESPONSE_WAIT_ACK;
return available;
}
@@ -465,7 +465,7 @@ size_t AsyncAbstractResponse::_ack(AsyncWebServerRequest* request, size_t len, u
}
if (headLen) {
- _head = String();
+ _head = emptyString;
}
if (outLen) {
@@ -607,7 +607,7 @@ AsyncFileResponse::~AsyncFileResponse() {
_content.close();
}
-void AsyncFileResponse::_setContentType(const String& path) {
+void AsyncFileResponse::_setContentTypeFromPath(const String& path) {
#if HAVE_EXTERN_GET_Content_Type_FUNCTION
#ifndef ESP8266
extern const char* getContentType(const String& path);
@@ -657,7 +657,7 @@ void AsyncFileResponse::_setContentType(const String& path) {
#endif
}
-AsyncFileResponse::AsyncFileResponse(FS& fs, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
+AsyncFileResponse::AsyncFileResponse(FS& fs, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
_code = 200;
_path = path;
@@ -672,8 +672,8 @@ AsyncFileResponse::AsyncFileResponse(FS& fs, const String& path, const String& c
_content = fs.open(_path, fs::FileOpenMode::read);
_contentLength = _content.size();
- if (contentType.length() == 0)
- _setContentType(path);
+ if (strlen(contentType) == 0)
+ _setContentTypeFromPath(path);
else
_contentType = contentType;
@@ -691,7 +691,7 @@ AsyncFileResponse::AsyncFileResponse(FS& fs, const String& path, const String& c
addHeader(T_Content_Disposition, buf);
}
-AsyncFileResponse::AsyncFileResponse(File content, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
+AsyncFileResponse::AsyncFileResponse(File content, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
_code = 200;
_path = path;
@@ -705,8 +705,8 @@ AsyncFileResponse::AsyncFileResponse(File content, const String& path, const Str
_content = content;
_contentLength = _content.size();
- if (contentType.length() == 0)
- _setContentType(path);
+ if (strlen(contentType) == 0)
+ _setContentTypeFromPath(path);
else
_contentType = contentType;
@@ -730,7 +730,7 @@ size_t AsyncFileResponse::_fillBuffer(uint8_t* data, size_t len) {
* Stream Response
* */
-AsyncStreamResponse::AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
+AsyncStreamResponse::AsyncStreamResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
_code = 200;
_content = &stream;
_contentLength = len;
@@ -750,7 +750,7 @@ size_t AsyncStreamResponse::_fillBuffer(uint8_t* data, size_t len) {
* Callback Response
* */
-AsyncCallbackResponse::AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) : AsyncAbstractResponse(templateCallback) {
+AsyncCallbackResponse::AsyncCallbackResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) : AsyncAbstractResponse(templateCallback) {
_code = 200;
_content = callback;
_contentLength = len;
@@ -772,7 +772,7 @@ size_t AsyncCallbackResponse::_fillBuffer(uint8_t* data, size_t len) {
* Chunked Response
* */
-AsyncChunkedResponse::AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor processorCallback) : AsyncAbstractResponse(processorCallback) {
+AsyncChunkedResponse::AsyncChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor processorCallback) : AsyncAbstractResponse(processorCallback) {
_code = 200;
_content = callback;
_contentLength = 0;
@@ -794,7 +794,7 @@ size_t AsyncChunkedResponse::_fillBuffer(uint8_t* data, size_t len) {
* Progmem Response
* */
-AsyncProgmemResponse::AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
+AsyncProgmemResponse::AsyncProgmemResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) {
_code = code;
_content = content;
_contentType = contentType;
@@ -818,7 +818,7 @@ size_t AsyncProgmemResponse::_fillBuffer(uint8_t* data, size_t len) {
* Response Stream (You can print/write/printf to it, up to the contentLen bytes)
* */
-AsyncResponseStream::AsyncResponseStream(const String& contentType, size_t bufferSize) {
+AsyncResponseStream::AsyncResponseStream(const char* contentType, size_t bufferSize) {
_code = 200;
_contentLength = 0;
_contentType = contentType;
diff --git a/lib/ESP Async WebServer/src/WebServer.cpp b/lib/ESPAsyncWebServer/src/WebServer.cpp
similarity index 97%
rename from lib/ESP Async WebServer/src/WebServer.cpp
rename to lib/ESPAsyncWebServer/src/WebServer.cpp
index 0e29a54..d7c9a02 100644
--- a/lib/ESP Async WebServer/src/WebServer.cpp
+++ b/lib/ESPAsyncWebServer/src/WebServer.cpp
@@ -24,11 +24,19 @@
using namespace asyncsrv;
bool ON_STA_FILTER(AsyncWebServerRequest* request) {
+ #ifndef CONFIG_IDF_TARGET_ESP32H2
return WiFi.localIP() == request->client()->localIP();
+ #else
+ return false;
+ #endif
}
bool ON_AP_FILTER(AsyncWebServerRequest* request) {
+ #ifndef CONFIG_IDF_TARGET_ESP32H2
return WiFi.localIP() != request->client()->localIP();
+ #else
+ return false;
+ #endif
}
#ifndef HAVE_FS_FILE_OPEN_MODE
diff --git a/lib/ESP Async WebServer/src/literals.h b/lib/ESPAsyncWebServer/src/literals.h
similarity index 99%
rename from lib/ESP Async WebServer/src/literals.h
rename to lib/ESPAsyncWebServer/src/literals.h
index c60a3eb..8a7293b 100644
--- a/lib/ESP Async WebServer/src/literals.h
+++ b/lib/ESPAsyncWebServer/src/literals.h
@@ -2,6 +2,8 @@
namespace asyncsrv {
+static constexpr const char* empty = "";
+
#ifndef ESP8622
static constexpr const char* T_100_CONTINUE = "100-continue";
static constexpr const char* T_ACCEPT = "Accept";
diff --git a/lib/ESP Async WebServer/src/port/SHA1Builder.cpp b/lib/ESPAsyncWebServer/src/port/SHA1Builder.cpp
similarity index 100%
rename from lib/ESP Async WebServer/src/port/SHA1Builder.cpp
rename to lib/ESPAsyncWebServer/src/port/SHA1Builder.cpp
diff --git a/lib/ESP Async WebServer/src/port/SHA1Builder.h b/lib/ESPAsyncWebServer/src/port/SHA1Builder.h
similarity index 100%
rename from lib/ESP Async WebServer/src/port/SHA1Builder.h
rename to lib/ESPAsyncWebServer/src/port/SHA1Builder.h
diff --git a/lib/Ethernet/.codespellrc b/lib/Ethernet/.codespellrc
deleted file mode 100644
index a231f49..0000000
--- a/lib/Ethernet/.codespellrc
+++ /dev/null
@@ -1,7 +0,0 @@
-# See: https://github.com/codespell-project/codespell#using-a-config-file
-[codespell]
-# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here:
-ignore-words-list = nd,
-check-filenames =
-check-hidden =
-skip = ./.git
diff --git a/lib/Ethernet/AUTHORS b/lib/Ethernet/AUTHORS
deleted file mode 100644
index 1faeec4..0000000
--- a/lib/Ethernet/AUTHORS
+++ /dev/null
@@ -1,36 +0,0 @@
-Alberto Panu https://github.com/bigjohnson
-Alasdair Allan https://github.com/aallan
-Alice Pintus https://github.com/00alis
-Adrian McEwen https://github.com/amcewen
-Arduino LLC https://arduino.cc/
-Arnie97 https://github.com/Arnie97
-Arturo Guadalupi https://github.com/agdl
-Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/
-chaveiro https://github.com/chaveiro
-Cristian Maglie https://github.com/cmaglie
-David A. Mellis https://github.com/damellis
-Dino Tinitigan https://github.com/bigdinotech
-Eddy https://github.com/eddyst
-Federico Vanzati https://github.com/Fede85
-Federico Fissore https://github.com/ffissore
-Jack Christensen https://github.com/JChristensen
-Johann Richard https://github.com/johannrichard
-Jordan Terrell https://github.com/iSynaptic
-Justin Paulin https://github.com/interwho
-lathoub https://github.com/lathoub
-Martino Facchin https://github.com/facchinm
-Matthias Hertel https://github.com/mathertel
-Matthijs Kooijman https://github.com/matthijskooijman
-Matt Robinson https://github.com/ribbons
-MCQN Ltd. http://mcqn.com/
-Michael Amie https://github.com/michaelamie
-Michael Margolis https://github.com/michaelmargolis
-Norbert Truchsess https://github.com/ntruchsess
-Paul Stoffregen https://github.com/PaulStoffregen
-per1234 https://github.com/per1234
-Richard Sim
-Scott Fitzgerald https://github.com/shfitz
-Thibaut Viard https://github.com/aethaniel
-Tom Igoe https://github.com/tigoe
-WIZnet http://www.wiznet.co.kr
-Zach Eveland https://github.com/zeveland
diff --git a/lib/Ethernet/README.adoc b/lib/Ethernet/README.adoc
deleted file mode 100644
index ed937b1..0000000
--- a/lib/Ethernet/README.adoc
+++ /dev/null
@@ -1,31 +0,0 @@
-:repository-owner: arduino-libraries
-:repository-name: Ethernet
-
-= {repository-name} Library for Arduino =
-
-image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg["Check Arduino status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml"]
-image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg["Compile Examples status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml"]
-image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg["Spell Check status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml"]
-
-With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet.
-
-For more information about this library please visit us at
-https://www.arduino.cc/en/Reference/{repository-name}
-
-== License ==
-
-Copyright (c) 2010 Arduino LLC. All right 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
diff --git a/lib/Ethernet/docs/api.md b/lib/Ethernet/docs/api.md
deleted file mode 100644
index 76265c8..0000000
--- a/lib/Ethernet/docs/api.md
+++ /dev/null
@@ -1,2607 +0,0 @@
-# Ethernet Library
-
-## Ethernet Class
-
-### `Ethernet.begin()`
-
-#### Description
-
-Initializes the Ethernet library and network settings.
-
-With version 1.0, the library supports DHCP. Using Ethernet.begin(mac) with the proper network setup, the Ethernet shield will automatically obtain an IP address. This increases the sketch size significantly. To make sure the DHCP lease is properly renewed when needed, be sure to call Ethernet.maintain() regularly.
-
-
-#### Syntax
-
-```
-Ethernet.begin(mac);
-Ethernet.begin(mac, ip);
-Ethernet.begin(mac, ip, dns);
-Ethernet.begin(mac, ip, dns, gateway);
-Ethernet.begin(mac, ip, dns, gateway, subnet);
-```
-
-#### Parameters
-- mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.
-- ip: the IP address of the device (array of 4 bytes)
-- dns: the IP address of the DNS server (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1
-- gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1
-- subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0
-
-#### Returns
-- The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure.
-- The other versions don't return anything.
-
-#### Example
-
-```
-#include
-#include
-
-// the media access control (ethernet hardware) address for the shield:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-//the IP address for the shield:
-byte ip[] = { 10, 0, 0, 177 };
-
-void setup()
-{
- Ethernet.begin(mac, ip);
-}
-
-void loop () {}
-```
-
-### `Ethernet.dnsServerIP()`
-
-#### Description
-
-Returns the DNS server IP address for the device.
-
-
-#### Syntax
-
-```
-Ethernet.dnsServerIP()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the DNS server IP address for the device (IPAddress).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- Ethernet.begin(mac, ip);
-
- Serial.print("The DNS server IP address is: ");
- Serial.println(Ethernet.dnsServerIP());
-}
-
-void loop () {}
-```
-
-### `Ethernet.gatewayIP()`
-
-#### Description
-
-Returns the gateway IP address for the device.
-
-
-#### Syntax
-
-```
-Ethernet.gatewayIP()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the gateway IP address for the device (IPAddress).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- Ethernet.begin(mac, ip);
-
- Serial.print("The gateway IP address is: ");
- Serial.println(Ethernet.gatewayIP());
-}
-
-void loop () {}
-```
-
-### `Ethernet.hardwareStatus()`
-
-#### Description
-
-Ethernet.hardwareStatus() tells you which WIZnet Ethernet controller chip was detected during Ethernet.begin(), if any. This can be used for troubleshooting. If no Ethernet controller was detected then there is likely a hardware problem.
-
-
-#### Syntax
-
-```
-Ethernet.hardwareStatus()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- which WIZnet Ethernet controller chip was detected during Ethernet.begin() (EthernetHardwareStatus):
-
-```
-EthernetNoHardware
-EthernetW5100
-EthernetW5200
-EthernetW5500
-```
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- Ethernet.begin(mac, ip);
-
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found.");
- }
- else if (Ethernet.hardwareStatus() == EthernetW5100) {
- Serial.println("W5100 Ethernet controller detected.");
- }
- else if (Ethernet.hardwareStatus() == EthernetW5200) {
- Serial.println("W5200 Ethernet controller detected.");
- }
- else if (Ethernet.hardwareStatus() == EthernetW5500) {
- Serial.println("W5500 Ethernet controller detected.");
- }
-}
-
-void loop () {}
-```
-
-### `Ethernet.init()`
-
-#### Description
-
-Used to configure the CS (chip select) pin for the Ethernet controller chip. The Ethernet library has a default CS pin, which is usually correct, but with some non-standard Ethernet hardware you might need to use a different CS pin.
-
-
-#### Syntax
-
-```
-Ethernet.init(sspin)
-
-```
-
-#### Parameters
-- sspin: the pin number to use for CS (byte)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Ethernet.init(53); // use pin 53 for Ethernet CS
- Ethernet.begin(mac, ip);
-}
-
-void loop () {}
-```
-
-### `Ethernet.linkStatus()`
-
-#### Description
-
-Tells you whether the link is active. LinkOFF could indicate the Ethernet cable is unplugged or defective. This feature is only available when using the W5200 and W5500 Ethernet controller chips.
-
-
-#### Syntax
-
-```
-Ethernet.linkStatus()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the link status (EthernetLinkStatus):
-
-- Unknown
-
-- LinkON
-
-- LinkOFF
-
-#### Example
-
-```
-#include
-#include
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-}
-
-void loop () {
- if (Ethernet.linkStatus() == Unknown) {
- Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500.");
- }
- else if (Ethernet.linkStatus() == LinkON) {
- Serial.println("Link status: On");
- }
- else if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Link status: Off");
- }
-}
-```
-
-### `Ethernet.localIP()`
-
-#### Description
-
-Obtains the IP address of the Ethernet shield. Useful when the address is auto assigned through DHCP.
-
-
-#### Syntax
-
-```
-Ethernet.localIP();
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the IP address
-
-#### Example
-
-```
-#include
-#include
-
-// Enter a MAC address for your controller below.
-// Newer Ethernet shields have a MAC address printed on a sticker on the shield
-byte mac[] = {
- 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
-
-// Initialize the Ethernet client library
-// with the IP address and port of the server
-// that you want to connect to (port 80 is default for HTTP):
-EthernetClient client;
-
-void setup() {
- // start the serial library:
- Serial.begin(9600);
- // start the Ethernet connection:
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- // no point in carrying on, so do nothing forevermore:
- for(;;)
- ;
- }
- // print your local IP address:
- Serial.println(Ethernet.localIP());
-
-}
-
-void loop() {
-
-}
-```
-
-### `Ethernet.MACAddress()`
-
-#### Description
-
-Fills the supplied buffer with the MAC address of the device.
-
-
-#### Syntax
-
-```
-Ethernet.MACAddress(mac_address)
-
-```
-
-#### Parameters
-- mac_address: buffer to receive the MAC address (array of 6 bytes)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- Ethernet.begin(mac, ip);
-
- byte macBuffer[6]; // create a buffer to hold the MAC address
- Ethernet.MACAddress(macBuffer); // fill the buffer
- Serial.print("The MAC address is: ");
- for (byte octet = 0; octet < 6; octet++) {
- Serial.print(macBuffer[octet], HEX);
- if (octet < 5) {
- Serial.print('-');
- }
- }
-}
-
-void loop () {}
-
-```
-
-### `Ethernet.maintain()`
-
-#### Description
-
-Allows for the renewal of DHCP leases. When assigned an IP address via DHCP, ethernet devices are given a lease on the address for an amount of time. With Ethernet.maintain(), it is possible to request a renewal from the DHCP server. Depending on the server's configuration, you may receive the same address, a new one, or none at all.
-
-You can call this function as often as you want, it will only re-request a DHCP lease when needed (returning 0 in all other cases). The easiest way is to just call it on every loop() invocation, but less often is also fine. Not calling this function (or calling it significantly less then once per second) will prevent the lease to be renewed when the DHCP protocol requires this, continuing to use the expired lease instead (which will not directly break connectivity, but if the DHCP server leases the same address to someone else, things will likely break).
-
-Ethernet.maintain() was added to Arduino 1.0.1.
-
-
-#### Syntax
-
-```
-Ethernet.maintain();
-
-```
-
-#### Parameters
-none
-
-#### Returns
-
-byte:
-
-- 0: nothing happened
-
-- 1: renew failed
-
-- 2: renew success
-
-- 3: rebind fail
-
-- 4: rebind success
-
-### `Ethernet.setDnsServerIP()`
-
-#### Description
-
-Set the IP address of the DNS server. Not for use with DHCP.
-
-
-#### Syntax
-
-```
-Ethernet.setDnsServerIP(dns_server)
-
-```
-
-#### Parameters
-- dns_server: the IP address of the DNS server (IPAddress)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-IPAddress myDns(192, 168, 1, 1);
-
-void setup() {
- Ethernet.begin(mac, ip, myDns);
- IPAddress newDns(192, 168, 1, 1);
- Ethernet.setDnsServerIP(newDns); // change the DNS server IP address
-}
-
-void loop () {}
-```
-
-### `Ethernet.setGatewayIP()`
-
-#### Description
-
-Set the IP address of the network gateway. Not for use with DHCP.
-
-
-#### Syntax
-
-```
-Ethernet.setGatewayIP(gateway)
-
-```
-
-#### Parameters
-- gateway: the IP address of the network gateway (IPAddress)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-IPAddress myDns(192, 168, 1, 1);
-IPAddress gateway(192, 168, 1, 1);
-
-void setup() {
- Ethernet.begin(mac, ip, myDns, gateway);
- IPAddress newGateway(192, 168, 100, 1);
- Ethernet.setGatewayIP(newGateway); // change the gateway IP address
-}
-
-void loop () {}
-```
-
-### `Ethernet.setLocalIP()`
-
-#### Description
-
-Set the IP address of the device. Not for use with DHCP.
-
-
-#### Syntax
-
-```
-Ethernet.setLocalIP(local_ip)
-
-```
-
-#### Parameters
-- local_ip: the IP address to use (IPAddress)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Ethernet.begin(mac, ip);
- IPAddress newIp(10, 0, 0, 178);
- Ethernet.setLocalIP(newIp); // change the IP address
-}
-
-void loop () {}
-```
-
-### `Ethernet.setMACAddress()`
-
-#### Description
-
-Set the MAC address. Not for use with DHCP.
-
-
-#### Syntax
-
-```
-Ethernet.setMACAddress(mac)
-
-```
-
-#### Parameters
-- mac: the MAC address to use (array of 6 bytes)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Ethernet.begin(mac, ip);
- byte newMac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02};
- Ethernet.setMACAddress(newMac); // change the MAC address
-}
-
-void loop () {}
-```
-
-### `Ethernet.setRetransmissionCount()`
-
-#### Description
-
-Set the number of transmission attempts the Ethernet controller will make before giving up. The initial value is 8. 8 transmission attempts times the 200 ms default timeout equals a blocking delay of 1600 ms during a communications failure. You might prefer to set a lower number to make your program more responsive in the event something goes wrong with communications. Despite the name, this sets the total number of transmission attempts (not the number of retries after the first attempt fails) so the minimum value you would ever want to set is 1.
-
-
-#### Syntax
-
-```
-Ethernet.setRetransmissionCount(number)
-
-```
-
-#### Parameters
-- number: number of transmission attempts the Ethernet controller should make before giving up (byte)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Ethernet.begin(mac, ip);
- Ethernet.setRetransmissionCount(1); // configure the Ethernet controller to only attempt one transmission before giving up
-}
-
-void loop () {}
-```
-
-### `Ethernet.setRetransmissionTimeout()`
-
-#### Description
-
-Set the Ethernet controller's timeout. The initial value is 200 ms. A 200 ms timeout times the default of 8 attempts equals a blocking delay of 1600 ms during a communications failure. You might prefer to set a shorter timeout to make your program more responsive in the event something goes wrong with communications. You will need to do some experimentation to determine an appropriate value for your specific application.
-
-
-#### Syntax
-
-```
-Ethernet.setRetransmissionTimeout(milliseconds)
-
-```
-
-#### Parameters
-- milliseconds: the timeout duration (uint16_t)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Ethernet.begin(mac, ip);
- Ethernet.setRetransmissionTimeout(50); // set the Ethernet controller's timeout to 50 ms
-}
-
-void loop () {}
-```
-
-### `Ethernet.setSubnetMask()`
-
-#### Description
-
-Set the subnet mask of the network. Not for use with DHCP.
-
-
-#### Syntax
-
-```
-Ethernet.setSubnetMask(subnet)
-
-```
-
-#### Parameters
-- subnet: the subnet mask of the network (IPAddress)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-IPAddress myDns(192, 168, 1, 1);
-IPAddress gateway(192, 168, 1, 1);
-IPAddress subnet(255, 255, 0, 0);
-
-void setup() {
- Ethernet.begin(mac, ip, myDns, gateway, subnet);
- IPAddress newSubnet(255, 255, 255, 0);
- Ethernet.setSubnetMask(newSubnet); // change the subnet mask
-}
-
-void loop () {}
-```
-
-### `Ethernet.subnetMask()`
-
-#### Description
-
-Returns the subnet mask of the device.
-
-
-#### Syntax
-
-```
-Ethernet.subnetMask()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the subnet mask of the device (IPAddress)
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- Ethernet.begin(mac, ip);
-
- Serial.print("The subnet mask is: ");
- Serial.println(Ethernet.subnetMask());
-}
-
-void loop () {}
-```
-
-## IPAddress Class
-
-### `IPAddress()`
-
-#### Description
-
-Defines an IP address. It can be used to declare both local and remote addresses.
-
-
-#### Syntax
-
-```
-IPAddress(address);
-
-```
-
-#### Parameters
-- address: a comma delimited list representing the address (4 bytes, ex. 192, 168, 1, 1)
-
-#### Returns
-None
-
-#### Example
-
-```
-#include
-#include
-
-// network configuration. dns server, gateway and subnet are optional.
-
- // the media access control (ethernet hardware) address for the shield:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-
-// the dns server ip
-IPAddress dnServer(192, 168, 0, 1);
-// the router's gateway address:
-IPAddress gateway(192, 168, 0, 1);
-// the subnet:
-IPAddress subnet(255, 255, 255, 0);
-
-//the IP address is dependent on your network
-IPAddress ip(192, 168, 0, 2);
-
-void setup() {
- Serial.begin(9600);
-
- // initialize the ethernet device
- Ethernet.begin(mac, ip, dnServer, gateway, subnet);
- //print out the IP address
- Serial.print("IP = ");
- Serial.println(Ethernet.localIP());
-}
-
-void loop() {
-}
-```
-
-## Server Class
-
-### `Server`
-
-#### Description
-Server is the base class for all Ethernet server based calls. It is not called directly, but invoked whenever you use a function that relies on it.
-
-### `EthernetServer()`
-
-#### Description
-
-Create a server that listens for incoming connections on the specified port.
-
-
-#### Syntax
-
-```
-Server(port);
-
-```
-
-#### Parameters
-- port: the port to listen on (int)
-
-#### Returns
-None
-
-#### Example
-
-```
-#include
-#include
-
-// network configuration. gateway and subnet are optional.
-
- // the media access control (ethernet hardware) address for the shield:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-//the IP address for the shield:
-byte ip[] = { 10, 0, 0, 177 };
-// the router's gateway address:
-byte gateway[] = { 10, 0, 0, 1 };
-// the subnet:
-byte subnet[] = { 255, 255, 0, 0 };
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup()
-{
- // initialize the ethernet device
- Ethernet.begin(mac, ip, gateway, subnet);
-
- // start listening for clients
- server.begin();
-}
-
-void loop()
-{
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client == true) {
- // read bytes from the incoming client and write them back
- // to any clients connected to the server:
- server.write(client.read());
- }
-}
-```
-
-### `server.begin()`
-
-#### Description
-
-Tells the server to begin listening for incoming connections.
-
-
-#### Syntax
-
-```
-server.begin()
-
-```
-
-#### Parameters
-None
-
-#### Returns
-None
-
-#### Example
-
-```
-#include
-#include
-
-// the media access control (ethernet hardware) address for the shield:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-//the IP address for the shield:
-byte ip[] = { 10, 0, 0, 177 };
-// the router's gateway address:
-byte gateway[] = { 10, 0, 0, 1 };
-// the subnet:
-byte subnet[] = { 255, 255, 0, 0 };
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup()
-{
- // initialize the ethernet device
- Ethernet.begin(mac, ip, gateway, subnet);
-
- // start listening for clients
- server.begin();
-}
-
-void loop()
-{
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client == true) {
- // read bytes from the incoming client and write them back
- // to any clients connected to the server:
- server.write(client.read());
- }
-}
-```
-
-### `server.accept()`
-
-#### Description
-
-The traditional server.available() function would only tell you of a new client after it sent data, which makes some protocols like FTP impossible to properly implement.
-
-The intention is programs will use either available() or accept(), but not both. With available(), the client connection continues to be managed by EthernetServer. You don’t need to keep a client object, since calling available() will give you whatever client has sent data. Simple servers can be written with very little code using available().
-
-With accept(), EthernetServer gives you the client only once, regardless of whether it has sent any data. You must keep track of the connected clients. This requires more code, but you gain more control.
-
-
-#### Syntax
-
-```
-server.accept()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- a Client object. If no client has data available for reading, this object will evaluate to false in an if-statement. (EthernetClient).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(192, 168, 69, 104);
-
-// telnet defaults to port 23
-EthernetServer server(23);
-
-EthernetClient clients[8];
-
-void setup() {
- Ethernet.begin(mac, ip);
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- // check for any new client connecting, and say hello (before any incoming data)
- EthernetClient newClient = server.accept();
- if (newClient) {
- for (byte i = 0; i < 8; i++) {
- if (!clients[i]) {
- newClient.print("Hello, client number: ");
- newClient.println(i);
- // Once we "accept", the client is no longer tracked by EthernetServer
- // so we must store it into our list of clients
- clients[i] = newClient;
- break;
- }
- }
- }
-
- // check for incoming data from all clients
- for (byte i = 0; i < 8; i++) {
- while (clients[i] && clients[i].available() > 0) {
- // read incoming data from the client
- Serial.write(clients[i].read());
- }
- }
-
- // stop any clients which disconnect
- for (byte i = 0; i < 8; i++) {
- if (clients[i] && !clients[i].connected()) {
- clients[i].stop();
- }
- }
-}
-```
-
-### `server.available()`
-
-#### Description
-
-Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop().
-
-
-#### Syntax
-
-```
-server.available()
-
-```
-
-#### Parameters
-None
-
-#### Returns
-- a Client object; if no Client has data available for reading, this object will evaluate to false in an if-statement (see the example below)
-
-#### Example
-
-```
-#include
-#include
-
-// the media access control (ethernet hardware) address for the shield:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-//the IP address for the shield:
-byte ip[] = { 10, 0, 0, 177 };
-// the router's gateway address:
-byte gateway[] = { 10, 0, 0, 1 };
-// the subnet:
-byte subnet[] = { 255, 255, 0, 0 };
-
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup()
-{
- // initialize the ethernet device
- Ethernet.begin(mac, ip, gateway, subnet);
-
- // start listening for clients
- server.begin();
-}
-
-void loop()
-{
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client) {
- // read bytes from the incoming client and write them back
- // to any clients connected to the server:
- server.write(client.read());
- }
-}
-```
-
-### `if(server)`
-
-#### Description
-Indicates whether the server is listening for new clients. You can use this to detect whether server.begin() was successful. It can also tell you when no more sockets are available to listen for more clients, because the maximum number have connected.
-
-
-#### Syntax
-
-```
-if(server)
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- whether the server is listening for new clients (bool).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip);
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- if (server) {
- Serial.println("Server is listening");
- }
- else {
- Serial.println("Server is not listening");
- }
-}
-```
-
-### `server.write()`
-
-#### Description
-
-Write data to all the clients connected to a server. This data is sent as a byte or series of bytes.
-
-
-#### Syntax
-
-```
-server.write(val)
-server.write(buf, len)
-
-```
-
-#### Parameters
-- val: a value to send as a single byte (byte or char)
-
-- buf: an array to send as a series of bytes (byte or char)
-
-- len: the length of the buffer
-
-#### Returns
-- byte
-- write() returns the number of bytes written. It is not necessary to read this.
-
-#### Example
-
-```
-#include
-#include
-
-// network configuration. gateway and subnet are optional.
-
- // the media access control (ethernet hardware) address for the shield:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-//the IP address for the shield:
-byte ip[] = { 10, 0, 0, 177 };
-// the router's gateway address:
-byte gateway[] = { 10, 0, 0, 1 };
-// the subnet:
-byte subnet[] = { 255, 255, 0, 0 };
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup()
-{
- // initialize the ethernet device
- Ethernet.begin(mac, ip, gateway, subnet);
-
- // start listening for clients
- server.begin();
-}
-
-void loop()
-{
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client == true) {
- // read bytes from the incoming client and write them back
- // to any clients connected to the server:
- server.write(client.read());
- }
-}
-```
-
-### `server.print()`
-
-#### Description
-
-Print data to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').
-
-
-#### Syntax
-
-```
-server.print(data)
-server.print(data, BASE)
-
-```
-
-#### Parameters
-- data: the data to print (char, byte, int, long, or string)
-
-- BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).
-
-#### Returns
-- byte
-- print() will return the number of bytes written, though reading that number is optional
-
-
-### `server.println()`
-
-#### Description
-
-Print data, followed by a newline, to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').
-
-
-#### Syntax
-
-```
-server.println()
-server.println(data)
-server.println(data, BASE)
-
-```
-
-#### Parameters
-- data (optional): the data to print (char, byte, int, long, or string)
-
-- BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).
-
-#### Returns
-- byte
-
-- println() will return the number of bytes written, though reading that number is optional
-
-## Client Class
-
-### `Client`
-
-#### Description
-Client is the base class for all Ethernet client based calls. It is not called directly, but invoked whenever you use a function that relies on it.
-
-### `EthernetClient()`
-
-#### Description
-
-Creates a client which can connect to a specified internet IP address and port (defined in the client.connect() function).
-
-
-#### Syntax
-
-```
-EthernetClient()
-
-```
-
-#### Parameters
-None
-
-#### Example
-
-```
-#include
-#include
-
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-byte ip[] = { 10, 0, 0, 177 };
-byte server[] = { 64, 233, 187, 99 }; // Google
-
-EthernetClient client;
-
-void setup()
-{
- Ethernet.begin(mac, ip);
- Serial.begin(9600);
-
- delay(1000);
-
- Serial.println("connecting...");
-
- if (client.connect(server, 80)) {
- Serial.println("connected");
- client.println("GET /search?q=arduino HTTP/1.0");
- client.println();
- } else {
- Serial.println("connection failed");
- }
-}
-
-void loop()
-{
- if (client.available()) {
- char c = client.read();
- Serial.print(c);
- }
-
- if (!client.connected()) {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- for(;;)
- ;
- }
-}
-```
-
-### `if (EthernetClient)`
-
-#### Description
-Indicates if the specified Ethernet client is ready.
-
-
-#### Syntax
-
-```
-if (client)
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- boolean : returns true if the specified client is available.
-
-#### Example
-
-```
-#include
-#include
-
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-byte ip[] = { 10, 0, 0, 177 };
-byte server[] = { 64, 233, 187, 99 }; // Google
-
-EthernetClient client;
-
-void setup()
-{
- Ethernet.begin(mac, ip);
- Serial.begin(9600);
-
- delay(1000);
-
- Serial.println("connecting...");
- while(!client){
- ; // wait until there is a client connected to proceed
- }
- if (client.connect(server, 80)) {
- Serial.println("connected");
- client.println("GET /search?q=arduino HTTP/1.0");
- client.println();
- } else {
- Serial.println("connection failed");
- }
-}
-
-void loop()
-{
- if (client.available()) {
- char c = client.read();
- Serial.print(c);
- }
-
- if (!client.connected()) {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- for(;;)
- ;
- }
-}
-
-```
-
-### `client.connected()`
-
-#### Description
-
-Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data.
-
-
-#### Syntax
-
-```
-client.connected()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- Returns true if the client is connected, false if not.
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-byte ip[] = { 10, 0, 0, 177 };
-byte server[] = { 64, 233, 187, 99 }; // Google
-
-EthernetClient client;
-
-void setup()
-{
- Ethernet.begin(mac, ip);
- Serial.begin(9600);
- client.connect(server, 80);
- delay(1000);
-
- Serial.println("connecting...");
-
- if (client.connected()) {
- Serial.println("connected");
- client.println("GET /search?q=arduino HTTP/1.0");
- client.println();
- } else {
- Serial.println("connection failed");
- }
-}
-
-void loop()
-{
- if (client.available()) {
- char c = client.read();
- Serial.print(c);
- }
-
- if (!client.connected()) {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- for(;;)
- ;
- }
-}
-```
-
-### `client.connect()`
-
-#### Description
-
-Connects to a specified IP address and port. The return value indicates success or failure. Also supports DNS lookups when using a domain name.
-
-
-#### Syntax
-
-```
-client.connect()
-client.connect(ip, port)
-client.connect(URL, port)
-
-```
-
-#### Parameters
-- ip: the IP address that the client will connect to (array of 4 bytes)
-
-- URL: the domain name the client will connect to (string, ex.:"arduino.cc")
-
-- port: the port that the client will connect to (int)
-
-#### Returns
-- Returns an int (1,-1,-2,-3,-4) indicating connection status :
-
-- SUCCESS 1
-- TIMED_OUT -1
-- INVALID_SERVER -2
-- TRUNCATED -3
-- INVALID_RESPONSE -4
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-byte ip[] = { 10, 0, 0, 177 };
-byte server[] = { 64, 233, 187, 99 }; // Google
-
-EthernetClient client;
-
-void setup()
-{
- Ethernet.begin(mac, ip);
- Serial.begin(9600);
-
- delay(1000);
-
- Serial.println("connecting...");
-
- if (client.connect(server, 80)) {
- Serial.println("connected");
- client.println("GET /search?q=arduino HTTP/1.0");
- client.println();
- } else {
- Serial.println("connection failed");
- }
-}
-
-void loop()
-{
- if (client.available()) {
- char c = client.read();
- Serial.print(c);
- }
-
- if (!client.connected()) {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- for(;;)
- ;
- }
-}
-```
-
-### `client.localPort()`
-
-#### Description
-
-Returns the local port number the client is connected to.
-
-
-#### Syntax
-
-```
-client.localPort
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the local port number the client is connected to (uint16_t).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip);
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client) {
- Serial.print("Client is connected on port: ");
- Serial.println(client.localPort());
- client.stop();
- }
-}
-```
-
-### `client.remoteIP()`
-
-#### Description
-
-Returns the IP address of the client.
-
-
-#### Syntax
-
-```
-client.remoteIP()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the client's IP address (IPAddress).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip);
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client) {
- Serial.print("Remote IP address: ");
- Serial.println(client.remoteIP());
- client.stop();
- }
-}
-```
-
-### `client.remotePort()`
-
-#### Description
-
-Returns the port of the host that sent the current incoming packet.
-
-
-#### Syntax
-
-```
-client.remotePort()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- the port of the host that sent the current incoming packet (uint16_t).
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip);
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client) {
- Serial.print("Remote port: ");
- Serial.println(client.remotePort());
- client.stop();
- }
-}
-```
-
-### `client.setConnectionTimeout()`
-
-#### Description
-
-Set the timeout for client.connect() and client.stop(). The initial value is 1000 ms. You might prefer to set a lower timeout value to make your program more responsive in the event something goes wrong.
-
-
-#### Syntax
-
-```
-client.setConnectionTimeout(milliseconds)
-
-```
-
-#### Parameters
-- milliseconds: the timeout duration for client.connect() and client.stop() (uint16_t)
-
-#### Returns
-Nothing
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
-IPAddress ip(10, 0, 0, 177);
-
-// telnet defaults to port 23
-EthernetServer server = EthernetServer(23);
-
-void setup() {
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip);
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- // if an incoming client connects, there will be bytes available to read:
- EthernetClient client = server.available();
- if (client) {
- client.setConnectionTimeout(100); // set the timeout duration for client.connect() and client.stop()
- }
-}
-```
-
-### `client.write()`
-
-#### Description
-
-Write data to the server the client is connected to. This data is sent as a byte or series of bytes.
-
-
-#### Syntax
-
-```
-client.write(val)
-client.write(buf, len)
-
-```
-
-#### Parameters
-- val: a value to send as a single byte (byte or char)
-
-- buf: an array to send as a series of bytes (byte or char)
-
-- len: the length of the buffer
-
-#### Returns
-byte:
-- write() returns the number of bytes written. It is not necessary to read this value.
-
-### `print()`
-
-#### Description
-
-Print data to the server that a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').
-
-
-#### Syntax
-
-```
-client.print(data)
-client.print(data, BASE)
-
-```
-
-#### Parameters
-- data: the data to print (char, byte, int, long, or string)
-
-- BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).
-#### Returns
-- byte: returns the number of bytes written, though reading that number is optional
-
-### `client.println()`
-
-#### Description
-
-Print data, followed by a carriage return and newline, to the server a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').
-
-
-#### Syntax
-
-```
-client.println()
-client.println(data)
-client.print(data, BASE)
-
-```
-
-#### Parameters
-- data (optional): the data to print (char, byte, int, long, or string)
-
-- BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).
-
-#### Returns
-- byte: return the number of bytes written, though reading that number is optional
-
-
-### `client.available()`
-
-#### Description
-
-Returns the number of bytes available for reading (that is, the amount of data that has been written to the client by the server it is connected to).
-
-available() inherits from the Stream utility class.
-
-
-#### Syntax
-
-```
-client.available()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- The number of bytes available.
-
-#### Example
-
-```
-#include
-#include
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-byte ip[] = { 10, 0, 0, 177 };
-byte server[] = { 64, 233, 187, 99 }; // Google
-
-EthernetClient client;
-
-void setup()
-{
- Ethernet.begin(mac, ip);
- Serial.begin(9600);
-
- delay(1000);
-
- Serial.println("connecting...");
-
- if (client.connect(server, 80)) {
- Serial.println("connected");
- client.println("GET /search?q=arduino HTTP/1.0");
- client.println();
- } else {
- Serial.println("connection failed");
- }
-}
-
-void loop()
-{
- if (client.available()) {
- char c = client.read();
- Serial.print(c);
- }
-
- if (!client.connected()) {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- for(;;)
- ;
- }
-}
-```
-
-### `client.read()`
-
-#### Description
-
-Read the next byte received from the server the client is connected to (after the last call to read()).
-
-read() inherits from the Stream utility class.
-
-
-#### Syntax
-
-```
-client.read()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-- The next byte (or character), or -1 if none is available.
-
-### `client.flush()`
-Waits until all outgoing characters in buffer have been sent.
-
-flush() inherits from the Stream utility class.
-
-
-#### Syntax
-
-```
-client.flush()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-none
-
-### `client.stop()`
-
-#### Description
-
-Disconnect from the server.
-
-
-#### Syntax
-
-```
-client.stop()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-none
-
-## EthernetUDP Class
-
-### `EthernetUDP.begin()`
-
-#### Description
-Initializes the ethernet UDP library and network settings.
-
-
-#### Syntax
-
-```
-EthernetUDP.begin(localPort);
-```
-
-#### Parameters
-- localPort: the local port to listen on (int)
-
-#### Returns
-- 1 if successful, 0 if there are no sockets available to use.
-
-#### Example
-
-```
-
-#include
-
-#include
-
-#include
-
-
-
-// Enter a MAC address and IP address for your controller below.
-
-// The IP address will be dependent on your local network:
-
-byte mac[] = {
-
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-
-IPAddress ip(192, 168, 1, 177);
-
-
-
-unsigned int localPort = 8888; // local port to listen on
-
-
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-
-EthernetUDP Udp;
-
-
-
-void setup() {
-
- // start the Ethernet and UDP:
-
- Ethernet.begin(mac,ip);
-
- Udp.begin(localPort);
-
-
-
-}
-
-
-
-void loop() {
-}
-
-
-```
-
-### `EthernetUDP.read()`
-
-#### Description
-Reads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer.
-
-This function can only be successfully called after UDP.parsePacket().
-
-
-#### Syntax
-
-```
-EthernetUDP.read();
-EthernetUDP.read(packetBuffer, MaxSize);
-```
-
-#### Parameters
-- packetBuffer: buffer to hold incoming packets (char)
-- MaxSize: maximum size of the buffer (int)
-
-#### Returns
-- char : returns the characters in the buffer
-
-#### Example
-
-```
-#include
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-
-}
-
-void loop() {
-
- int packetSize = Udp.parsePacket();
- if(packetSize)
- {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From ");
- IPAddress remote = Udp.remoteIP();
- for (int i =0; i < 4; i++)
- {
- Serial.print(remote[i], DEC);
- if (i < 3)
- {
- Serial.print(".");
- }
- }
- Serial.print(", port ");
- Serial.println(Udp.remotePort());
-
- // read the packet into packetBuffer
- Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
- Serial.println("Contents:");
- Serial.println(packetBuffer);
-}
-}
-```
-
-### `EthernetUDP.write()`
-
-#### Description
-Writes UDP data to the remote connection. Must be wrapped between beginPacket() and endPacket(). beginPacket() initializes the packet of data, it is not sent until endPacket() is called.
-
-
-#### Syntax
-
-```
-EthernetUDP.write(message);
-EthernetUDP.write(buffer, size);
-
-```
-
-#### Parameters
-
-- message: the outgoing message (char)
-
-- buffer: an array to send as a series of bytes (byte or char)
-
-- size: the length of the buffer
-
-#### Returns
-- byte : returns the number of characters sent. This does not have to be read
-
-#### Example
-
-```
-
-
-
-#include
-
-#include
-
-#include
-
-
-
-// Enter a MAC address and IP address for your controller below.
-
-// The IP address will be dependent on your local network:
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-
-IPAddress ip(192, 168, 1, 177);
-
-
-
-unsigned int localPort = 8888; // local port to listen on
-
-
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-
-EthernetUDP Udp;
-
-
-
-void setup() {
-
- // start the Ethernet and UDP:
-
- Ethernet.begin(mac,ip);
-
- Udp.begin(localPort);
-
-}
-
-
-
-void loop() {
-
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
-
- Udp.write("hello");
-
- Udp.endPacket();
-
-}
-
-
-```
-
-### `EthernetUDP.beginPacket()`
-
-#### Description
-Starts a connection to write UDP data to the remote connection
-
-
-#### Syntax
-
-```
-EthernetUDP.beginPacket(remoteIP, remotePort);
-```
-
-#### Parameters
-- remoteIP: the IP address of the remote connection (4 bytes)
-- remotePort: the port of the remote connection (int)
-#### Returns
-- Returns an int: 1 if successful, 0 if there was a problem resolving the hostname or port.
-
-#### Example
-
-```
-#include
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-
-}
-
-void loop() {
-
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
- Udp.write("hello");
- Udp.endPacket();
-
-}
-```
-
-### `EthernetUDP.endPacket()`
-
-#### Description
-Called after writing UDP data to the remote connection.
-
-
-#### Syntax
-
-```
-EthernetUDP.endPacket();
-```
-
-#### Parameters
-None
-
-#### Returns
-- Returns an int: 1 if the packet was sent successfully, 0 if there was an error
-
-#### Example
-
-```
-#include
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-
-}
-
-void loop() {
-
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
- Udp.write("hello");
- Udp.endPacket();
-
-}
-```
-
-### `EthernetUDP.parsePacket()`
-
-#### Description
-Checks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP.read().
-
-
-#### Syntax
-
-```
-EthernetUDP.parsePacket();
-```
-
-#### Parameters
-None
-
-#### Returns
-- int: the size of a received UDP packet
-
-#### Example
-
-```
-
-#include // needed for Arduino versions later than 0018
-#include
-#include // UDP library from: bjoern@cs.stanford.edu 12/30/2008
-
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-
- Serial.begin(9600);
-}
-
-void loop() {
- // if there's data available, read a packet
- int packetSize = Udp.parsePacket();
- if(packetSize)
- {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- }
- delay(10);
-}
-```
-
-### `EthernetUDP.available()`
-
-#### Description
-
-Get the number of bytes (characters) available for reading from the buffer. This is data that's already arrived.
-
-This function can only be successfully called after UDP.parsePacket().
-
-available() inherits from the Stream utility class.
-
-
-#### Syntax
-
-```
-EthernetUDP.available()
-
-```
-
-#### Parameters
-None
-
-#### Returns
-- the number of bytes available to read
-
-#### Example
-
-```
-#include
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-
-}
-
-void loop() {
-
- int packetSize = Udp.parsePacket();
- if(Udp.available())
- {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From ");
- IPAddress remote = Udp.remoteIP();
- for (int i =0; i < 4; i++)
- {
- Serial.print(remote[i], DEC);
- if (i < 3)
- {
- Serial.print(".");
- }
- }
- Serial.print(", port ");
- Serial.println(Udp.remotePort());
-
- // read the packet into packetBuffer
- Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
- Serial.println("Contents:");
- Serial.println(packetBuffer);
- }
-}
-```
-
-## UDP class
-
-### `UDP.stop()`
-
-#### Description
-
-Disconnect from the server. Release any resource being used during the UDP session.
-
-
-#### Syntax
-
-```
-UDP.stop()
-
-```
-
-#### Parameters
-none
-
-#### Returns
-none
-
-### `UDP.remoteIP()`
-
-#### Description
-Gets the IP address of the remote connection.
-
-This function must be called after UDP.parsePacket().
-
-
-#### Syntax
-
-```
-UDP.remoteIP();
-```
-
-#### Parameters
-None
-
-#### Returns
-- 4 bytes : the IP address of the remote connection
-
-#### Example
-
-```
-
-#include
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-}
-
-void loop() {
-
- int packetSize = Udp.parsePacket();
- if(packetSize)
- {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From IP : ");
-
- IPAddress remote = Udp.remoteIP();
- //print out the remote connection's IP address
- Serial.print(remote);
-
- Serial.print(" on port : ");
- //print out the remote connection's port
- Serial.println(Udp.remotePort());
- }
-
-}
-
-
-```
-
-### `UDP.remotePort()`
-
-#### Description
-Gets the port of the remote UDP connection.
-
-This function must be called after UDP.parsePacket().
-
-
-#### Syntax
-
-```
-UDP.remotePort();
-```
-
-#### Parameters
-None
-
-#### Returns
-- int : the port of the UDP connection to a remote host
-
-#### Example
-
-```
-#include
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
-
-void setup() {
- // start the Ethernet and UDP:
- Ethernet.begin(mac,ip);
- Udp.begin(localPort);
-
-}
-
-void loop() {
-
- int packetSize = Udp.parsePacket();
- if(packetSize)
- {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From ");
- IPAddress remote = Udp.remoteIP();
- for (int i =0; i < 4; i++)
- {
- Serial.print(remote[i], DEC);
- if (i < 3)
- {
- Serial.print(".");
- }
- }
- Serial.print(", port ");
- Serial.println(Udp.remotePort());
-
- // read the packet into packetBuffer
- Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
- Serial.println("Contents:");
- Serial.println(packetBuffer);
- }
-}
-```
\ No newline at end of file
diff --git a/lib/Ethernet/docs/arduino_mega_ethernet_pins.png b/lib/Ethernet/docs/arduino_mega_ethernet_pins.png
deleted file mode 100644
index e35edc2..0000000
Binary files a/lib/Ethernet/docs/arduino_mega_ethernet_pins.png and /dev/null differ
diff --git a/lib/Ethernet/docs/arduino_uno_ethernet_pins.png b/lib/Ethernet/docs/arduino_uno_ethernet_pins.png
deleted file mode 100644
index ae7e520..0000000
Binary files a/lib/Ethernet/docs/arduino_uno_ethernet_pins.png and /dev/null differ
diff --git a/lib/Ethernet/docs/readme.md b/lib/Ethernet/docs/readme.md
deleted file mode 100644
index cdb2044..0000000
--- a/lib/Ethernet/docs/readme.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# Ethernet Library
-
-This library is designed to work with the Arduino Ethernet Shield, Arduino Ethernet Shield 2, Leonardo Ethernet, and any other W5100/W5200/W5500-based devices. The library allows an Arduino board to connect to the Internet. The board can serve as either a server accepting incoming connections or a client making outgoing ones. The library supports up to eight (W5100 and boards with <= 2 kB SRAM are limited to four) concurrent connections (incoming, outgoing, or a combination).
-
-The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.
-
-
-
-
-
-To use this library
-
-```
-#include
-#include
-```
\ No newline at end of file
diff --git a/lib/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino b/lib/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino
deleted file mode 100644
index c97a958..0000000
--- a/lib/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- Advanced Chat Server
-
- A more advanced server that distributes any incoming messages
- to all connected clients but the client the message comes from.
- To use, telnet to your device's IP address and type.
- You can see the client's input in the serial monitor as well.
- Using an Arduino WIZnet Ethernet shield.
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
-
- created 18 Dec 2009
- by David A. Mellis
- modified 9 Apr 2012
- by Tom Igoe
- redesigned to make use of operator== 25 Nov 2013
- by Norbert Truchsess
-
- */
-
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network.
-// gateway and subnet are optional:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-IPAddress ip(192, 168, 1, 177);
-IPAddress myDns(192, 168, 1, 1);
-IPAddress gateway(192, 168, 1, 1);
-IPAddress subnet(255, 255, 0, 0);
-
-
-// telnet defaults to port 23
-EthernetServer server(23);
-
-EthernetClient clients[8];
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip, myDns, gateway, subnet);
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
-
- // start listening for clients
- server.begin();
-
- Serial.print("Chat server address:");
- Serial.println(Ethernet.localIP());
-}
-
-void loop() {
- // check for any new client connecting, and say hello (before any incoming data)
- EthernetClient newClient = server.accept();
- if (newClient) {
- for (byte i=0; i < 8; i++) {
- if (!clients[i]) {
- Serial.print("We have a new client #");
- Serial.println(i);
- newClient.print("Hello, client number: ");
- newClient.println(i);
- // Once we "accept", the client is no longer tracked by EthernetServer
- // so we must store it into our list of clients
- clients[i] = newClient;
- break;
- }
- }
- }
-
- // check for incoming data from all clients
- for (byte i=0; i < 8; i++) {
- if (clients[i] && clients[i].available() > 0) {
- // read bytes from a client
- byte buffer[80];
- int count = clients[i].read(buffer, 80);
- // write the bytes to all other connected clients
- for (byte j=0; j < 8; j++) {
- if (j != i && clients[j].connected()) {
- clients[j].write(buffer, count);
- }
- }
- }
- }
-
- // stop any clients which disconnect
- for (byte i=0; i < 8; i++) {
- if (clients[i] && !clients[i].connected()) {
- Serial.print("disconnect client #");
- Serial.println(i);
- clients[i].stop();
- }
- }
-}
diff --git a/lib/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino b/lib/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino
deleted file mode 100644
index 831f17f..0000000
--- a/lib/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- SCP1000 Barometric Pressure Sensor Display
-
- Serves the output of a Barometric Pressure Sensor as a web page.
- Uses the SPI library. For details on the sensor, see:
- http://www.sparkfun.com/commerce/product_info.php?products_id=8161
-
- This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
- http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
-
- TODO: this hardware is long obsolete. This example program should
- be rewritten to use https://www.sparkfun.com/products/9721
-
- Circuit:
- SCP1000 sensor attached to pins 6,7, and 11 - 13:
- DRDY: pin 6
- CSB: pin 7
- MOSI: pin 11
- MISO: pin 12
- SCK: pin 13
-
- created 31 July 2010
- by Tom Igoe
- */
-
-#include
-// the sensor communicates using SPI, so include the library:
-#include
-
-
-// assign a MAC address for the Ethernet controller.
-// fill in your address here:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-// assign an IP address for the controller:
-IPAddress ip(192, 168, 1, 20);
-
-
-// Initialize the Ethernet server library
-// with the IP address and port you want to use
-// (port 80 is default for HTTP):
-EthernetServer server(80);
-
-
-//Sensor's memory register addresses:
-const int PRESSURE = 0x1F; //3 most significant bits of pressure
-const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure
-const int TEMPERATURE = 0x21; //16 bit temperature reading
-
-// pins used for the connection with the sensor
-// the others you need are controlled by the SPI library):
-const int dataReadyPin = 6;
-const int chipSelectPin = 7;
-
-float temperature = 0.0;
-long pressure = 0;
-long lastReadingTime = 0;
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // start the SPI library:
- SPI.begin();
-
- // start the Ethernet connection
- Ethernet.begin(mac, ip);
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
-
- // start listening for clients
- server.begin();
-
- // initialize the data ready and chip select pins:
- pinMode(dataReadyPin, INPUT);
- pinMode(chipSelectPin, OUTPUT);
-
- //Configure SCP1000 for low noise configuration:
- writeRegister(0x02, 0x2D);
- writeRegister(0x01, 0x03);
- writeRegister(0x03, 0x02);
-
- // give the sensor and Ethernet shield time to set up:
- delay(1000);
-
- //Set the sensor to high resolution mode to start readings:
- writeRegister(0x03, 0x0A);
-
-}
-
-void loop() {
- // check for a reading no more than once a second.
- if (millis() - lastReadingTime > 1000) {
- // if there's a reading ready, read it:
- // don't do anything until the data ready pin is high:
- if (digitalRead(dataReadyPin) == HIGH) {
- getData();
- // timestamp the last time you got a reading:
- lastReadingTime = millis();
- }
- }
-
- // listen for incoming Ethernet connections:
- listenForEthernetClients();
-}
-
-
-void getData() {
- Serial.println("Getting reading");
- //Read the temperature data
- int tempData = readRegister(0x21, 2);
-
- // convert the temperature to Celsius and display it:
- temperature = (float)tempData / 20.0;
-
- //Read the pressure data highest 3 bits:
- byte pressureDataHigh = readRegister(0x1F, 1);
- pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0
-
- //Read the pressure data lower 16 bits:
- unsigned int pressureDataLow = readRegister(0x20, 2);
- //combine the two parts into one 19-bit number:
- pressure = ((pressureDataHigh << 16) | pressureDataLow) / 4;
-
- Serial.print("Temperature: ");
- Serial.print(temperature);
- Serial.println(" degrees C");
- Serial.print("Pressure: " + String(pressure));
- Serial.println(" Pa");
-}
-
-void listenForEthernetClients() {
- // listen for incoming clients
- EthernetClient client = server.available();
- if (client) {
- Serial.println("Got a client");
- // an HTTP request ends with a blank line
- bool currentLineIsBlank = true;
- while (client.connected()) {
- if (client.available()) {
- char c = client.read();
- // if you've gotten to the end of the line (received a newline
- // character) and the line is blank, the HTTP request has ended,
- // so you can send a reply
- if (c == '\n' && currentLineIsBlank) {
- // send a standard HTTP response header
- client.println("HTTP/1.1 200 OK");
- client.println("Content-Type: text/html");
- client.println();
- // print the current readings, in HTML format:
- client.print("Temperature: ");
- client.print(temperature);
- client.print(" degrees C");
- client.println(" ");
- client.print("Pressure: " + String(pressure));
- client.print(" Pa");
- client.println(" ");
- break;
- }
- if (c == '\n') {
- // you're starting a new line
- currentLineIsBlank = true;
- } else if (c != '\r') {
- // you've gotten a character on the current line
- currentLineIsBlank = false;
- }
- }
- }
- // give the web browser time to receive the data
- delay(1);
- // close the connection:
- client.stop();
- }
-}
-
-
-//Send a write command to SCP1000
-void writeRegister(byte registerName, byte registerValue) {
- // SCP1000 expects the register name in the upper 6 bits
- // of the byte:
- registerName <<= 2;
- // command (read or write) goes in the lower two bits:
- registerName |= 0b00000010; //Write command
-
- // take the chip select low to select the device:
- digitalWrite(chipSelectPin, LOW);
-
- SPI.transfer(registerName); //Send register location
- SPI.transfer(registerValue); //Send value to record into register
-
- // take the chip select high to de-select:
- digitalWrite(chipSelectPin, HIGH);
-}
-
-
-//Read register from the SCP1000:
-unsigned int readRegister(byte registerName, int numBytes) {
- byte inByte = 0; // incoming from the SPI read
- unsigned int result = 0; // result to return
-
- // SCP1000 expects the register name in the upper 6 bits
- // of the byte:
- registerName <<= 2;
- // command (read or write) goes in the lower two bits:
- registerName &= 0b11111100; //Read command
-
- // take the chip select low to select the device:
- digitalWrite(chipSelectPin, LOW);
- // send the device the register you want to read:
- SPI.transfer(registerName);
- // send a value of 0 to read the first byte returned:
- inByte = SPI.transfer(0x00);
-
- result = inByte;
- // if there's more than one byte returned,
- // shift the first byte then get the second byte:
- if (numBytes > 1) {
- result = inByte << 8;
- inByte = SPI.transfer(0x00);
- result = result | inByte;
- }
- // take the chip select high to de-select:
- digitalWrite(chipSelectPin, HIGH);
- // return the result:
- return (result);
-}
diff --git a/lib/Ethernet/examples/ChatServer/ChatServer.ino b/lib/Ethernet/examples/ChatServer/ChatServer.ino
deleted file mode 100644
index 3e28060..0000000
--- a/lib/Ethernet/examples/ChatServer/ChatServer.ino
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- Chat Server
-
- A simple server that distributes any incoming messages to all
- connected clients. To use, telnet to your device's IP address and type.
- You can see the client's input in the serial monitor as well.
- Using an Arduino WIZnet Ethernet shield.
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
-
- created 18 Dec 2009
- by David A. Mellis
- modified 9 Apr 2012
- by Tom Igoe
-
- */
-
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network.
-// gateway and subnet are optional:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 177);
-IPAddress myDns(192, 168, 1, 1);
-IPAddress gateway(192, 168, 1, 1);
-IPAddress subnet(255, 255, 0, 0);
-
-
-// telnet defaults to port 23
-EthernetServer server(23);
-bool alreadyConnected = false; // whether or not the client was connected previously
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // initialize the Ethernet device
- Ethernet.begin(mac, ip, myDns, gateway, subnet);
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
-
- // start listening for clients
- server.begin();
-
- Serial.print("Chat server address:");
- Serial.println(Ethernet.localIP());
-}
-
-void loop() {
- // wait for a new client:
- EthernetClient client = server.available();
-
- // when the client sends the first byte, say hello:
- if (client) {
- if (!alreadyConnected) {
- // clear out the input buffer:
- client.flush();
- Serial.println("We have a new client");
- client.println("Hello, client!");
- alreadyConnected = true;
- }
-
- if (client.available() > 0) {
- // read the bytes incoming from the client:
- char thisChar = client.read();
- // echo the bytes back to the client:
- server.write(thisChar);
- // echo the bytes to the server as well:
- Serial.write(thisChar);
- }
- }
-}
diff --git a/lib/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/lib/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino
deleted file mode 100644
index 612106f..0000000
--- a/lib/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- DHCP-based IP printer
-
- This sketch uses the DHCP extensions to the Ethernet library
- to get an IP address via DHCP and print the address obtained.
- using an Arduino WIZnet Ethernet shield.
-
- Circuit:
- Ethernet shield attached to pins 10, 11, 12, 13
-
- created 12 April 2011
- modified 9 Apr 2012
- by Tom Igoe
- modified 02 Sept 2015
- by Arturo Guadalupi
-
- */
-
-#include
-#include
-
-// Enter a MAC address for your controller below.
-// Newer Ethernet shields have a MAC address printed on a sticker on the shield
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // start the Ethernet connection:
- Serial.println("Initialize Ethernet with DHCP:");
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- } else if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
- // no point in carrying on, so do nothing forevermore:
- while (true) {
- delay(1);
- }
- }
- // print your local IP address:
- Serial.print("My IP address: ");
- Serial.println(Ethernet.localIP());
-}
-
-void loop() {
- switch (Ethernet.maintain()) {
- case 1:
- //renewed fail
- Serial.println("Error: renewed fail");
- break;
-
- case 2:
- //renewed success
- Serial.println("Renewed success");
- //print your local IP address:
- Serial.print("My IP address: ");
- Serial.println(Ethernet.localIP());
- break;
-
- case 3:
- //rebind fail
- Serial.println("Error: rebind fail");
- break;
-
- case 4:
- //rebind success
- Serial.println("Rebind success");
- //print your local IP address:
- Serial.print("My IP address: ");
- Serial.println(Ethernet.localIP());
- break;
-
- default:
- //nothing happened
- break;
- }
-}
diff --git a/lib/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino b/lib/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino
deleted file mode 100644
index 01cd814..0000000
--- a/lib/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- DHCP Chat Server
-
- A simple server that distributes any incoming messages to all
- connected clients. To use, telnet to your device's IP address and type.
- You can see the client's input in the serial monitor as well.
- Using an Arduino WIZnet Ethernet shield.
-
- THis version attempts to get an IP address using DHCP
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
-
- created 21 May 2011
- modified 9 Apr 2012
- by Tom Igoe
- modified 02 Sept 2015
- by Arturo Guadalupi
- Based on ChatServer example by David A. Mellis
-
- */
-
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network.
-// gateway and subnet are optional:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-IPAddress ip(192, 168, 1, 177);
-IPAddress myDns(192, 168, 1, 1);
-IPAddress gateway(192, 168, 1, 1);
-IPAddress subnet(255, 255, 0, 0);
-
-// telnet defaults to port 23
-EthernetServer server(23);
-bool gotAMessage = false; // whether or not you got a message from the client yet
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // start the Ethernet connection:
- Serial.println("Trying to get an IP address using DHCP");
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
- // initialize the Ethernet device not using DHCP:
- Ethernet.begin(mac, ip, myDns, gateway, subnet);
- }
- // print your local IP address:
- Serial.print("My IP address: ");
- Serial.println(Ethernet.localIP());
-
- // start listening for clients
- server.begin();
-}
-
-void loop() {
- // wait for a new client:
- EthernetClient client = server.available();
-
- // when the client sends the first byte, say hello:
- if (client) {
- if (!gotAMessage) {
- Serial.println("We have a new client");
- client.println("Hello, client!");
- gotAMessage = true;
- }
-
- // read the bytes incoming from the client:
- char thisChar = client.read();
- // echo the bytes back to the client:
- server.write(thisChar);
- // echo the bytes to the server as well:
- Serial.print(thisChar);
- Ethernet.maintain();
- }
-}
diff --git a/lib/Ethernet/examples/LinkStatus/LinkStatus.ino b/lib/Ethernet/examples/LinkStatus/LinkStatus.ino
deleted file mode 100644
index 84651d0..0000000
--- a/lib/Ethernet/examples/LinkStatus/LinkStatus.ino
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- Link Status
-
- This sketch prints the Ethernet link status. When the
- Ethernet cable is connected the link status should go to "ON".
- NOTE: Only WIZnet W5200 and W5500 are capable of reporting
- the link status. W5100 will report "Unknown".
- Hardware:
- - Ethernet shield or equivalent board/shield with WIZnet W5200/W5500
- Written by Cristian Maglie
- This example is public domain.
-*/
-
-#include
-#include
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- Serial.begin(9600);
-}
-
-void loop() {
- auto link = Ethernet.linkStatus();
- Serial.print("Link status: ");
- switch (link) {
- case Unknown:
- Serial.println("Unknown");
- break;
- case LinkON:
- Serial.println("ON");
- break;
- case LinkOFF:
- Serial.println("OFF");
- break;
- }
- delay(1000);
-}
diff --git a/lib/Ethernet/examples/PagerServer/PagerServer.ino b/lib/Ethernet/examples/PagerServer/PagerServer.ino
deleted file mode 100644
index e17ae6e..0000000
--- a/lib/Ethernet/examples/PagerServer/PagerServer.ino
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- Pager Server
-
- A simple server that echoes any incoming messages to all
- connected clients. Connect two or more telnet sessions
- to see how server.available() and server.print() works.
-
- created in September 2020 for the Ethernet library
- by Juraj Andrassy https://github.com/jandrassy
-
-*/
-#include
-
-// Enter a MAC address for your controller below.
-// Newer Ethernet shields have a MAC address printed on a sticker on the shield
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-
-// Set the static IP address to use if the DHCP fails to assign
-IPAddress ip(192, 168, 0, 177);
-
-EthernetServer server(2323);
-
-void setup() {
-
- Serial.begin(9600);
- while (!Serial);
-
- // start the Ethernet connection:
- Serial.println("Initialize Ethernet with DHCP:");
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
- // try to configure using IP address instead of DHCP:
- Ethernet.begin(mac, ip);
- } else {
- Serial.print(" DHCP assigned IP ");
- Serial.println(Ethernet.localIP());
- }
-
- server.begin();
-
- IPAddress ip = Ethernet.localIP();
- Serial.println();
- Serial.print("To access the server, connect with Telnet client to ");
- Serial.print(ip);
- Serial.println(" 2323");
-}
-
-void loop() {
-
- EthernetClient client = server.available(); // returns first client which has data to read or a 'false' client
- if (client) { // client is true only if it is connected and has data to read
- String s = client.readStringUntil('\n'); // read the message incoming from one of the clients
- s.trim(); // trim eventual \r
- Serial.println(s); // print the message to Serial Monitor
- client.print("echo: "); // this is only for the sending client
- server.println(s); // send the message to all connected clients
-#ifndef ARDUINO_ARCH_SAM
- server.flush(); // flush the buffers
-#endif /* !defined(ARDUINO_ARCH_SAM) */
- }
-}
diff --git a/lib/Ethernet/examples/TelnetClient/TelnetClient.ino b/lib/Ethernet/examples/TelnetClient/TelnetClient.ino
deleted file mode 100644
index ff554a5..0000000
--- a/lib/Ethernet/examples/TelnetClient/TelnetClient.ino
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- Telnet client
-
- This sketch connects to a telnet server (http://www.google.com)
- using an Arduino WIZnet Ethernet shield. You'll need a telnet server
- to test this with.
- Processing's ChatServer example (part of the Network library) works well,
- running on port 10002. It can be found as part of the examples
- in the Processing application, available at
- https://processing.org/
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
-
- created 14 Sep 2010
- modified 9 Apr 2012
- by Tom Igoe
- */
-
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-IPAddress ip(192, 168, 1, 177);
-
-// Enter the IP address of the server you're connecting to:
-IPAddress server(1, 1, 1, 1);
-
-// Initialize the Ethernet client library
-// with the IP address and port of the server
-// that you want to connect to (port 23 is default for telnet;
-// if you're using Processing's ChatServer, use port 10002):
-EthernetClient client;
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // start the Ethernet connection:
- Ethernet.begin(mac, ip);
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- while (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- delay(500);
- }
-
- // give the Ethernet shield a second to initialize:
- delay(1000);
- Serial.println("connecting...");
-
- // if you get a connection, report back via serial:
- if (client.connect(server, 10002)) {
- Serial.println("connected");
- } else {
- // if you didn't get a connection to the server:
- Serial.println("connection failed");
- }
-}
-
-void loop() {
- // if there are incoming bytes available
- // from the server, read them and print them:
- if (client.available()) {
- char c = client.read();
- Serial.print(c);
- }
-
- // as long as there are bytes in the serial queue,
- // read them and send them out the socket if it's open:
- while (Serial.available() > 0) {
- char inChar = Serial.read();
- if (client.connected()) {
- client.print(inChar);
- }
- }
-
- // if the server's disconnected, stop the client:
- if (!client.connected()) {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- // do nothing:
- while (true) {
- delay(1);
- }
- }
-}
diff --git a/lib/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino b/lib/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino
deleted file mode 100644
index 3995b33..0000000
--- a/lib/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- UDPSendReceiveString
-
- This sketch receives UDP message strings, prints them to the serial port
- and sends an "acknowledge" string back to the sender
-
- A Processing sketch is included at the end of file that can be used to send
- and receive messages for testing with a computer.
-
- created 21 Aug 2010
- by Michael Margolis
-
- This code is in the public domain.
- */
-
-
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-IPAddress ip(192, 168, 1, 177);
-
-unsigned int localPort = 8888; // local port to listen on
-
-// buffers for receiving and sending data
-char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet,
-char ReplyBuffer[] = "acknowledged"; // a string to send back
-
-// An EthernetUDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // start the Ethernet
- Ethernet.begin(mac, ip);
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
-
- // start UDP
- Udp.begin(localPort);
-}
-
-void loop() {
- // if there's data available, read a packet
- int packetSize = Udp.parsePacket();
- if (packetSize) {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From ");
- IPAddress remote = Udp.remoteIP();
- for (int i=0; i < 4; i++) {
- Serial.print(remote[i], DEC);
- if (i < 3) {
- Serial.print(".");
- }
- }
- Serial.print(", port ");
- Serial.println(Udp.remotePort());
-
- // read the packet into packetBuffer
- Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
- Serial.println("Contents:");
- Serial.println(packetBuffer);
-
- // send a reply to the IP address and port that sent us the packet we received
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
- Udp.write(ReplyBuffer);
- Udp.endPacket();
- }
- delay(10);
-}
-
-
-/*
- Processing sketch to run with this example
- =====================================================
-
- // Processing UDP example to send and receive string data from Arduino
- // press any key to send the "Hello Arduino" message
-
-
- import hypermedia.net.*;
-
- UDP udp; // define the UDP object
-
-
- void setup() {
- udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000
- //udp.log( true ); // <-- printout the connection activity
- udp.listen( true ); // and wait for incoming message
- }
-
- void draw()
- {
- }
-
- void keyPressed() {
- String ip = "192.168.1.177"; // the remote IP address
- int port = 8888; // the destination port
-
- udp.send("Hello World", ip, port ); // the message to send
-
- }
-
- void receive( byte[] data ) { // <-- default handler
- //void receive( byte[] data, String ip, int port ) { // <-- extended handler
-
- for(int i=0; i < data.length; i++)
- print(char(data[i]));
- println();
- }
- */
diff --git a/lib/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino b/lib/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino
deleted file mode 100644
index 1455b40..0000000
--- a/lib/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- Udp NTP Client
-
- Get the time from a Network Time Protocol (NTP) time server
- Demonstrates use of UDP sendPacket and ReceivePacket
- For more on NTP time servers and the messages needed to communicate with them,
- see https://en.wikipedia.org/wiki/Network_Time_Protocol
-
- created 4 Sep 2010
- by Michael Margolis
- modified 9 Apr 2012
- by Tom Igoe
- modified 02 Sept 2015
- by Arturo Guadalupi
-
- This code is in the public domain.
-
- */
-
-#include
-#include
-#include
-
-// Enter a MAC address for your controller below.
-// Newer Ethernet shields have a MAC address printed on a sticker on the shield
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-
-unsigned int localPort = 8888; // local port to listen for UDP packets
-
-const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server
-
-const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
-
-byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
-
-// A UDP instance to let us send and receive packets over UDP
-EthernetUDP Udp;
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // start Ethernet and UDP
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- } else if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
- // no point in carrying on, so do nothing forevermore:
- while (true) {
- delay(1);
- }
- }
- Udp.begin(localPort);
-}
-
-void loop() {
- sendNTPpacket(timeServer); // send an NTP packet to a time server
-
- // wait to see if a reply is available
- delay(1000);
- if (Udp.parsePacket()) {
- // We've received a packet, read the data from it
- Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
-
- // the timestamp starts at byte 40 of the received packet and is four bytes,
- // or two words, long. First, extract the two words:
-
- unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
- unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
- // combine the four bytes (two words) into a long integer
- // this is NTP time (seconds since Jan 1 1900):
- unsigned long secsSince1900 = highWord << 16 | lowWord;
- Serial.print("Seconds since Jan 1 1900 = ");
- Serial.println(secsSince1900);
-
- // now convert NTP time into everyday time:
- Serial.print("Unix time = ");
- // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
- const unsigned long seventyYears = 2208988800UL;
- // subtract seventy years:
- unsigned long epoch = secsSince1900 - seventyYears;
- // print Unix time:
- Serial.println(epoch);
-
-
- // print the hour, minute and second:
- Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
- Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
- Serial.print(':');
- if (((epoch % 3600) / 60) < 10) {
- // In the first 10 minutes of each hour, we'll want a leading '0'
- Serial.print('0');
- }
- Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
- Serial.print(':');
- if ((epoch % 60) < 10) {
- // In the first 10 seconds of each minute, we'll want a leading '0'
- Serial.print('0');
- }
- Serial.println(epoch % 60); // print the second
- }
- // wait ten seconds before asking for the time again
- delay(10000);
- Ethernet.maintain();
-}
-
-// send an NTP request to the time server at the given address
-void sendNTPpacket(const char * address) {
- // set all bytes in the buffer to 0
- memset(packetBuffer, 0, NTP_PACKET_SIZE);
- // Initialize values needed to form NTP request
- // (see URL above for details on the packets)
- packetBuffer[0] = 0b11100011; // LI, Version, Mode
- packetBuffer[1] = 0; // Stratum, or type of clock
- packetBuffer[2] = 6; // Polling Interval
- packetBuffer[3] = 0xEC; // Peer Clock Precision
- // 8 bytes of zero for Root Delay & Root Dispersion
- packetBuffer[12] = 49;
- packetBuffer[13] = 0x4E;
- packetBuffer[14] = 49;
- packetBuffer[15] = 52;
-
- // all NTP fields have been given values, now
- // you can send a packet requesting a timestamp:
- Udp.beginPacket(address, 123); // NTP requests are to port 123
- Udp.write(packetBuffer, NTP_PACKET_SIZE);
- Udp.endPacket();
-}
diff --git a/lib/Ethernet/examples/WebClient/WebClient.ino b/lib/Ethernet/examples/WebClient/WebClient.ino
deleted file mode 100644
index f4a5d02..0000000
--- a/lib/Ethernet/examples/WebClient/WebClient.ino
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- Web client
-
- This sketch connects to a website (http://www.google.com)
- using an Arduino WIZnet Ethernet shield.
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
-
- created 18 Dec 2009
- by David A. Mellis
- modified 9 Apr 2012
- by Tom Igoe, based on work by Adrian McEwen
-
- */
-
-#include
-#include
-
-// Enter a MAC address for your controller below.
-// Newer Ethernet shields have a MAC address printed on a sticker on the shield
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-
-// if you don't want to use DNS (and reduce your sketch size)
-// use the numeric IP instead of the name for the server:
-//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
-char server[] = "www.google.com"; // name address for Google (using DNS)
-
-// Set the static IP address to use if the DHCP fails to assign
-IPAddress ip(192, 168, 0, 177);
-IPAddress myDns(192, 168, 0, 1);
-
-// Initialize the Ethernet client library
-// with the IP address and port of the server
-// that you want to connect to (port 80 is default for HTTP):
-EthernetClient client;
-
-// Variables to measure the speed
-unsigned long beginMicros, endMicros;
-unsigned long byteCount = 0;
-bool printWebData = true; // set to false for better speed measurement
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // start the Ethernet connection:
- Serial.println("Initialize Ethernet with DHCP:");
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
- // try to configure using IP address instead of DHCP:
- Ethernet.begin(mac, ip, myDns);
- } else {
- Serial.print(" DHCP assigned IP ");
- Serial.println(Ethernet.localIP());
- }
- // give the Ethernet shield a second to initialize:
- delay(1000);
- Serial.print("connecting to ");
- Serial.print(server);
- Serial.println("...");
-
- // if you get a connection, report back via serial:
- if (client.connect(server, 80)) {
- Serial.print("connected to ");
- Serial.println(client.remoteIP());
- // Make a HTTP request:
- client.println("GET /search?q=arduino HTTP/1.1");
- client.println("Host: www.google.com");
- client.println("Connection: close");
- client.println();
- } else {
- // if you didn't get a connection to the server:
- Serial.println("connection failed");
- }
- beginMicros = micros();
-}
-
-void loop() {
- // if there are incoming bytes available
- // from the server, read them and print them:
- int len = client.available();
- if (len > 0) {
- byte buffer[80];
- if (len > 80) len = 80;
- client.read(buffer, len);
- if (printWebData) {
- Serial.write(buffer, len); // show in the serial monitor (slows some boards)
- }
- byteCount = byteCount + len;
- }
-
- // if the server's disconnected, stop the client:
- if (!client.connected()) {
- endMicros = micros();
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- Serial.print("Received ");
- Serial.print(byteCount);
- Serial.print(" bytes in ");
- float seconds = (float)(endMicros - beginMicros) / 1000000.0;
- Serial.print(seconds, 4);
- float rate = (float)byteCount / seconds / 1000.0;
- Serial.print(", rate = ");
- Serial.print(rate);
- Serial.print(" kbytes/second");
- Serial.println();
-
- // do nothing forevermore:
- while (true) {
- delay(1);
- }
- }
-}
diff --git a/lib/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino b/lib/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino
deleted file mode 100644
index 1fb11e1..0000000
--- a/lib/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- Repeating Web client
-
- This sketch connects to a web server and makes a request
- using a WIZnet Ethernet shield. You can use the Arduino Ethernet Shield, or
- the Adafruit Ethernet shield, either one will work, as long as it's got
- a WIZnet Ethernet module on board.
-
- This example uses DNS, by assigning the Ethernet client with a MAC address,
- IP address, and DNS address.
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
-
- created 19 Apr 2012
- by Tom Igoe
- modified 21 Jan 2014
- by Federico Vanzati
-
- https://www.arduino.cc/en/Tutorial/WebClientRepeating
- This code is in the public domain.
-
- */
-
-#include
-#include
-
-// assign a MAC address for the Ethernet controller.
-// fill in your address here:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-// Set the static IP address to use if the DHCP fails to assign
-IPAddress ip(192, 168, 0, 177);
-IPAddress myDns(192, 168, 0, 1);
-
-// initialize the library instance:
-EthernetClient client;
-
-char server[] = "www.arduino.cc"; // also change the Host line in httpRequest()
-//IPAddress server(64,131,82,241);
-
-unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
-const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // start serial port:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
-
- // start the Ethernet connection:
- Serial.println("Initialize Ethernet with DHCP:");
- if (Ethernet.begin(mac) == 0) {
- Serial.println("Failed to configure Ethernet using DHCP");
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
- // try to configure using IP address instead of DHCP:
- Ethernet.begin(mac, ip, myDns);
- Serial.print("My IP address: ");
- Serial.println(Ethernet.localIP());
- } else {
- Serial.print(" DHCP assigned IP ");
- Serial.println(Ethernet.localIP());
- }
- // give the Ethernet shield a second to initialize:
- delay(1000);
-}
-
-void loop() {
- // if there's incoming data from the net connection.
- // send it out the serial port. This is for debugging
- // purposes only:
- if (client.available()) {
- char c = client.read();
- Serial.write(c);
- }
-
- // if ten seconds have passed since your last connection,
- // then connect again and send data:
- if (millis() - lastConnectionTime > postingInterval) {
- httpRequest();
- }
-
-}
-
-// this method makes a HTTP connection to the server:
-void httpRequest() {
- // close any connection before send a new request.
- // This will free the socket on the Ethernet shield
- client.stop();
-
- // if there's a successful connection:
- if (client.connect(server, 80)) {
- Serial.println("connecting...");
- // send the HTTP GET request:
- client.println("GET /latest.txt HTTP/1.1");
- client.println("Host: www.arduino.cc");
- client.println("User-Agent: arduino-ethernet");
- client.println("Connection: close");
- client.println();
-
- // note the time that the connection was made:
- lastConnectionTime = millis();
- } else {
- // if you couldn't make a connection:
- Serial.println("connection failed");
- }
-}
diff --git a/lib/Ethernet/examples/WebServer/WebServer.ino b/lib/Ethernet/examples/WebServer/WebServer.ino
deleted file mode 100644
index f3929d2..0000000
--- a/lib/Ethernet/examples/WebServer/WebServer.ino
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- Web Server
-
- A simple web server that shows the value of the analog input pins.
- using an Arduino WIZnet Ethernet shield.
-
- Circuit:
- * Ethernet shield attached to pins 10, 11, 12, 13
- * Analog inputs attached to pins A0 through A5 (optional)
-
- created 18 Dec 2009
- by David A. Mellis
- modified 9 Apr 2012
- by Tom Igoe
- modified 02 Sept 2015
- by Arturo Guadalupi
-
- */
-
-#include
-#include
-
-// Enter a MAC address and IP address for your controller below.
-// The IP address will be dependent on your local network:
-byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
-};
-IPAddress ip(192, 168, 1, 177);
-
-// Initialize the Ethernet server library
-// with the IP address and port you want to use
-// (port 80 is default for HTTP):
-EthernetServer server(80);
-
-void setup() {
- // You can use Ethernet.init(pin) to configure the CS pin
- //Ethernet.init(10); // Most Arduino shields
- //Ethernet.init(5); // MKR ETH Shield
- //Ethernet.init(0); // Teensy 2.0
- //Ethernet.init(20); // Teensy++ 2.0
- //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
- //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
-
- // Open serial communications and wait for port to open:
- Serial.begin(9600);
- while (!Serial) {
- ; // wait for serial port to connect. Needed for native USB port only
- }
- Serial.println("Ethernet WebServer Example");
-
- // start the Ethernet connection and the server:
- Ethernet.begin(mac, ip);
-
- // Check for Ethernet hardware present
- if (Ethernet.hardwareStatus() == EthernetNoHardware) {
- Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
- while (true) {
- delay(1); // do nothing, no point running without Ethernet hardware
- }
- }
- if (Ethernet.linkStatus() == LinkOFF) {
- Serial.println("Ethernet cable is not connected.");
- }
-
- // start the server
- server.begin();
- Serial.print("server is at ");
- Serial.println(Ethernet.localIP());
-}
-
-
-void loop() {
- // listen for incoming clients
- EthernetClient client = server.available();
- if (client) {
- Serial.println("new client");
- // an HTTP request ends with a blank line
- bool currentLineIsBlank = true;
- while (client.connected()) {
- if (client.available()) {
- char c = client.read();
- Serial.write(c);
- // if you've gotten to the end of the line (received a newline
- // character) and the line is blank, the HTTP request has ended,
- // so you can send a reply
- if (c == '\n' && currentLineIsBlank) {
- // send a standard HTTP response header
- client.println("HTTP/1.1 200 OK");
- client.println("Content-Type: text/html");
- client.println("Connection: close"); // the connection will be closed after completion of the response
- client.println("Refresh: 5"); // refresh the page automatically every 5 sec
- client.println();
- client.println("");
- client.println("");
- // output the value of each analog input pin
- for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
- int sensorReading = analogRead(analogChannel);
- client.print("analog input ");
- client.print(analogChannel);
- client.print(" is ");
- client.print(sensorReading);
- client.println(" ");
- }
- client.println("");
- break;
- }
- if (c == '\n') {
- // you're starting a new line
- currentLineIsBlank = true;
- } else if (c != '\r') {
- // you've gotten a character on the current line
- currentLineIsBlank = false;
- }
- }
- }
- // give the web browser time to receive the data
- delay(1);
- // close the connection:
- client.stop();
- Serial.println("client disconnected");
- }
-}
diff --git a/lib/Ethernet/keywords.txt b/lib/Ethernet/keywords.txt
deleted file mode 100644
index 9fd2541..0000000
--- a/lib/Ethernet/keywords.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-#######################################
-# Syntax Coloring Map For Ethernet
-#######################################
-
-#######################################
-# Datatypes (KEYWORD1)
-#######################################
-
-Ethernet KEYWORD1 Ethernet
-EthernetClient KEYWORD1 EthernetClient
-EthernetServer KEYWORD1 EthernetServer
-IPAddress KEYWORD1 EthernetIPAddress
-
-#######################################
-# Methods and Functions (KEYWORD2)
-#######################################
-
-status KEYWORD2
-connect KEYWORD2
-write KEYWORD2
-available KEYWORD2
-availableForWrite KEYWORD2
-read KEYWORD2
-peek KEYWORD2
-flush KEYWORD2
-stop KEYWORD2
-connected KEYWORD2
-accept KEYWORD2
-begin KEYWORD2
-beginMulticast KEYWORD2
-beginPacket KEYWORD2
-endPacket KEYWORD2
-parsePacket KEYWORD2
-remoteIP KEYWORD2
-remotePort KEYWORD2
-getSocketNumber KEYWORD2
-localIP KEYWORD2
-localPort KEYWORD2
-maintain KEYWORD2
-linkStatus KEYWORD2
-hardwareStatus KEYWORD2
-MACAddress KEYWORD2
-subnetMask KEYWORD2
-gatewayIP KEYWORD2
-dnsServerIP KEYWORD2
-setMACAddress KEYWORD2
-setLocalIP KEYWORD2
-setSubnetMask KEYWORD2
-setGatewayIP KEYWORD2
-setDnsServerIP KEYWORD2
-setRetransmissionTimeout KEYWORD2
-setRetransmissionCount KEYWORD2
-setConnectionTimeout KEYWORD2
-
-#######################################
-# Constants (LITERAL1)
-#######################################
-
-EthernetLinkStatus LITERAL1
-Unknown LITERAL1
-LinkON LITERAL1
-LinkOFF LITERAL1
-EthernetHardwareStatus LITERAL1
-EthernetNoHardware LITERAL1
-EthernetW5100 LITERAL1
-EthernetW5200 LITERAL1
-EthernetW5500 LITERAL1
diff --git a/lib/Ethernet/library.properties b/lib/Ethernet/library.properties
deleted file mode 100644
index 046e6c2..0000000
--- a/lib/Ethernet/library.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-name=Ethernet
-version=2.0.2
-author=Various (see AUTHORS file for details)
-maintainer=Arduino
-sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield.
-paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS.
-category=Communication
-url=https://www.arduino.cc/en/Reference/Ethernet
-architectures=*
-includes=Ethernet.h
\ No newline at end of file
diff --git a/lib/Ethernet/src/Dhcp.cpp b/lib/Ethernet/src/Dhcp.cpp
deleted file mode 100644
index 28df310..0000000
--- a/lib/Ethernet/src/Dhcp.cpp
+++ /dev/null
@@ -1,437 +0,0 @@
-// DHCP Library v0.3 - April 25, 2009
-// Author: Jordan Terrell - blog.jordanterrell.com
-
-#include
-#include "Ethernet.h"
-#include "Dhcp.h"
-#include "utility/w5100.h"
-
-int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
-{
- _dhcpLeaseTime=0;
- _dhcpT1=0;
- _dhcpT2=0;
- _timeout = timeout;
- _responseTimeout = responseTimeout;
-
- // zero out _dhcpMacAddr
- memset(_dhcpMacAddr, 0, 6);
- reset_DHCP_lease();
-
- memcpy((void*)_dhcpMacAddr, (void*)mac, 6);
- _dhcp_state = STATE_DHCP_START;
- return request_DHCP_lease();
-}
-
-void DhcpClass::reset_DHCP_lease()
-{
- // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp
- memset(_dhcpLocalIp, 0, sizeof(_dhcpLocalIp));
- memset(_dhcpSubnetMask, 0, sizeof(_dhcpSubnetMask));
- memset(_dhcpGatewayIp, 0, sizeof(_dhcpGatewayIp));
- memset(_dhcpDhcpServerIp, 0, sizeof(_dhcpDhcpServerIp));
- memset(_dhcpDnsServerIp, 0, sizeof(_dhcpDnsServerIp));
-}
-
- //return:0 on error, 1 if request is sent and response is received
-int DhcpClass::request_DHCP_lease()
-{
- uint8_t messageType = 0;
-
- // Pick an initial transaction ID
- _dhcpTransactionId = random(1UL, 2000UL);
- _dhcpInitialTransactionId = _dhcpTransactionId;
-
- _dhcpUdpSocket.stop();
- if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) {
- // Couldn't get a socket
- return 0;
- }
-
- presend_DHCP();
-
- int result = 0;
-
- unsigned long startTime = millis();
-
- while (_dhcp_state != STATE_DHCP_LEASED) {
- if (_dhcp_state == STATE_DHCP_START) {
- _dhcpTransactionId++;
- send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000));
- _dhcp_state = STATE_DHCP_DISCOVER;
- } else if (_dhcp_state == STATE_DHCP_REREQUEST) {
- _dhcpTransactionId++;
- send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000));
- _dhcp_state = STATE_DHCP_REQUEST;
- } else if (_dhcp_state == STATE_DHCP_DISCOVER) {
- uint32_t respId;
- messageType = parseDHCPResponse(_responseTimeout, respId);
- if (messageType == DHCP_OFFER) {
- // We'll use the transaction ID that the offer came with,
- // rather than the one we were up to
- _dhcpTransactionId = respId;
- send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000));
- _dhcp_state = STATE_DHCP_REQUEST;
- }
- } else if (_dhcp_state == STATE_DHCP_REQUEST) {
- uint32_t respId;
- messageType = parseDHCPResponse(_responseTimeout, respId);
- if (messageType == DHCP_ACK) {
- _dhcp_state = STATE_DHCP_LEASED;
- result = 1;
- //use default lease time if we didn't get it
- if (_dhcpLeaseTime == 0) {
- _dhcpLeaseTime = DEFAULT_LEASE;
- }
- // Calculate T1 & T2 if we didn't get it
- if (_dhcpT1 == 0) {
- // T1 should be 50% of _dhcpLeaseTime
- _dhcpT1 = _dhcpLeaseTime >> 1;
- }
- if (_dhcpT2 == 0) {
- // T2 should be 87.5% (7/8ths) of _dhcpLeaseTime
- _dhcpT2 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3);
- }
- _renewInSec = _dhcpT1;
- _rebindInSec = _dhcpT2;
- } else if (messageType == DHCP_NAK) {
- _dhcp_state = STATE_DHCP_START;
- }
- }
-
- if (messageType == 255) {
- messageType = 0;
- _dhcp_state = STATE_DHCP_START;
- }
-
- if (result != 1 && ((millis() - startTime) > _timeout))
- break;
- }
-
- // We're done with the socket now
- _dhcpUdpSocket.stop();
- _dhcpTransactionId++;
-
- _lastCheckLeaseMillis = millis();
- return result;
-}
-
-void DhcpClass::presend_DHCP()
-{
-}
-
-void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed)
-{
- uint8_t buffer[32];
- memset(buffer, 0, 32);
- IPAddress dest_addr(255, 255, 255, 255); // Broadcast address
-
- if (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) {
- //Serial.printf("DHCP transmit error\n");
- // FIXME Need to return errors
- return;
- }
-
- buffer[0] = DHCP_BOOTREQUEST; // op
- buffer[1] = DHCP_HTYPE10MB; // htype
- buffer[2] = DHCP_HLENETHERNET; // hlen
- buffer[3] = DHCP_HOPS; // hops
-
- // xid
- unsigned long xid = htonl(_dhcpTransactionId);
- memcpy(buffer + 4, &(xid), 4);
-
- // 8, 9 - seconds elapsed
- buffer[8] = ((secondsElapsed & 0xff00) >> 8);
- buffer[9] = (secondsElapsed & 0x00ff);
-
- // flags
- unsigned short flags = htons(DHCP_FLAGSBROADCAST);
- memcpy(buffer + 10, &(flags), 2);
-
- // ciaddr: already zeroed
- // yiaddr: already zeroed
- // siaddr: already zeroed
- // giaddr: already zeroed
-
- //put data in W5100 transmit buffer
- _dhcpUdpSocket.write(buffer, 28);
-
- memset(buffer, 0, 32); // clear local buffer
-
- memcpy(buffer, _dhcpMacAddr, 6); // chaddr
-
- //put data in W5100 transmit buffer
- _dhcpUdpSocket.write(buffer, 16);
-
- memset(buffer, 0, 32); // clear local buffer
-
- // leave zeroed out for sname && file
- // put in W5100 transmit buffer x 6 (192 bytes)
-
- for(int i = 0; i < 6; i++) {
- _dhcpUdpSocket.write(buffer, 32);
- }
-
- // OPT - Magic Cookie
- buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF);
- buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF);
- buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF);
- buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF);
-
- // OPT - message type
- buffer[4] = dhcpMessageType;
- buffer[5] = 0x01;
- buffer[6] = messageType; //DHCP_REQUEST;
-
- // OPT - client identifier
- buffer[7] = dhcpClientIdentifier;
- buffer[8] = 0x07;
- buffer[9] = 0x01;
- memcpy(buffer + 10, _dhcpMacAddr, 6);
-
- // OPT - host name
- buffer[16] = hostName;
- buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address
- strcpy((char*)&(buffer[18]), HOST_NAME);
-
- printByte((char*)&(buffer[24]), _dhcpMacAddr[3]);
- printByte((char*)&(buffer[26]), _dhcpMacAddr[4]);
- printByte((char*)&(buffer[28]), _dhcpMacAddr[5]);
-
- //put data in W5100 transmit buffer
- _dhcpUdpSocket.write(buffer, 30);
-
- if (messageType == DHCP_REQUEST) {
- buffer[0] = dhcpRequestedIPaddr;
- buffer[1] = 0x04;
- buffer[2] = _dhcpLocalIp[0];
- buffer[3] = _dhcpLocalIp[1];
- buffer[4] = _dhcpLocalIp[2];
- buffer[5] = _dhcpLocalIp[3];
-
- buffer[6] = dhcpServerIdentifier;
- buffer[7] = 0x04;
- buffer[8] = _dhcpDhcpServerIp[0];
- buffer[9] = _dhcpDhcpServerIp[1];
- buffer[10] = _dhcpDhcpServerIp[2];
- buffer[11] = _dhcpDhcpServerIp[3];
-
- //put data in W5100 transmit buffer
- _dhcpUdpSocket.write(buffer, 12);
- }
-
- buffer[0] = dhcpParamRequest;
- buffer[1] = 0x06;
- buffer[2] = subnetMask;
- buffer[3] = routersOnSubnet;
- buffer[4] = dns;
- buffer[5] = domainName;
- buffer[6] = dhcpT1value;
- buffer[7] = dhcpT2value;
- buffer[8] = endOption;
-
- //put data in W5100 transmit buffer
- _dhcpUdpSocket.write(buffer, 9);
-
- _dhcpUdpSocket.endPacket();
-}
-
-uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId)
-{
- uint8_t type = 0;
- uint8_t opt_len = 0;
-
- unsigned long startTime = millis();
-
- while (_dhcpUdpSocket.parsePacket() <= 0) {
- if ((millis() - startTime) > responseTimeout) {
- return 255;
- }
- delay(50);
- }
- // start reading in the packet
- RIP_MSG_FIXED fixedMsg;
- _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED));
-
- if (fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) {
- transactionId = ntohl(fixedMsg.xid);
- if (memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 ||
- (transactionId < _dhcpInitialTransactionId) ||
- (transactionId > _dhcpTransactionId)) {
- // Need to read the rest of the packet here regardless
- _dhcpUdpSocket.flush(); // FIXME
- return 0;
- }
-
- memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4);
-
- // Skip to the option part
- _dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED));
-
- while (_dhcpUdpSocket.available() > 0) {
- switch (_dhcpUdpSocket.read()) {
- case endOption :
- break;
-
- case padOption :
- break;
-
- case dhcpMessageType :
- opt_len = _dhcpUdpSocket.read();
- type = _dhcpUdpSocket.read();
- break;
-
- case subnetMask :
- opt_len = _dhcpUdpSocket.read();
- _dhcpUdpSocket.read(_dhcpSubnetMask, 4);
- break;
-
- case routersOnSubnet :
- opt_len = _dhcpUdpSocket.read();
- _dhcpUdpSocket.read(_dhcpGatewayIp, 4);
- _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4);
- break;
-
- case dns :
- opt_len = _dhcpUdpSocket.read();
- _dhcpUdpSocket.read(_dhcpDnsServerIp, 4);
- _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4);
- break;
-
- case dhcpServerIdentifier :
- opt_len = _dhcpUdpSocket.read();
- if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) ||
- IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) {
- _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp));
- } else {
- // Skip over the rest of this option
- _dhcpUdpSocket.read((uint8_t *)NULL, opt_len);
- }
- break;
-
- case dhcpT1value :
- opt_len = _dhcpUdpSocket.read();
- _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1));
- _dhcpT1 = ntohl(_dhcpT1);
- break;
-
- case dhcpT2value :
- opt_len = _dhcpUdpSocket.read();
- _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2));
- _dhcpT2 = ntohl(_dhcpT2);
- break;
-
- case dhcpIPaddrLeaseTime :
- opt_len = _dhcpUdpSocket.read();
- _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime));
- _dhcpLeaseTime = ntohl(_dhcpLeaseTime);
- _renewInSec = _dhcpLeaseTime;
- break;
-
- default :
- opt_len = _dhcpUdpSocket.read();
- // Skip over the rest of this option
- _dhcpUdpSocket.read((uint8_t *)NULL, opt_len);
- break;
- }
- }
- }
-
- // Need to skip to end of the packet regardless here
- _dhcpUdpSocket.flush(); // FIXME
-
- return type;
-}
-
-
-/*
- returns:
- 0/DHCP_CHECK_NONE: nothing happened
- 1/DHCP_CHECK_RENEW_FAIL: renew failed
- 2/DHCP_CHECK_RENEW_OK: renew success
- 3/DHCP_CHECK_REBIND_FAIL: rebind fail
- 4/DHCP_CHECK_REBIND_OK: rebind success
-*/
-int DhcpClass::checkLease()
-{
- int rc = DHCP_CHECK_NONE;
-
- unsigned long now = millis();
- unsigned long elapsed = now - _lastCheckLeaseMillis;
-
- // if more then one sec passed, reduce the counters accordingly
- if (elapsed >= 1000) {
- // set the new timestamps
- _lastCheckLeaseMillis = now - (elapsed % 1000);
- elapsed = elapsed / 1000;
-
- // decrease the counters by elapsed seconds
- // we assume that the cycle time (elapsed) is fairly constant
- // if the remainder is less than cycle time * 2
- // do it early instead of late
- if (_renewInSec < elapsed * 2) {
- _renewInSec = 0;
- } else {
- _renewInSec -= elapsed;
- }
- if (_rebindInSec < elapsed * 2) {
- _rebindInSec = 0;
- } else {
- _rebindInSec -= elapsed;
- }
- }
-
- // if we have a lease but should renew, do it
- if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) {
- _dhcp_state = STATE_DHCP_REREQUEST;
- rc = 1 + request_DHCP_lease();
- }
-
- // if we have a lease or is renewing but should bind, do it
- if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED ||
- _dhcp_state == STATE_DHCP_START)) {
- // this should basically restart completely
- _dhcp_state = STATE_DHCP_START;
- reset_DHCP_lease();
- rc = 3 + request_DHCP_lease();
- }
- return rc;
-}
-
-IPAddress DhcpClass::getLocalIp()
-{
- return IPAddress(_dhcpLocalIp);
-}
-
-IPAddress DhcpClass::getSubnetMask()
-{
- return IPAddress(_dhcpSubnetMask);
-}
-
-IPAddress DhcpClass::getGatewayIp()
-{
- return IPAddress(_dhcpGatewayIp);
-}
-
-IPAddress DhcpClass::getDhcpServerIp()
-{
- return IPAddress(_dhcpDhcpServerIp);
-}
-
-IPAddress DhcpClass::getDnsServerIp()
-{
- return IPAddress(_dhcpDnsServerIp);
-}
-
-void DhcpClass::printByte(char * buf, uint8_t n )
-{
- char *str = &buf[1];
- buf[0]='0';
- do {
- unsigned long m = n;
- n /= 16;
- char c = m - 16 * n;
- *str-- = c < 10 ? c + '0' : c + 'A' - 10;
- } while(n);
-}
\ No newline at end of file
diff --git a/lib/Ethernet/src/Dhcp.h b/lib/Ethernet/src/Dhcp.h
deleted file mode 100644
index 43ec4f8..0000000
--- a/lib/Ethernet/src/Dhcp.h
+++ /dev/null
@@ -1,137 +0,0 @@
-// DHCP Library v0.3 - April 25, 2009
-// Author: Jordan Terrell - blog.jordanterrell.com
-
-#ifndef Dhcp_h
-#define Dhcp_h
-
-/* DHCP state machine. */
-#define STATE_DHCP_START 0
-#define STATE_DHCP_DISCOVER 1
-#define STATE_DHCP_REQUEST 2
-#define STATE_DHCP_LEASED 3
-#define STATE_DHCP_REREQUEST 4
-#define STATE_DHCP_RELEASE 5
-
-#define DHCP_FLAGSBROADCAST 0x8000
-
-/* UDP port numbers for DHCP */
-#define DHCP_SERVER_PORT 67 /* from server to client */
-#define DHCP_CLIENT_PORT 68 /* from client to server */
-
-/* DHCP message OP code */
-#define DHCP_BOOTREQUEST 1
-#define DHCP_BOOTREPLY 2
-
-/* DHCP message type */
-#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
-
-#define DHCP_HTYPE10MB 1
-#define DHCP_HTYPE100MB 2
-
-#define DHCP_HLENETHERNET 6
-#define DHCP_HOPS 0
-#define DHCP_SECS 0
-
-#define MAGIC_COOKIE 0x63825363
-#define MAX_DHCP_OPT 16
-
-#define HOST_NAME "WIZnet"
-#define DEFAULT_LEASE (900) //default lease time in seconds
-
-#define DHCP_CHECK_NONE (0)
-#define DHCP_CHECK_RENEW_FAIL (1)
-#define DHCP_CHECK_RENEW_OK (2)
-#define DHCP_CHECK_REBIND_FAIL (3)
-#define DHCP_CHECK_REBIND_OK (4)
-
-enum
-{
- padOption = 0,
- subnetMask = 1,
- timerOffset = 2,
- routersOnSubnet = 3,
- /* timeServer = 4,
- nameServer = 5,*/
- dns = 6,
- /*logServer = 7,
- cookieServer = 8,
- lprServer = 9,
- impressServer = 10,
- resourceLocationServer = 11,*/
- hostName = 12,
- /*bootFileSize = 13,
- meritDumpFile = 14,*/
- domainName = 15,
- /*swapServer = 16,
- rootPath = 17,
- extentionsPath = 18,
- IPforwarding = 19,
- nonLocalSourceRouting = 20,
- policyFilter = 21,
- maxDgramReasmSize = 22,
- defaultIPTTL = 23,
- pathMTUagingTimeout = 24,
- pathMTUplateauTable = 25,
- ifMTU = 26,
- allSubnetsLocal = 27,
- broadcastAddr = 28,
- performMaskDiscovery = 29,
- maskSupplier = 30,
- performRouterDiscovery = 31,
- routerSolicitationAddr = 32,
- staticRoute = 33,
- trailerEncapsulation = 34,
- arpCacheTimeout = 35,
- ethernetEncapsulation = 36,
- tcpDefaultTTL = 37,
- tcpKeepaliveInterval = 38,
- tcpKeepaliveGarbage = 39,
- nisDomainName = 40,
- nisServers = 41,
- ntpServers = 42,
- vendorSpecificInfo = 43,
- netBIOSnameServer = 44,
- netBIOSdgramDistServer = 45,
- netBIOSnodeType = 46,
- netBIOSscope = 47,
- xFontServer = 48,
- xDisplayManager = 49,*/
- dhcpRequestedIPaddr = 50,
- dhcpIPaddrLeaseTime = 51,
- /*dhcpOptionOverload = 52,*/
- dhcpMessageType = 53,
- dhcpServerIdentifier = 54,
- dhcpParamRequest = 55,
- /*dhcpMsg = 56,
- dhcpMaxMsgSize = 57,*/
- dhcpT1value = 58,
- dhcpT2value = 59,
- /*dhcpClassIdentifier = 60,*/
- dhcpClientIdentifier = 61,
- endOption = 255
-};
-
-typedef struct _RIP_MSG_FIXED
-{
- uint8_t op;
- uint8_t htype;
- uint8_t hlen;
- uint8_t hops;
- uint32_t xid;
- uint16_t secs;
- uint16_t flags;
- uint8_t ciaddr[4];
- uint8_t yiaddr[4];
- uint8_t siaddr[4];
- uint8_t giaddr[4];
- uint8_t chaddr[6];
-} RIP_MSG_FIXED;
-
-#endif
diff --git a/lib/Ethernet/src/Dns.cpp b/lib/Ethernet/src/Dns.cpp
deleted file mode 100644
index dca7ce4..0000000
--- a/lib/Ethernet/src/Dns.cpp
+++ /dev/null
@@ -1,353 +0,0 @@
-// Arduino DNS client for WIZnet W5100-based Ethernet shield
-// (c) Copyright 2009-2010 MCQN Ltd.
-// Released under Apache License, version 2.0
-
-#include
-#include "Ethernet.h"
-#include "Dns.h"
-#include "utility/w5100.h"
-
-
-#define SOCKET_NONE 255
-// Various flags and header field values for a DNS message
-#define UDP_HEADER_SIZE 8
-#define DNS_HEADER_SIZE 12
-#define TTL_SIZE 4
-#define QUERY_FLAG (0)
-#define RESPONSE_FLAG (1<<15)
-#define QUERY_RESPONSE_MASK (1<<15)
-#define OPCODE_STANDARD_QUERY (0)
-#define OPCODE_INVERSE_QUERY (1<<11)
-#define OPCODE_STATUS_REQUEST (2<<11)
-#define OPCODE_MASK (15<<11)
-#define AUTHORITATIVE_FLAG (1<<10)
-#define TRUNCATION_FLAG (1<<9)
-#define RECURSION_DESIRED_FLAG (1<<8)
-#define RECURSION_AVAILABLE_FLAG (1<<7)
-#define RESP_NO_ERROR (0)
-#define RESP_FORMAT_ERROR (1)
-#define RESP_SERVER_FAILURE (2)
-#define RESP_NAME_ERROR (3)
-#define RESP_NOT_IMPLEMENTED (4)
-#define RESP_REFUSED (5)
-#define RESP_MASK (15)
-#define TYPE_A (0x0001)
-#define CLASS_IN (0x0001)
-#define LABEL_COMPRESSION_MASK (0xC0)
-// Port number that DNS servers listen on
-#define DNS_PORT 53
-
-// Possible return codes from ProcessResponse
-#define SUCCESS 1
-#define TIMED_OUT -1
-#define INVALID_SERVER -2
-#define TRUNCATED -3
-#define INVALID_RESPONSE -4
-
-void DNSClient::begin(const IPAddress& aDNSServer)
-{
- iDNSServer = aDNSServer;
- iRequestId = 0;
-}
-
-
-int DNSClient::inet_aton(const char* address, IPAddress& result)
-{
- uint16_t acc = 0; // Accumulator
- uint8_t dots = 0;
-
- while (*address) {
- char c = *address++;
- if (c >= '0' && c <= '9') {
- acc = acc * 10 + (c - '0');
- if (acc > 255) {
- // Value out of [0..255] range
- return 0;
- }
- } else if (c == '.') {
- if (dots == 3) {
- // Too much dots (there must be 3 dots)
- return 0;
- }
- result[dots++] = acc;
- acc = 0;
- } else {
- // Invalid char
- return 0;
- }
- }
-
- if (dots != 3) {
- // Too few dots (there must be 3 dots)
- return 0;
- }
- result[3] = acc;
- return 1;
-}
-
-int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout)
-{
- int ret = 0;
-
- // See if it's a numeric IP address
- if (inet_aton(aHostname, aResult)) {
- // It is, our work here is done
- return 1;
- }
-
- // Check we've got a valid DNS server to use
- if (iDNSServer == INADDR_NONE) {
- return INVALID_SERVER;
- }
-
- // Find a socket to use
- if (iUdp.begin(1024+(millis() & 0xF)) == 1) {
- // Try up to three times
- int retries = 0;
- // while ((retries < 3) && (ret <= 0)) {
- // Send DNS request
- ret = iUdp.beginPacket(iDNSServer, DNS_PORT);
- if (ret != 0) {
- // Now output the request data
- ret = BuildRequest(aHostname);
- if (ret != 0) {
- // And finally send the request
- ret = iUdp.endPacket();
- if (ret != 0) {
- // Now wait for a response
- int wait_retries = 0;
- ret = TIMED_OUT;
- while ((wait_retries < 3) && (ret == TIMED_OUT)) {
- ret = ProcessResponse(timeout, aResult);
- wait_retries++;
- }
- }
- }
- }
- retries++;
- //}
-
- // We're done with the socket now
- iUdp.stop();
- }
-
- return ret;
-}
-
-uint16_t DNSClient::BuildRequest(const char* aName)
-{
- // Build header
- // 1 1 1 1 1 1
- // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // | ID |
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // | QDCOUNT |
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // | ANCOUNT |
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // | NSCOUNT |
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // | ARCOUNT |
- // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
- // As we only support one request at a time at present, we can simplify
- // some of this header
- iRequestId = millis(); // generate a random ID
- uint16_t twoByteBuffer;
-
- // FIXME We should also check that there's enough space available to write to, rather
- // FIXME than assume there's enough space (as the code does at present)
- iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId));
-
- twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG);
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
-
- twoByteBuffer = htons(1); // One question record
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
-
- twoByteBuffer = 0; // Zero answer records
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
-
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
- // and zero additional records
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
-
- // Build question
- const char* start =aName;
- const char* end =start;
- uint8_t len;
- // Run through the name being requested
- while (*end) {
- // Find out how long this section of the name is
- end = start;
- while (*end && (*end != '.') ) {
- end++;
- }
-
- if (end-start > 0) {
- // Write out the size of this section
- len = end-start;
- iUdp.write(&len, sizeof(len));
- // And then write out the section
- iUdp.write((uint8_t*)start, end-start);
- }
- start = end+1;
- }
-
- // We've got to the end of the question name, so
- // terminate it with a zero-length section
- len = 0;
- iUdp.write(&len, sizeof(len));
- // Finally the type and class of question
- twoByteBuffer = htons(TYPE_A);
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
-
- twoByteBuffer = htons(CLASS_IN); // Internet class of question
- iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
- // Success! Everything buffered okay
- return 1;
-}
-
-
-uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress)
-{
- uint32_t startTime = millis();
-
- // Wait for a response packet
- while (iUdp.parsePacket() <= 0) {
- if ((millis() - startTime) > aTimeout) {
- return TIMED_OUT;
- }
- delay(50);
- }
-
- // We've had a reply!
- // Read the UDP header
- //uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header
- union {
- uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header
- uint16_t word[DNS_HEADER_SIZE/2];
- } header;
-
- // Check that it's a response from the right server and the right port
- if ( (iDNSServer != iUdp.remoteIP()) || (iUdp.remotePort() != DNS_PORT) ) {
- // It's not from who we expected
- return INVALID_SERVER;
- }
-
- // Read through the rest of the response
- if (iUdp.available() < DNS_HEADER_SIZE) {
- return TRUNCATED;
- }
- iUdp.read(header.byte, DNS_HEADER_SIZE);
-
- uint16_t header_flags = htons(header.word[1]);
- // Check that it's a response to this request
- if ((iRequestId != (header.word[0])) ||
- ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) {
- // Mark the entire packet as read
- iUdp.flush(); // FIXME
- return INVALID_RESPONSE;
- }
- // Check for any errors in the response (or in our request)
- // although we don't do anything to get round these
- if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) {
- // Mark the entire packet as read
- iUdp.flush(); // FIXME
- return -5; //INVALID_RESPONSE;
- }
-
- // And make sure we've got (at least) one answer
- uint16_t answerCount = htons(header.word[3]);
- if (answerCount == 0) {
- // Mark the entire packet as read
- iUdp.flush(); // FIXME
- return -6; //INVALID_RESPONSE;
- }
-
- // Skip over any questions
- for (uint16_t i=0; i < htons(header.word[2]); i++) {
- // Skip over the name
- uint8_t len;
- do {
- iUdp.read(&len, sizeof(len));
- if (len > 0) {
- // Don't need to actually read the data out for the string, just
- // advance ptr to beyond it
- iUdp.read((uint8_t *)NULL, (size_t)len);
- }
- } while (len != 0);
-
- // Now jump over the type and class
- iUdp.read((uint8_t *)NULL, 4);
- }
-
- // Now we're up to the bit we're interested in, the answer
- // There might be more than one answer (although we'll just use the first
- // type A answer) and some authority and additional resource records but
- // we're going to ignore all of them.
-
- for (uint16_t i=0; i < answerCount; i++) {
- // Skip the name
- uint8_t len;
- do {
- iUdp.read(&len, sizeof(len));
- if ((len & LABEL_COMPRESSION_MASK) == 0) {
- // It's just a normal label
- if (len > 0) {
- // And it's got a length
- // Don't need to actually read the data out for the string,
- // just advance ptr to beyond it
- iUdp.read((uint8_t *)NULL, len);
- }
- } else {
- // This is a pointer to a somewhere else in the message for the
- // rest of the name. We don't care about the name, and RFC1035
- // says that a name is either a sequence of labels ended with a
- // 0 length octet or a pointer or a sequence of labels ending in
- // a pointer. Either way, when we get here we're at the end of
- // the name
- // Skip over the pointer
- iUdp.read((uint8_t *)NULL, 1); // we don't care about the byte
- // And set len so that we drop out of the name loop
- len = 0;
- }
- } while (len != 0);
-
- // Check the type and class
- uint16_t answerType;
- uint16_t answerClass;
- iUdp.read((uint8_t*)&answerType, sizeof(answerType));
- iUdp.read((uint8_t*)&answerClass, sizeof(answerClass));
-
- // Ignore the Time-To-Live as we don't do any caching
- iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes
-
- // And read out the length of this answer
- // Don't need header_flags anymore, so we can reuse it here
- iUdp.read((uint8_t*)&header_flags, sizeof(header_flags));
-
- if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) {
- if (htons(header_flags) != 4) {
- // It's a weird size
- // Mark the entire packet as read
- iUdp.flush(); // FIXME
- return -9;//INVALID_RESPONSE;
- }
- // FIXME: seems to lock up here on ESP8266, but why??
- iUdp.read(aAddress.raw_address(), 4);
- return SUCCESS;
- } else {
- // This isn't an answer type we're after, move onto the next one
- iUdp.read((uint8_t *)NULL, htons(header_flags));
- }
- }
-
- // Mark the entire packet as read
- iUdp.flush(); // FIXME
-
- // If we get here then we haven't found an answer
- return -10; //INVALID_RESPONSE;
-}
diff --git a/lib/Ethernet/src/Dns.h b/lib/Ethernet/src/Dns.h
deleted file mode 100644
index 58f9d2c..0000000
--- a/lib/Ethernet/src/Dns.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Arduino DNS client for WIZnet W5100-based Ethernet shield
-// (c) Copyright 2009-2010 MCQN Ltd.
-// Released under Apache License, version 2.0
-
-#ifndef DNSClient_h
-#define DNSClient_h
-
-#include "Ethernet.h"
-
-class DNSClient
-{
-public:
- void begin(const IPAddress& aDNSServer);
-
- /** Convert a numeric IP address string into a four-byte IP address.
- @param aIPAddrString IP address to convert
- @param aResult IPAddress structure to store the returned IP address
- @result 1 if aIPAddrString was successfully converted to an IP address,
- else error code
- */
- int inet_aton(const char *aIPAddrString, IPAddress& aResult);
-
- /** Resolve the given hostname to an IP address.
- @param aHostname Name to be resolved
- @param aResult IPAddress structure to store the returned IP address
- @result 1 if aIPAddrString was successfully converted to an IP address,
- else error code
- */
- int getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout=5000);
-
-protected:
- uint16_t BuildRequest(const char* aName);
- uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress);
-
- IPAddress iDNSServer;
- uint16_t iRequestId;
- EthernetUDP iUdp;
-};
-
-#endif
diff --git a/lib/Ethernet/src/Ethernet.cpp b/lib/Ethernet/src/Ethernet.cpp
deleted file mode 100644
index 8f6f76a..0000000
--- a/lib/Ethernet/src/Ethernet.cpp
+++ /dev/null
@@ -1,243 +0,0 @@
-/* Copyright 2018 Paul Stoffregen
- *
- * 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.
- */
-
-#include
-#include "Ethernet.h"
-#include "utility/w5100.h"
-#include "Dhcp.h"
-
-IPAddress EthernetClass::_dnsServerAddress;
-DhcpClass* EthernetClass::_dhcp = NULL;
-
-int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
-{
- static DhcpClass s_dhcp;
- _dhcp = &s_dhcp;
-
- // Initialise the basic info
- if (W5100.init() == 0) return 0;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setMACAddress(mac);
- W5100.setIPAddress(IPAddress(0,0,0,0).raw_address());
- SPI.endTransaction();
-
- // Now try to get our config info from a DHCP server
- int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout);
- if (ret == 1) {
- // We've successfully found a DHCP server and got our configuration
- // info, so set things accordingly
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
- W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
- W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
- SPI.endTransaction();
- _dnsServerAddress = _dhcp->getDnsServerIp();
- socketPortRand(micros());
- }
- return ret;
-}
-
-void EthernetClass::begin(uint8_t *mac, IPAddress ip)
-{
- // Assume the DNS server will be the machine on the same network as the local IP
- // but with last octet being '1'
- IPAddress dns = ip;
- dns[3] = 1;
- begin(mac, ip, dns);
-}
-
-void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns)
-{
- // Assume the gateway will be the machine on the same network as the local IP
- // but with last octet being '1'
- IPAddress gateway = ip;
- gateway[3] = 1;
- begin(mac, ip, dns, gateway);
-}
-
-void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway)
-{
- IPAddress subnet(255, 255, 255, 0);
- begin(mac, ip, dns, gateway, subnet);
-}
-
-void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet)
-{
- if (W5100.init() == 0) return;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setMACAddress(mac);
-#ifdef ESP8266
- W5100.setIPAddress(&ip[0]);
- W5100.setGatewayIp(&gateway[0]);
- W5100.setSubnetMask(&subnet[0]);
-#else
- W5100.setIPAddress(ip.raw_address());
- W5100.setGatewayIp(gateway.raw_address());
- W5100.setSubnetMask(subnet.raw_address());
-#endif
- SPI.endTransaction();
- _dnsServerAddress = dns;
-}
-
-void EthernetClass::init(uint8_t sspin, uint8_t sckpin, uint8_t misopin, uint8_t mosipin)
-{
- W5100.setSS(sspin);
- W5100.setSPI(sckpin, misopin, mosipin);
-}
-
-EthernetLinkStatus EthernetClass::linkStatus()
-{
- switch (W5100.getLinkStatus()) {
- case UNKNOWN: return Unknown;
- case LINK_ON: return LinkON;
- case LINK_OFF: return LinkOFF;
- default: return Unknown;
- }
-}
-
-EthernetHardwareStatus EthernetClass::hardwareStatus()
-{
- switch (W5100.getChip()) {
- case 51: return EthernetW5100;
- case 52: return EthernetW5200;
- case 55: return EthernetW5500;
- default: return EthernetNoHardware;
- }
-}
-
-int EthernetClass::maintain()
-{
- int rc = DHCP_CHECK_NONE;
- if (_dhcp != NULL) {
- // we have a pointer to dhcp, use it
- rc = _dhcp->checkLease();
- switch (rc) {
- case DHCP_CHECK_NONE:
- //nothing done
- break;
- case DHCP_CHECK_RENEW_OK:
- case DHCP_CHECK_REBIND_OK:
- //we might have got a new IP.
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
- W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
- W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
- SPI.endTransaction();
- _dnsServerAddress = _dhcp->getDnsServerIp();
- break;
- default:
- //this is actually an error, it will retry though
- break;
- }
- }
- return rc;
-}
-
-
-void EthernetClass::MACAddress(uint8_t *mac_address)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.getMACAddress(mac_address);
- SPI.endTransaction();
-}
-
-IPAddress EthernetClass::localIP()
-{
- IPAddress ret;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.getIPAddress(ret.raw_address());
- SPI.endTransaction();
- return ret;
-}
-
-IPAddress EthernetClass::subnetMask()
-{
- IPAddress ret;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.getSubnetMask(ret.raw_address());
- SPI.endTransaction();
- return ret;
-}
-
-IPAddress EthernetClass::gatewayIP()
-{
- IPAddress ret;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.getGatewayIp(ret.raw_address());
- SPI.endTransaction();
- return ret;
-}
-
-void EthernetClass::setMACAddress(const uint8_t *mac_address)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setMACAddress(mac_address);
- SPI.endTransaction();
-}
-
-void EthernetClass::setLocalIP(const IPAddress local_ip)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- IPAddress ip = local_ip;
- W5100.setIPAddress(ip.raw_address());
- SPI.endTransaction();
-}
-
-void EthernetClass::setSubnetMask(const IPAddress subnet)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- IPAddress ip = subnet;
- W5100.setSubnetMask(ip.raw_address());
- SPI.endTransaction();
-}
-
-void EthernetClass::setGatewayIP(const IPAddress gateway)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- IPAddress ip = gateway;
- W5100.setGatewayIp(ip.raw_address());
- SPI.endTransaction();
-}
-
-void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds)
-{
- if (milliseconds > 6553) milliseconds = 6553;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setRetransmissionTime(milliseconds * 10);
- SPI.endTransaction();
-}
-
-void EthernetClass::setRetransmissionCount(uint8_t num)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.setRetransmissionCount(num);
- SPI.endTransaction();
-}
-
-
-
-
-
-
-
-
-
-
-EthernetClass Ethernet;
\ No newline at end of file
diff --git a/lib/Ethernet/src/Ethernet.h b/lib/Ethernet/src/Ethernet.h
deleted file mode 100644
index 5a1e780..0000000
--- a/lib/Ethernet/src/Ethernet.h
+++ /dev/null
@@ -1,323 +0,0 @@
-/* Copyright 2018 Paul Stoffregen
- *
- * 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 ethernet_h_
-#define ethernet_h_
-
-// All symbols exposed to Arduino sketches are contained in this header file
-//
-// Older versions had much of this stuff in EthernetClient.h, EthernetServer.h,
-// and socket.h. Including headers in different order could cause trouble, so
-// these "friend" classes are now defined in the same header file. socket.h
-// was removed to avoid possible conflict with the C library header files.
-
-
-// Configure the maximum number of sockets to support. W5100 chips can have
-// up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes
-// of RAM are used for each socket. Reducing the maximum can save RAM, but
-// you are limited to fewer simultaneous connections.
-#if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048)
-#define MAX_SOCK_NUM 4
-#else
-#define MAX_SOCK_NUM 8
-#endif
-
-// By default, each socket uses 2K buffers inside the WIZnet chip. If
-// MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting
-// this will use larger buffers within the WIZnet chip. Large buffers
-// can really help with UDP protocols like Artnet. In theory larger
-// buffers should allow faster TCP over high-latency links, but this
-// does not always seem to work in practice (maybe WIZnet bugs?)
-//#define ETHERNET_LARGE_BUFFERS
-
-
-#include
-#include "Client.h"
-#include "Server.h"
-#include "Udp.h"
-
-enum EthernetLinkStatus {
- Unknown,
- LinkON,
- LinkOFF
-};
-
-enum EthernetHardwareStatus {
- EthernetNoHardware,
- EthernetW5100,
- EthernetW5200,
- EthernetW5500
-};
-
-class EthernetUDP;
-class EthernetClient;
-class EthernetServer;
-class DhcpClass;
-
-class EthernetClass {
-private:
- static IPAddress _dnsServerAddress;
- static DhcpClass* _dhcp;
-public:
- // Initialise the Ethernet shield to use the provided MAC address and
- // gain the rest of the configuration through DHCP.
- // Returns 0 if the DHCP configuration failed, and 1 if it succeeded
- static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
- static int maintain();
- static EthernetLinkStatus linkStatus();
- static EthernetHardwareStatus hardwareStatus();
-
- // Manual configuration
- static void begin(uint8_t *mac, IPAddress ip);
- static void begin(uint8_t *mac, IPAddress ip, IPAddress dns);
- static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway);
- static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet);
- static void init(uint8_t sspin = 10, uint8_t sckpin = 255, uint8_t misopin = 255, uint8_t mosipin = 255);
-
- static void MACAddress(uint8_t *mac_address);
- static IPAddress localIP();
- static IPAddress subnetMask();
- static IPAddress gatewayIP();
- static IPAddress dnsServerIP() { return _dnsServerAddress; }
-
- void setMACAddress(const uint8_t *mac_address);
- void setLocalIP(const IPAddress local_ip);
- void setSubnetMask(const IPAddress subnet);
- void setGatewayIP(const IPAddress gateway);
- void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; }
- void setRetransmissionTimeout(uint16_t milliseconds);
- void setRetransmissionCount(uint8_t num);
-
- friend class EthernetClient;
- friend class EthernetServer;
- friend class EthernetUDP;
-private:
- // Opens a socket(TCP or UDP or IP_RAW mode)
- static uint8_t socketBegin(uint8_t protocol, uint16_t port);
- static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port);
- static uint8_t socketStatus(uint8_t s);
- // Close socket
- static void socketClose(uint8_t s);
- // Establish TCP connection (Active connection)
- static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port);
- // disconnect the connection
- static void socketDisconnect(uint8_t s);
- // Establish TCP connection (Passive connection)
- static uint8_t socketListen(uint8_t s);
- // Send data (TCP)
- static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len);
- static uint16_t socketSendAvailable(uint8_t s);
- // Receive data (TCP)
- static int socketRecv(uint8_t s, uint8_t * buf, int16_t len);
- static uint16_t socketRecvAvailable(uint8_t s);
- static uint8_t socketPeek(uint8_t s);
- // sets up a UDP datagram, the data for which will be provided by one
- // or more calls to bufferData and then finally sent with sendUDP.
- // return true if the datagram was successfully set up, or false if there was an error
- static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port);
- // copy up to len bytes of data from buf into a UDP datagram to be
- // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls.
- // return Number of bytes successfully buffered
- static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len);
- // Send a UDP datagram built up from a sequence of startUDP followed by one or more
- // calls to bufferData.
- // return true if the datagram was successfully sent, or false if there was an error
- static bool socketSendUDP(uint8_t s);
- // Initialize the "random" source port number
- static void socketPortRand(uint16_t n);
-};
-
-extern EthernetClass Ethernet;
-
-
-#define UDP_TX_PACKET_MAX_SIZE 24
-
-class EthernetUDP : public UDP {
-private:
- uint16_t _port; // local port to listen on
- IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed
- uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed
- uint16_t _offset; // offset into the packet being sent
-
-protected:
- uint8_t sockindex;
- uint16_t _remaining; // remaining bytes of incoming packet yet to be processed
-
-public:
- EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor
- virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
- virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
- virtual void stop(); // Finish with the UDP socket
-
- // Sending UDP packets
-
- // Start building up a packet to send to the remote host specific in ip and port
- // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
- virtual int beginPacket(IPAddress ip, uint16_t port);
- // Start building up a packet to send to the remote host specific in host and port
- // Returns 1 if successful, 0 if there was a problem resolving the hostname or port
- virtual int beginPacket(const char *host, uint16_t port);
- // Finish off this packet and send it
- // Returns 1 if the packet was sent successfully, 0 if there was an error
- virtual int endPacket();
- // Write a single byte into the packet
- virtual size_t write(uint8_t);
- // Write size bytes from buffer into the packet
- virtual size_t write(const uint8_t *buffer, size_t size);
-
- using Print::write;
-
- // Start processing the next available incoming packet
- // Returns the size of the packet in bytes, or 0 if no packets are available
- virtual int parsePacket();
- // Number of bytes remaining in the current packet
- virtual int available();
- // Read a single byte from the current packet
- virtual int read();
- // Read up to len bytes from the current packet and place them into buffer
- // Returns the number of bytes read, or 0 if none are available
- virtual int read(unsigned char* buffer, size_t len);
- // Read up to len characters from the current packet and place them into buffer
- // Returns the number of characters read, or 0 if none are available
- virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); };
- // Return the next byte from the current packet without moving on to the next byte
- virtual int peek();
- virtual void flush(); // Finish reading the current packet
-
- // Return the IP address of the host who sent the current incoming packet
- virtual IPAddress remoteIP() { return _remoteIP; };
- // Return the port of the host who sent the current incoming packet
- virtual uint16_t remotePort() { return _remotePort; };
- virtual uint16_t localPort() { return _port; }
-};
-
-
-
-
-class EthernetClient : public Client {
-public:
- EthernetClient() : _sockindex(MAX_SOCK_NUM), _timeout(1000) { }
- EthernetClient(uint8_t s) : _sockindex(s), _timeout(1000) { }
- virtual ~EthernetClient() {};
-
- uint8_t status();
- virtual int connect(IPAddress ip, uint16_t port);
- virtual int connect(const char *host, uint16_t port);
- virtual int availableForWrite(void);
- virtual size_t write(uint8_t);
- virtual size_t write(const uint8_t *buf, size_t size);
- virtual int available();
- virtual int read();
- virtual int read(uint8_t *buf, size_t size);
- virtual int peek();
- virtual void flush();
- virtual void stop();
- virtual uint8_t connected();
- virtual operator bool() { return _sockindex < MAX_SOCK_NUM; }
- virtual bool operator==(const bool value) { return bool() == value; }
- virtual bool operator!=(const bool value) { return bool() != value; }
- virtual bool operator==(const EthernetClient&);
- virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); }
- uint8_t getSocketNumber() const { return _sockindex; }
- virtual uint16_t localPort();
- virtual IPAddress remoteIP();
- virtual uint16_t remotePort();
- virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; }
-
- friend class EthernetServer;
-
- using Print::write;
-
-private:
- uint8_t _sockindex; // MAX_SOCK_NUM means client not in use
- uint16_t _timeout;
-};
-
-
-class EthernetServer : public Server {
-private:
- uint16_t _port;
-public:
- EthernetServer(uint16_t port) : _port(port) { }
- EthernetClient available();
- EthernetClient accept();
- virtual void begin();
- virtual size_t write(uint8_t);
- virtual size_t write(const uint8_t *buf, size_t size);
- virtual operator bool();
- using Print::write;
- //void statusreport();
-
- // TODO: make private when socket allocation moves to EthernetClass
- static uint16_t server_port[MAX_SOCK_NUM];
-};
-
-
-class DhcpClass {
-private:
- uint32_t _dhcpInitialTransactionId;
- uint32_t _dhcpTransactionId;
- uint8_t _dhcpMacAddr[6];
-#ifdef __arm__
- uint8_t _dhcpLocalIp[4] __attribute__((aligned(4)));
- uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4)));
- uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4)));
- uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4)));
- uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4)));
-#else
- uint8_t _dhcpLocalIp[4];
- uint8_t _dhcpSubnetMask[4];
- uint8_t _dhcpGatewayIp[4];
- uint8_t _dhcpDhcpServerIp[4];
- uint8_t _dhcpDnsServerIp[4];
-#endif
- uint32_t _dhcpLeaseTime;
- uint32_t _dhcpT1, _dhcpT2;
- uint32_t _renewInSec;
- uint32_t _rebindInSec;
- unsigned long _timeout;
- unsigned long _responseTimeout;
- unsigned long _lastCheckLeaseMillis;
- uint8_t _dhcp_state;
- EthernetUDP _dhcpUdpSocket;
-
- int request_DHCP_lease();
- void reset_DHCP_lease();
- void presend_DHCP();
- void send_DHCP_MESSAGE(uint8_t, uint16_t);
- void printByte(char *, uint8_t);
-
- uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId);
-public:
- IPAddress getLocalIp();
- IPAddress getSubnetMask();
- IPAddress getGatewayIp();
- IPAddress getDhcpServerIp();
- IPAddress getDnsServerIp();
-
- int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
- int checkLease();
-};
-
-
-
-
-
-#endif
diff --git a/lib/Ethernet/src/EthernetClient.cpp b/lib/Ethernet/src/EthernetClient.cpp
deleted file mode 100644
index 5a20c74..0000000
--- a/lib/Ethernet/src/EthernetClient.cpp
+++ /dev/null
@@ -1,213 +0,0 @@
-/* Copyright 2018 Paul Stoffregen
- *
- * 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.
- */
-
-#include
-#include "Ethernet.h"
-#include "Dns.h"
-#include "utility/w5100.h"
-
-int EthernetClient::connect(const char * host, uint16_t port)
-{
- DNSClient dns; // Look up the host first
- IPAddress remote_addr;
-
- if (_sockindex < MAX_SOCK_NUM) {
- if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) {
- Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()?
- }
- _sockindex = MAX_SOCK_NUM;
- }
- dns.begin(Ethernet.dnsServerIP());
- if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout
- return connect(remote_addr, port);
-}
-
-int EthernetClient::connect(IPAddress ip, uint16_t port)
-{
- if (_sockindex < MAX_SOCK_NUM) {
- if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) {
- Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()?
- }
- _sockindex = MAX_SOCK_NUM;
- }
-#if defined(ESP8266) || defined(ESP32)
- if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0;
-#else
- if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0;
-#endif
- _sockindex = Ethernet.socketBegin(SnMR::TCP, 0);
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- Ethernet.socketConnect(_sockindex, rawIPAddress(ip), port);
- uint32_t start = millis();
- while (1) {
- uint8_t stat = Ethernet.socketStatus(_sockindex);
- if (stat == SnSR::ESTABLISHED) return 1;
- if (stat == SnSR::CLOSE_WAIT) return 1;
- if (stat == SnSR::CLOSED) return 0;
- if (millis() - start > _timeout) break;
- delay(1);
- }
- Ethernet.socketClose(_sockindex);
- _sockindex = MAX_SOCK_NUM;
- return 0;
-}
-
-int EthernetClient::availableForWrite(void)
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- return Ethernet.socketSendAvailable(_sockindex);
-}
-
-size_t EthernetClient::write(uint8_t b)
-{
- return write(&b, 1);
-}
-
-size_t EthernetClient::write(const uint8_t *buf, size_t size)
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- if (Ethernet.socketSend(_sockindex, buf, size)) return size;
- setWriteError();
- return 0;
-}
-
-int EthernetClient::available()
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- return Ethernet.socketRecvAvailable(_sockindex);
- // TODO: do the WIZnet chips automatically retransmit TCP ACK
- // packets if they are lost by the network? Someday this should
- // be checked by a man-in-the-middle test which discards certain
- // packets. If ACKs aren't resent, we would need to check for
- // returning 0 here and after a timeout do another Sock_RECV
- // command to cause the WIZnet chip to resend the ACK packet.
-}
-
-int EthernetClient::read(uint8_t *buf, size_t size)
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- return Ethernet.socketRecv(_sockindex, buf, size);
-}
-
-int EthernetClient::peek()
-{
- if (_sockindex >= MAX_SOCK_NUM) return -1;
- if (!available()) return -1;
- return Ethernet.socketPeek(_sockindex);
-}
-
-int EthernetClient::read()
-{
- uint8_t b;
- if (Ethernet.socketRecv(_sockindex, &b, 1) > 0) return b;
- return -1;
-}
-
-void EthernetClient::flush()
-{
- while (_sockindex < MAX_SOCK_NUM) {
- uint8_t stat = Ethernet.socketStatus(_sockindex);
- if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return;
- if (Ethernet.socketSendAvailable(_sockindex) >= W5100.SSIZE) return;
- }
-}
-
-void EthernetClient::stop()
-{
- if (_sockindex >= MAX_SOCK_NUM) return;
-
- // attempt to close the connection gracefully (send a FIN to other side)
- Ethernet.socketDisconnect(_sockindex);
- unsigned long start = millis();
-
- // wait up to a second for the connection to close
- do {
- if (Ethernet.socketStatus(_sockindex) == SnSR::CLOSED) {
- _sockindex = MAX_SOCK_NUM;
- return; // exit the loop
- }
- delay(1);
- } while (millis() - start < _timeout);
-
- // if it hasn't closed, close it forcefully
- Ethernet.socketClose(_sockindex);
- _sockindex = MAX_SOCK_NUM;
-}
-
-uint8_t EthernetClient::connected()
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
-
- uint8_t s = Ethernet.socketStatus(_sockindex);
- return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
- (s == SnSR::CLOSE_WAIT && !available()));
-}
-
-uint8_t EthernetClient::status()
-{
- if (_sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED;
- return Ethernet.socketStatus(_sockindex);
-}
-
-// the next function allows us to use the client returned by
-// EthernetServer::available() as the condition in an if-statement.
-bool EthernetClient::operator==(const EthernetClient& rhs)
-{
- if (_sockindex != rhs._sockindex) return false;
- if (_sockindex >= MAX_SOCK_NUM) return false;
- if (rhs._sockindex >= MAX_SOCK_NUM) return false;
- return true;
-}
-
-// https://github.com/per1234/EthernetMod
-// from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd
-uint16_t EthernetClient::localPort()
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- uint16_t port;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- port = W5100.readSnPORT(_sockindex);
- SPI.endTransaction();
- return port;
-}
-
-// https://github.com/per1234/EthernetMod
-// returns the remote IP address: https://forum.arduino.cc/index.php?topic=82416.0
-IPAddress EthernetClient::remoteIP()
-{
- if (_sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0);
- uint8_t remoteIParray[4];
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.readSnDIPR(_sockindex, remoteIParray);
- SPI.endTransaction();
- return IPAddress(remoteIParray);
-}
-
-// https://github.com/per1234/EthernetMod
-// from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75
-uint16_t EthernetClient::remotePort()
-{
- if (_sockindex >= MAX_SOCK_NUM) return 0;
- uint16_t port;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- port = W5100.readSnDPORT(_sockindex);
- SPI.endTransaction();
- return port;
-}
diff --git a/lib/Ethernet/src/EthernetClient.h b/lib/Ethernet/src/EthernetClient.h
deleted file mode 100644
index b5aef96..0000000
--- a/lib/Ethernet/src/EthernetClient.h
+++ /dev/null
@@ -1,3 +0,0 @@
-// This file is in the public domain. No copyright is claimed.
-
-#include "Ethernet.h"
diff --git a/lib/Ethernet/src/EthernetServer.cpp b/lib/Ethernet/src/EthernetServer.cpp
deleted file mode 100644
index ddebd15..0000000
--- a/lib/Ethernet/src/EthernetServer.cpp
+++ /dev/null
@@ -1,179 +0,0 @@
-/* Copyright 2018 Paul Stoffregen
- *
- * 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.
- */
-
-#include
-#include "Ethernet.h"
-#include "utility/w5100.h"
-
-uint16_t EthernetServer::server_port[MAX_SOCK_NUM];
-
-
-void EthernetServer::begin()
-{
- uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port);
- if (sockindex < MAX_SOCK_NUM) {
- if (Ethernet.socketListen(sockindex)) {
- server_port[sockindex] = _port;
- } else {
- Ethernet.socketDisconnect(sockindex);
- }
- }
-}
-
-EthernetClient EthernetServer::available()
-{
- bool listening = false;
- uint8_t sockindex = MAX_SOCK_NUM;
- uint8_t chip, maxindex=MAX_SOCK_NUM;
-
- chip = W5100.getChip();
- if (!chip) return EthernetClient(MAX_SOCK_NUM);
-#if MAX_SOCK_NUM > 4
- if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
-#endif
- for (uint8_t i=0; i < maxindex; i++) {
- if (server_port[i] == _port) {
- uint8_t stat = Ethernet.socketStatus(i);
- if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) {
- if (Ethernet.socketRecvAvailable(i) > 0) {
- sockindex = i;
- } else {
- // remote host closed connection, our end still open
- if (stat == SnSR::CLOSE_WAIT) {
- Ethernet.socketDisconnect(i);
- // status becomes LAST_ACK for short time
- }
- }
- } else if (stat == SnSR::LISTEN) {
- listening = true;
- } else if (stat == SnSR::CLOSED) {
- server_port[i] = 0;
- }
- }
- }
- if (!listening) begin();
- return EthernetClient(sockindex);
-}
-
-EthernetClient EthernetServer::accept()
-{
- bool listening = false;
- uint8_t sockindex = MAX_SOCK_NUM;
- uint8_t chip, maxindex=MAX_SOCK_NUM;
-
- chip = W5100.getChip();
- if (!chip) return EthernetClient(MAX_SOCK_NUM);
-#if MAX_SOCK_NUM > 4
- if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
-#endif
- for (uint8_t i=0; i < maxindex; i++) {
- if (server_port[i] == _port) {
- uint8_t stat = Ethernet.socketStatus(i);
- if (sockindex == MAX_SOCK_NUM &&
- (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT)) {
- // Return the connected client even if no data received.
- // Some protocols like FTP expect the server to send the
- // first data.
- sockindex = i;
- server_port[i] = 0; // only return the client once
- } else if (stat == SnSR::LISTEN) {
- listening = true;
- } else if (stat == SnSR::CLOSED) {
- server_port[i] = 0;
- }
- }
- }
- if (!listening) begin();
- return EthernetClient(sockindex);
-}
-
-EthernetServer::operator bool()
-{
- uint8_t maxindex=MAX_SOCK_NUM;
-#if MAX_SOCK_NUM > 4
- if (W5100.getChip() == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
-#endif
- for (uint8_t i=0; i < maxindex; i++) {
- if (server_port[i] == _port) {
- if (Ethernet.socketStatus(i) == SnSR::LISTEN) {
- return true; // server is listening for incoming clients
- }
- }
- }
- return false;
-}
-
-#if 0
-void EthernetServer::statusreport()
-{
- Serial.printf("EthernetServer, port=%d\n", _port);
- for (uint8_t i=0; i < MAX_SOCK_NUM; i++) {
- uint16_t port = server_port[i];
- uint8_t stat = Ethernet.socketStatus(i);
- const char *name;
- switch (stat) {
- case 0x00: name = "CLOSED"; break;
- case 0x13: name = "INIT"; break;
- case 0x14: name = "LISTEN"; break;
- case 0x15: name = "SYNSENT"; break;
- case 0x16: name = "SYNRECV"; break;
- case 0x17: name = "ESTABLISHED"; break;
- case 0x18: name = "FIN_WAIT"; break;
- case 0x1A: name = "CLOSING"; break;
- case 0x1B: name = "TIME_WAIT"; break;
- case 0x1C: name = "CLOSE_WAIT"; break;
- case 0x1D: name = "LAST_ACK"; break;
- case 0x22: name = "UDP"; break;
- case 0x32: name = "IPRAW"; break;
- case 0x42: name = "MACRAW"; break;
- case 0x5F: name = "PPPOE"; break;
- default: name = "???";
- }
- int avail = Ethernet.socketRecvAvailable(i);
- Serial.printf(" %d: port=%d, status=%s (0x%02X), avail=%d\n",
- i, port, name, stat, avail);
- }
-}
-#endif
-
-size_t EthernetServer::write(uint8_t b)
-{
- return write(&b, 1);
-}
-
-size_t EthernetServer::write(const uint8_t *buffer, size_t size)
-{
- uint8_t chip, maxindex=MAX_SOCK_NUM;
-
- chip = W5100.getChip();
- if (!chip) return 0;
-#if MAX_SOCK_NUM > 4
- if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
-#endif
- available();
- for (uint8_t i=0; i < maxindex; i++) {
- if (server_port[i] == _port) {
- if (Ethernet.socketStatus(i) == SnSR::ESTABLISHED) {
- Ethernet.socketSend(i, buffer, size);
- }
- }
- }
- return size;
-}
diff --git a/lib/Ethernet/src/EthernetServer.h b/lib/Ethernet/src/EthernetServer.h
deleted file mode 100644
index b5aef96..0000000
--- a/lib/Ethernet/src/EthernetServer.h
+++ /dev/null
@@ -1,3 +0,0 @@
-// This file is in the public domain. No copyright is claimed.
-
-#include "Ethernet.h"
diff --git a/lib/Ethernet/src/EthernetUdp.cpp b/lib/Ethernet/src/EthernetUdp.cpp
deleted file mode 100644
index e28791f..0000000
--- a/lib/Ethernet/src/EthernetUdp.cpp
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield.
- * This version only offers minimal wrapping of socket.cpp
- * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/
- *
- * MIT License:
- * Copyright (c) 2008 Bjoern Hartmann
- * 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.
- *
- * bjoern@cs.stanford.edu 12/30/2008
- */
-
-#include
-#include "Ethernet.h"
-#include "Dns.h"
-#include "utility/w5100.h"
-
-/* Start EthernetUDP socket, listening at local port PORT */
-uint8_t EthernetUDP::begin(uint16_t port)
-{
- if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex);
- sockindex = Ethernet.socketBegin(SnMR::UDP, port);
- if (sockindex >= MAX_SOCK_NUM) return 0;
- _port = port;
- _remaining = 0;
- return 1;
-}
-
-/* return number of bytes available in the current packet,
- will return zero if parsePacket hasn't been called yet */
-int EthernetUDP::available()
-{
- return _remaining;
-}
-
-/* Release any resources being used by this EthernetUDP instance */
-void EthernetUDP::stop()
-{
- if (sockindex < MAX_SOCK_NUM) {
- Ethernet.socketClose(sockindex);
- sockindex = MAX_SOCK_NUM;
- }
-}
-
-int EthernetUDP::beginPacket(const char *host, uint16_t port)
-{
- // Look up the host first
- int ret = 0;
- DNSClient dns;
- IPAddress remote_addr;
-
- dns.begin(Ethernet.dnsServerIP());
- ret = dns.getHostByName(host, remote_addr);
- if (ret != 1) return ret;
- return beginPacket(remote_addr, port);
-}
-
-int EthernetUDP::beginPacket(IPAddress ip, uint16_t port)
-{
- _offset = 0;
- //Serial.printf("UDP beginPacket\n");
- return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port);
-}
-
-int EthernetUDP::endPacket()
-{
- return Ethernet.socketSendUDP(sockindex);
-}
-
-size_t EthernetUDP::write(uint8_t byte)
-{
- return write(&byte, 1);
-}
-
-size_t EthernetUDP::write(const uint8_t *buffer, size_t size)
-{
- //Serial.printf("UDP write %d\n", size);
- uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size);
- _offset += bytes_written;
- return bytes_written;
-}
-
-int EthernetUDP::parsePacket()
-{
- // discard any remaining bytes in the last packet
- while (_remaining) {
- // could this fail (loop endlessly) if _remaining > 0 and recv in read fails?
- // should only occur if recv fails after telling us the data is there, lets
- // hope the w5100 always behaves :)
- read((uint8_t *)NULL, _remaining);
- }
-
- if (Ethernet.socketRecvAvailable(sockindex) > 0) {
- //HACK - hand-parse the UDP packet using TCP recv method
- uint8_t tmpBuf[8];
- int ret=0;
- //read 8 header bytes and get IP and port from it
- ret = Ethernet.socketRecv(sockindex, tmpBuf, 8);
- if (ret > 0) {
- _remoteIP = tmpBuf;
- _remotePort = tmpBuf[4];
- _remotePort = (_remotePort << 8) + tmpBuf[5];
- _remaining = tmpBuf[6];
- _remaining = (_remaining << 8) + tmpBuf[7];
-
- // When we get here, any remaining bytes are the data
- ret = _remaining;
- }
- return ret;
- }
- // There aren't any packets available
- return 0;
-}
-
-int EthernetUDP::read()
-{
- uint8_t byte;
-
- if ((_remaining > 0) && (Ethernet.socketRecv(sockindex, &byte, 1) > 0)) {
- // We read things without any problems
- _remaining--;
- return byte;
- }
-
- // If we get here, there's no data available
- return -1;
-}
-
-int EthernetUDP::read(unsigned char *buffer, size_t len)
-{
- if (_remaining > 0) {
- int got;
- if (_remaining <= len) {
- // data should fit in the buffer
- got = Ethernet.socketRecv(sockindex, buffer, _remaining);
- } else {
- // too much data for the buffer,
- // grab as much as will fit
- got = Ethernet.socketRecv(sockindex, buffer, len);
- }
- if (got > 0) {
- _remaining -= got;
- //Serial.printf("UDP read %d\n", got);
- return got;
- }
- }
- // If we get here, there's no data available or recv failed
- return -1;
-}
-
-int EthernetUDP::peek()
-{
- // Unlike recv, peek doesn't check to see if there's any data available, so we must.
- // If the user hasn't called parsePacket yet then return nothing otherwise they
- // may get the UDP header
- if (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1;
- return Ethernet.socketPeek(sockindex);
-}
-
-void EthernetUDP::flush()
-{
- // TODO: we should wait for TX buffer to be emptied
-}
-
-/* Start EthernetUDP socket, listening at local port PORT */
-uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port)
-{
- if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex);
- sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port);
- if (sockindex >= MAX_SOCK_NUM) return 0;
- _port = port;
- _remaining = 0;
- return 1;
-}
diff --git a/lib/Ethernet/src/EthernetUdp.h b/lib/Ethernet/src/EthernetUdp.h
deleted file mode 100644
index 16bb062..0000000
--- a/lib/Ethernet/src/EthernetUdp.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield.
- * This version only offers minimal wrapping of socket.cpp
- * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/
- *
- * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these)
- * 1) UDP does not guarantee the order in which assembled UDP packets are received. This
- * might not happen often in practice, but in larger network topologies, a UDP
- * packet can be received out of sequence.
- * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being
- * aware of it. Again, this may not be a concern in practice on small local networks.
- * For more information, see http://www.cafeaulait.org/course/week12/35.html
- *
- * MIT License:
- * Copyright (c) 2008 Bjoern Hartmann
- * 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.
- *
- * bjoern@cs.stanford.edu 12/30/2008
- */
-
-#include "Ethernet.h"
-
diff --git a/lib/Ethernet/src/socket.cpp b/lib/Ethernet/src/socket.cpp
deleted file mode 100644
index 7dc83fe..0000000
--- a/lib/Ethernet/src/socket.cpp
+++ /dev/null
@@ -1,538 +0,0 @@
-/* Copyright 2018 Paul Stoffregen
- *
- * 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.
- */
-
-#include
-#include "Ethernet.h"
-#include "utility/w5100.h"
-
-#if ARDUINO >= 156 && !defined(ARDUINO_ARCH_PIC32)
-extern void yield(void);
-#else
-#define yield()
-#endif
-
-// TODO: randomize this when not using DHCP, but how?
-static uint16_t local_port = 49152; // 49152 to 65535
-
-typedef struct {
- uint16_t RX_RSR; // Number of bytes received
- uint16_t RX_RD; // Address to read
- uint16_t TX_FSR; // Free space ready for transmit
- uint8_t RX_inc; // how much have we advanced RX_RD
-} socketstate_t;
-
-static socketstate_t state[MAX_SOCK_NUM];
-
-
-static uint16_t getSnTX_FSR(uint8_t s);
-static uint16_t getSnRX_RSR(uint8_t s);
-static void write_data(uint8_t s, uint16_t offset, const uint8_t *data, uint16_t len);
-static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len);
-
-
-
-/*****************************************/
-/* Socket management */
-/*****************************************/
-
-
-void EthernetClass::socketPortRand(uint16_t n)
-{
- n &= 0x3FFF;
- local_port ^= n;
- //Serial.printf("socketPortRand %d, srcport=%d\n", n, local_port);
-}
-
-uint8_t EthernetClass::socketBegin(uint8_t protocol, uint16_t port)
-{
- uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM;
-
- // first check hardware compatibility
- chip = W5100.getChip();
- if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected
-#if MAX_SOCK_NUM > 4
- if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
-#endif
- //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port);
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- // look at all the hardware sockets, use any that are closed (unused)
- for (s=0; s < maxindex; s++) {
- status[s] = W5100.readSnSR(s);
- if (status[s] == SnSR::CLOSED) goto makesocket;
- }
- //Serial.printf("W5000socket step2\n");
- // as a last resort, forcibly close any already closing
- for (s=0; s < maxindex; s++) {
- uint8_t stat = status[s];
- if (stat == SnSR::LAST_ACK) goto closemakesocket;
- if (stat == SnSR::TIME_WAIT) goto closemakesocket;
- if (stat == SnSR::FIN_WAIT) goto closemakesocket;
- if (stat == SnSR::CLOSING) goto closemakesocket;
- }
-#if 0
- Serial.printf("W5000socket step3\n");
- // next, use any that are effectively closed
- for (s=0; s < MAX_SOCK_NUM; s++) {
- uint8_t stat = status[s];
- // TODO: this also needs to check if no more data
- if (stat == SnSR::CLOSE_WAIT) goto closemakesocket;
- }
-#endif
- SPI.endTransaction();
- return MAX_SOCK_NUM; // all sockets are in use
-closemakesocket:
- //Serial.printf("W5000socket close\n");
- W5100.execCmdSn(s, Sock_CLOSE);
-makesocket:
- //Serial.printf("W5000socket %d\n", s);
- EthernetServer::server_port[s] = 0;
- delayMicroseconds(250); // TODO: is this needed??
- W5100.writeSnMR(s, protocol);
- W5100.writeSnIR(s, 0xFF);
- if (port > 0) {
- W5100.writeSnPORT(s, port);
- } else {
- // if don't set the source port, set local_port number.
- if (++local_port < 49152) local_port = 49152;
- W5100.writeSnPORT(s, local_port);
- }
- W5100.execCmdSn(s, Sock_OPEN);
- state[s].RX_RSR = 0;
- state[s].RX_RD = W5100.readSnRX_RD(s); // always zero?
- state[s].RX_inc = 0;
- state[s].TX_FSR = 0;
- //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD);
- SPI.endTransaction();
- return s;
-}
-
-// multicast version to set fields before open thd
-uint8_t EthernetClass::socketBeginMulticast(uint8_t protocol, IPAddress ip, uint16_t port)
-{
- uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM;
-
- // first check hardware compatibility
- chip = W5100.getChip();
- if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected
-#if MAX_SOCK_NUM > 4
- if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
-#endif
- //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port);
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- // look at all the hardware sockets, use any that are closed (unused)
- for (s=0; s < maxindex; s++) {
- status[s] = W5100.readSnSR(s);
- if (status[s] == SnSR::CLOSED) goto makesocket;
- }
- //Serial.printf("W5000socket step2\n");
- // as a last resort, forcibly close any already closing
- for (s=0; s < maxindex; s++) {
- uint8_t stat = status[s];
- if (stat == SnSR::LAST_ACK) goto closemakesocket;
- if (stat == SnSR::TIME_WAIT) goto closemakesocket;
- if (stat == SnSR::FIN_WAIT) goto closemakesocket;
- if (stat == SnSR::CLOSING) goto closemakesocket;
- }
-#if 0
- Serial.printf("W5000socket step3\n");
- // next, use any that are effectively closed
- for (s=0; s < MAX_SOCK_NUM; s++) {
- uint8_t stat = status[s];
- // TODO: this also needs to check if no more data
- if (stat == SnSR::CLOSE_WAIT) goto closemakesocket;
- }
-#endif
- SPI.endTransaction();
- return MAX_SOCK_NUM; // all sockets are in use
-closemakesocket:
- //Serial.printf("W5000socket close\n");
- W5100.execCmdSn(s, Sock_CLOSE);
-makesocket:
- //Serial.printf("W5000socket %d\n", s);
- EthernetServer::server_port[s] = 0;
- delayMicroseconds(250); // TODO: is this needed??
- W5100.writeSnMR(s, protocol);
- W5100.writeSnIR(s, 0xFF);
- if (port > 0) {
- W5100.writeSnPORT(s, port);
- } else {
- // if don't set the source port, set local_port number.
- if (++local_port < 49152) local_port = 49152;
- W5100.writeSnPORT(s, local_port);
- }
- // Calculate MAC address from Multicast IP Address
- byte mac[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00 };
- mac[3] = ip[1] & 0x7F;
- mac[4] = ip[2];
- mac[5] = ip[3];
- W5100.writeSnDIPR(s, ip.raw_address()); //239.255.0.1
- W5100.writeSnDPORT(s, port);
- W5100.writeSnDHAR(s, mac);
- W5100.execCmdSn(s, Sock_OPEN);
- state[s].RX_RSR = 0;
- state[s].RX_RD = W5100.readSnRX_RD(s); // always zero?
- state[s].RX_inc = 0;
- state[s].TX_FSR = 0;
- //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD);
- SPI.endTransaction();
- return s;
-}
-// Return the socket's status
-//
-uint8_t EthernetClass::socketStatus(uint8_t s)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- uint8_t status = W5100.readSnSR(s);
- SPI.endTransaction();
- return status;
-}
-
-// Immediately close. If a TCP connection is established, the
-// remote host is left unaware we closed.
-//
-void EthernetClass::socketClose(uint8_t s)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.execCmdSn(s, Sock_CLOSE);
- SPI.endTransaction();
-}
-
-
-// Place the socket in listening (server) mode
-//
-uint8_t EthernetClass::socketListen(uint8_t s)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- if (W5100.readSnSR(s) != SnSR::INIT) {
- SPI.endTransaction();
- return 0;
- }
- W5100.execCmdSn(s, Sock_LISTEN);
- SPI.endTransaction();
- return 1;
-}
-
-
-// establish a TCP connection in Active (client) mode.
-//
-void EthernetClass::socketConnect(uint8_t s, uint8_t * addr, uint16_t port)
-{
- // set destination IP
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.writeSnDIPR(s, addr);
- W5100.writeSnDPORT(s, port);
- W5100.execCmdSn(s, Sock_CONNECT);
- SPI.endTransaction();
-}
-
-
-
-// Gracefully disconnect a TCP connection.
-//
-void EthernetClass::socketDisconnect(uint8_t s)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.execCmdSn(s, Sock_DISCON);
- SPI.endTransaction();
-}
-
-
-
-/*****************************************/
-/* Socket Data Receive Functions */
-/*****************************************/
-
-
-static uint16_t getSnRX_RSR(uint8_t s)
-{
-#if 1
- uint16_t val, prev;
-
- prev = W5100.readSnRX_RSR(s);
- while (1) {
- val = W5100.readSnRX_RSR(s);
- if (val == prev) {
- return val;
- }
- prev = val;
- }
-#else
- uint16_t val = W5100.readSnRX_RSR(s);
- return val;
-#endif
-}
-
-static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len)
-{
- uint16_t size;
- uint16_t src_mask;
- uint16_t src_ptr;
-
- //Serial.printf("read_data, len=%d, at:%d\n", len, src);
- src_mask = (uint16_t)src & W5100.SMASK;
- src_ptr = W5100.RBASE(s) + src_mask;
-
- if (W5100.hasOffsetAddressMapping() || src_mask + len <= W5100.SSIZE) {
- W5100.read(src_ptr, dst, len);
- } else {
- size = W5100.SSIZE - src_mask;
- W5100.read(src_ptr, dst, size);
- dst += size;
- W5100.read(W5100.RBASE(s), dst, len - size);
- }
-}
-
-// Receive data. Returns size, or -1 for no data, or 0 if connection closed
-//
-int EthernetClass::socketRecv(uint8_t s, uint8_t *buf, int16_t len)
-{
- // Check how much data is available
- int ret = state[s].RX_RSR;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- if (ret < len) {
- uint16_t rsr = getSnRX_RSR(s);
- ret = rsr - state[s].RX_inc;
- state[s].RX_RSR = ret;
- //Serial.printf("Sock_RECV, RX_RSR=%d, RX_inc=%d\n", ret, state[s].RX_inc);
- }
- if (ret == 0) {
- // No data available.
- uint8_t status = W5100.readSnSR(s);
- if ( status == SnSR::LISTEN || status == SnSR::CLOSED ||
- status == SnSR::CLOSE_WAIT ) {
- // The remote end has closed its side of the connection,
- // so this is the eof state
- ret = 0;
- } else {
- // The connection is still up, but there's no data waiting to be read
- ret = -1;
- }
- } else {
- if (ret > len) ret = len; // more data available than buffer length
- uint16_t ptr = state[s].RX_RD;
- if (buf) read_data(s, ptr, buf, ret);
- ptr += ret;
- state[s].RX_RD = ptr;
- state[s].RX_RSR -= ret;
- uint16_t inc = state[s].RX_inc + ret;
- if (inc >= 250 || state[s].RX_RSR == 0) {
- state[s].RX_inc = 0;
- W5100.writeSnRX_RD(s, ptr);
- W5100.execCmdSn(s, Sock_RECV);
- //Serial.printf("Sock_RECV cmd, RX_RD=%d, RX_RSR=%d\n",
- // state[s].RX_RD, state[s].RX_RSR);
- } else {
- state[s].RX_inc = inc;
- }
- }
- SPI.endTransaction();
- //Serial.printf("socketRecv, ret=%d\n", ret);
- return ret;
-}
-
-uint16_t EthernetClass::socketRecvAvailable(uint8_t s)
-{
- uint16_t ret = state[s].RX_RSR;
- if (ret == 0) {
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- uint16_t rsr = getSnRX_RSR(s);
- SPI.endTransaction();
- ret = rsr - state[s].RX_inc;
- state[s].RX_RSR = ret;
- //Serial.printf("sockRecvAvailable s=%d, RX_RSR=%d\n", s, ret);
- }
- return ret;
-}
-
-// get the first byte in the receive queue (no checking)
-//
-uint8_t EthernetClass::socketPeek(uint8_t s)
-{
- uint8_t b;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- uint16_t ptr = state[s].RX_RD;
- W5100.read((ptr & W5100.SMASK) + W5100.RBASE(s), &b, 1);
- SPI.endTransaction();
- return b;
-}
-
-
-
-/*****************************************/
-/* Socket Data Transmit Functions */
-/*****************************************/
-
-static uint16_t getSnTX_FSR(uint8_t s)
-{
- uint16_t val, prev;
-
- prev = W5100.readSnTX_FSR(s);
- while (1) {
- val = W5100.readSnTX_FSR(s);
- if (val == prev) {
- state[s].TX_FSR = val;
- return val;
- }
- prev = val;
- }
-}
-
-
-static void write_data(uint8_t s, uint16_t data_offset, const uint8_t *data, uint16_t len)
-{
- uint16_t ptr = W5100.readSnTX_WR(s);
- ptr += data_offset;
- uint16_t offset = ptr & W5100.SMASK;
- uint16_t dstAddr = offset + W5100.SBASE(s);
-
- if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) {
- W5100.write(dstAddr, data, len);
- } else {
- // Wrap around circular buffer
- uint16_t size = W5100.SSIZE - offset;
- W5100.write(dstAddr, data, size);
- W5100.write(W5100.SBASE(s), data + size, len - size);
- }
- ptr += len;
- W5100.writeSnTX_WR(s, ptr);
-}
-
-
-/**
- * @brief This function used to send the data in TCP mode
- * @return 1 for success else 0.
- */
-uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len)
-{
- uint8_t status=0;
- uint16_t ret=0;
- uint16_t freesize=0;
-
- if (len > W5100.SSIZE) {
- ret = W5100.SSIZE; // check size not to exceed MAX size.
- } else {
- ret = len;
- }
-
- // if freebuf is available, start.
- do {
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- freesize = getSnTX_FSR(s);
- status = W5100.readSnSR(s);
- SPI.endTransaction();
- if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) {
- ret = 0;
- break;
- }
- yield();
- } while (freesize < ret);
-
- // copy data
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- write_data(s, 0, (uint8_t *)buf, ret);
- W5100.execCmdSn(s, Sock_SEND);
-
- /* +2008.01 bj */
- while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) {
- /* m2008.01 [bj] : reduce code */
- if ( W5100.readSnSR(s) == SnSR::CLOSED ) {
- SPI.endTransaction();
- return 0;
- }
- SPI.endTransaction();
- yield();
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- }
- /* +2008.01 bj */
- W5100.writeSnIR(s, SnIR::SEND_OK);
- SPI.endTransaction();
- return ret;
-}
-
-uint16_t EthernetClass::socketSendAvailable(uint8_t s)
-{
- uint8_t status=0;
- uint16_t freesize=0;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- freesize = getSnTX_FSR(s);
- status = W5100.readSnSR(s);
- SPI.endTransaction();
- if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) {
- return freesize;
- }
- return 0;
-}
-
-uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len)
-{
- //Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len);
- uint16_t ret =0;
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- uint16_t txfree = getSnTX_FSR(s);
- if (len > txfree) {
- ret = txfree; // check size not to exceed MAX size.
- } else {
- ret = len;
- }
- write_data(s, offset, buf, ret);
- SPI.endTransaction();
- return ret;
-}
-
-bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port)
-{
- if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) ||
- ((port == 0x00)) ) {
- return false;
- }
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.writeSnDIPR(s, addr);
- W5100.writeSnDPORT(s, port);
- SPI.endTransaction();
- return true;
-}
-
-bool EthernetClass::socketSendUDP(uint8_t s)
-{
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- W5100.execCmdSn(s, Sock_SEND);
-
- /* +2008.01 bj */
- while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) {
- if (W5100.readSnIR(s) & SnIR::TIMEOUT) {
- /* +2008.01 [bj]: clear interrupt */
- W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT));
- SPI.endTransaction();
- //Serial.printf("sendUDP timeout\n");
- return false;
- }
- SPI.endTransaction();
- yield();
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- }
-
- /* +2008.01 bj */
- W5100.writeSnIR(s, SnIR::SEND_OK);
- SPI.endTransaction();
-
- //Serial.printf("sendUDP ok\n");
- /* Sent ok */
- return true;
-}
diff --git a/lib/Ethernet/src/utility/w5100.cpp b/lib/Ethernet/src/utility/w5100.cpp
deleted file mode 100644
index e7ec24d..0000000
--- a/lib/Ethernet/src/utility/w5100.cpp
+++ /dev/null
@@ -1,481 +0,0 @@
-/*
- * Copyright 2018 Paul Stoffregen
- * Copyright (c) 2010 by Cristian Maglie
- *
- * This file is free software; you can redistribute it and/or modify
- * it under the terms of either the GNU General Public License version 2
- * or the GNU Lesser General Public License version 2.1, both as
- * published by the Free Software Foundation.
- */
-
-#include
-#include "Ethernet.h"
-#include "w5100.h"
-
-
-/***************************************************/
-/** Default SS pin setting **/
-/***************************************************/
-
-// If variant.h or other headers specifically define the
-// default SS pin for Ethernet, use it.
-#if defined(PIN_SPI_SS_ETHERNET_LIB)
-#define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB
-
-// MKR boards default to pin 5 for MKR ETH
-// Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10
-#elif defined(USE_ARDUINO_MKR_PIN_LAYOUT) || defined(ARDUINO_SAMD_MKRZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRVIDOR4000)
-#define SS_PIN_DEFAULT 5
-
-// For boards using AVR, assume shields with SS on pin 10
-// will be used. This allows for Arduino Mega (where
-// SS is pin 53) and Arduino Leonardo (where SS is pin 17)
-// to work by default with Arduino Ethernet Shield R2 & R3.
-#elif defined(__AVR__)
-#define SS_PIN_DEFAULT 10
-
-// If variant.h or other headers define these names
-// use them if none of the other cases match
-#elif defined(PIN_SPI_SS)
-#define SS_PIN_DEFAULT PIN_SPI_SS
-#elif defined(CORE_SS0_PIN)
-#define SS_PIN_DEFAULT CORE_SS0_PIN
-
-// As a final fallback, use pin 10
-#else
-#define SS_PIN_DEFAULT 10
-#endif
-
-
-
-
-// W5100 controller instance
-uint8_t W5100Class::chip = 0;
-uint8_t W5100Class::CH_BASE_MSB;
-uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT;
-uint8_t W5100Class::sck_pin = 255;
-uint8_t W5100Class::miso_pin = 255;
-uint8_t W5100Class::mosi_pin = 255;
-#ifdef ETHERNET_LARGE_BUFFERS
-uint16_t W5100Class::SSIZE = 2048;
-uint16_t W5100Class::SMASK = 0x07FF;
-#endif
-W5100Class W5100;
-
-// pointers and bitmasks for optimized SS pin
-#if defined(__AVR__)
- volatile uint8_t * W5100Class::ss_pin_reg;
- uint8_t W5100Class::ss_pin_mask;
-#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__)
- volatile uint8_t * W5100Class::ss_pin_reg;
-#elif defined(__MKL26Z64__)
- volatile uint8_t * W5100Class::ss_pin_reg;
- uint8_t W5100Class::ss_pin_mask;
-#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__)
- volatile uint32_t * W5100Class::ss_pin_reg;
- uint32_t W5100Class::ss_pin_mask;
-#elif defined(__PIC32MX__)
- volatile uint32_t * W5100Class::ss_pin_reg;
- uint32_t W5100Class::ss_pin_mask;
-#elif defined(ARDUINO_ARCH_ESP8266)
- volatile uint32_t * W5100Class::ss_pin_reg;
- uint32_t W5100Class::ss_pin_mask;
-#elif defined(__SAMD21G18A__)
- volatile uint32_t * W5100Class::ss_pin_reg;
- uint32_t W5100Class::ss_pin_mask;
-#endif
-
-
-uint8_t W5100Class::init(void)
-{
- static bool initialized = false;
- uint8_t i;
-
- if (initialized) return 1;
-
- // Many Ethernet shields have a CAT811 or similar reset chip
- // connected to W5100 or W5200 chips. The W5200 will not work at
- // all, and may even drive its MISO pin, until given an active low
- // reset pulse! The CAT811 has a 240 ms typical pulse length, and
- // a 400 ms worst case maximum pulse length. MAX811 has a worst
- // case maximum 560 ms pulse length. This delay is meant to wait
- // until the reset pulse is ended. If your hardware has a shorter
- // reset time, this can be edited or removed.
- delay(560);
- //Serial.println("w5100 init");
-
- if(sck_pin != 255 && miso_pin != 255 && mosi_pin != 255) {
- SPI.begin(sck_pin, miso_pin, mosi_pin, -1);
- } else {
- SPI.begin();
- }
- initSS();
- resetSS();
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
-
- // Attempt W5200 detection first, because W5200 does not properly
- // reset its SPI state when CS goes high (inactive). Communication
- // from detecting the other chips can leave the W5200 in a state
- // where it won't recover, unless given a reset pulse.
- if (isW5200()) {
- CH_BASE_MSB = 0x40;
-#ifdef ETHERNET_LARGE_BUFFERS
-#if MAX_SOCK_NUM <= 1
- SSIZE = 16384;
-#elif MAX_SOCK_NUM <= 2
- SSIZE = 8192;
-#elif MAX_SOCK_NUM <= 4
- SSIZE = 4096;
-#else
- SSIZE = 2048;
-#endif
- SMASK = SSIZE - 1;
-#endif
- for (i=0; i> 10);
- writeSnTX_SIZE(i, SSIZE >> 10);
- }
- for (; i<8; i++) {
- writeSnRX_SIZE(i, 0);
- writeSnTX_SIZE(i, 0);
- }
- // Try W5500 next. WIZnet finally seems to have implemented
- // SPI well with this chip. It appears to be very resilient,
- // so try it after the fragile W5200
- } else if (isW5500()) {
- CH_BASE_MSB = 0x10;
-#ifdef ETHERNET_LARGE_BUFFERS
-#if MAX_SOCK_NUM <= 1
- SSIZE = 16384;
-#elif MAX_SOCK_NUM <= 2
- SSIZE = 8192;
-#elif MAX_SOCK_NUM <= 4
- SSIZE = 4096;
-#else
- SSIZE = 2048;
-#endif
- SMASK = SSIZE - 1;
- for (i=0; i> 10);
- writeSnTX_SIZE(i, SSIZE >> 10);
- }
- for (; i<8; i++) {
- writeSnRX_SIZE(i, 0);
- writeSnTX_SIZE(i, 0);
- }
-#endif
- // Try W5100 last. This simple chip uses fixed 4 byte frames
- // for every 8 bit access. Terribly inefficient, but so simple
- // it recovers from "hearing" unsuccessful W5100 or W5200
- // communication. W5100 is also the only chip without a VERSIONR
- // register for identification, so we check this last.
- } else if (isW5100()) {
- CH_BASE_MSB = 0x04;
-#ifdef ETHERNET_LARGE_BUFFERS
-#if MAX_SOCK_NUM <= 1
- SSIZE = 8192;
- writeTMSR(0x03);
- writeRMSR(0x03);
-#elif MAX_SOCK_NUM <= 2
- SSIZE = 4096;
- writeTMSR(0x0A);
- writeRMSR(0x0A);
-#else
- SSIZE = 2048;
- writeTMSR(0x55);
- writeRMSR(0x55);
-#endif
- SMASK = SSIZE - 1;
-#else
- writeTMSR(0x55);
- writeRMSR(0x55);
-#endif
- // No hardware seems to be present. Or it could be a W5200
- // that's heard other SPI communication if its chip select
- // pin wasn't high when a SD card or other SPI chip was used.
- } else {
- //Serial.println("no chip :-(");
- chip = 0;
- SPI.endTransaction();
- return 0; // no known chip is responding :-(
- }
- SPI.endTransaction();
- initialized = true;
- return 1; // successful init
-}
-
-// Soft reset the WIZnet chip, by writing to its MR register reset bit
-uint8_t W5100Class::softReset(void)
-{
- uint16_t count=0;
-
- //Serial.println("WIZnet soft reset");
- // write to reset bit
- writeMR(0x80);
- // then wait for soft reset to complete
- do {
- uint8_t mr = readMR();
- //Serial.print("mr=");
- //Serial.println(mr, HEX);
- if (mr == 0) return 1;
- delay(1);
- } while (++count < 20);
- return 0;
-}
-
-uint8_t W5100Class::isW5100(void)
-{
- chip = 51;
- //Serial.println("w5100.cpp: detect W5100 chip");
- if (!softReset()) return 0;
- writeMR(0x10);
- if (readMR() != 0x10) return 0;
- writeMR(0x12);
- if (readMR() != 0x12) return 0;
- writeMR(0x00);
- if (readMR() != 0x00) return 0;
- //Serial.println("chip is W5100");
- return 1;
-}
-
-uint8_t W5100Class::isW5200(void)
-{
- chip = 52;
- //Serial.println("w5100.cpp: detect W5200 chip");
- if (!softReset()) return 0;
- writeMR(0x08);
- if (readMR() != 0x08) return 0;
- writeMR(0x10);
- if (readMR() != 0x10) return 0;
- writeMR(0x00);
- if (readMR() != 0x00) return 0;
- int ver = readVERSIONR_W5200();
- //Serial.print("version=");
- //Serial.println(ver);
- if (ver != 3) return 0;
- //Serial.println("chip is W5200");
- return 1;
-}
-
-uint8_t W5100Class::isW5500(void)
-{
- chip = 55;
- //Serial.println("w5100.cpp: detect W5500 chip");
- if (!softReset()) return 0;
- writeMR(0x08);
- if (readMR() != 0x08) return 0;
- writeMR(0x10);
- if (readMR() != 0x10) return 0;
- writeMR(0x00);
- if (readMR() != 0x00) return 0;
- int ver = readVERSIONR_W5500();
- //Serial.print("version=");
- //Serial.println(ver);
- if (ver != 4) return 0;
- //Serial.println("chip is W5500");
- return 1;
-}
-
-W5100Linkstatus W5100Class::getLinkStatus()
-{
- uint8_t phystatus;
-
- if (!init()) return UNKNOWN;
- switch (chip) {
- case 52:
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- phystatus = readPSTATUS_W5200();
- SPI.endTransaction();
- if (phystatus & 0x20) return LINK_ON;
- return LINK_OFF;
- case 55:
- SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
- phystatus = readPHYCFGR_W5500();
- SPI.endTransaction();
- if (phystatus & 0x01) return LINK_ON;
- return LINK_OFF;
- default:
- return UNKNOWN;
- }
-}
-
-uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len)
-{
- uint8_t cmd[8];
-
- if (chip == 51) {
- for (uint16_t i=0; i> 8);
- SPI.transfer(addr & 0xFF);
- addr++;
- SPI.transfer(buf[i]);
- resetSS();
- }
- } else if (chip == 52) {
- setSS();
- cmd[0] = addr >> 8;
- cmd[1] = addr & 0xFF;
- cmd[2] = ((len >> 8) & 0x7F) | 0x80;
- cmd[3] = len & 0xFF;
- SPI.transfer(cmd, 4);
-#ifdef SPI_HAS_TRANSFER_BUF
- SPI.transfer(buf, NULL, len);
-#else
- // TODO: copy 8 bytes at a time to cmd[] and block transfer
- for (uint16_t i=0; i < len; i++) {
- SPI.transfer(buf[i]);
- }
-#endif
- resetSS();
- } else { // chip == 55
- setSS();
- if (addr < 0x100) {
- // common registers 00nn
- cmd[0] = 0;
- cmd[1] = addr & 0xFF;
- cmd[2] = 0x04;
- } else if (addr < 0x8000) {
- // socket registers 10nn, 11nn, 12nn, 13nn, etc
- cmd[0] = 0;
- cmd[1] = addr & 0xFF;
- cmd[2] = ((addr >> 3) & 0xE0) | 0x0C;
- } else if (addr < 0xC000) {
- // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc
- // 10## #nnn nnnn nnnn
- cmd[0] = addr >> 8;
- cmd[1] = addr & 0xFF;
- #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
- cmd[2] = 0x14; // 16K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
- cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
- cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers
- #else
- cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers
- #endif
- } else {
- // receive buffers
- cmd[0] = addr >> 8;
- cmd[1] = addr & 0xFF;
- #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
- cmd[2] = 0x1C; // 16K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
- cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
- cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers
- #else
- cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers
- #endif
- }
- if (len <= 5) {
- for (uint8_t i=0; i < len; i++) {
- cmd[i + 3] = buf[i];
- }
- SPI.transfer(cmd, len + 3);
- } else {
- SPI.transfer(cmd, 3);
-#ifdef SPI_HAS_TRANSFER_BUF
- SPI.transfer(buf, NULL, len);
-#else
- // TODO: copy 8 bytes at a time to cmd[] and block transfer
- for (uint16_t i=0; i < len; i++) {
- SPI.transfer(buf[i]);
- }
-#endif
- }
- resetSS();
- }
- return len;
-}
-
-uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len)
-{
- uint8_t cmd[4];
-
- if (chip == 51) {
- for (uint16_t i=0; i < len; i++) {
- setSS();
- #if 1
- SPI.transfer(0x0F);
- SPI.transfer(addr >> 8);
- SPI.transfer(addr & 0xFF);
- addr++;
- buf[i] = SPI.transfer(0);
- #else
- cmd[0] = 0x0F;
- cmd[1] = addr >> 8;
- cmd[2] = addr & 0xFF;
- cmd[3] = 0;
- SPI.transfer(cmd, 4); // TODO: why doesn't this work?
- buf[i] = cmd[3];
- addr++;
- #endif
- resetSS();
- }
- } else if (chip == 52) {
- setSS();
- cmd[0] = addr >> 8;
- cmd[1] = addr & 0xFF;
- cmd[2] = (len >> 8) & 0x7F;
- cmd[3] = len & 0xFF;
- SPI.transfer(cmd, 4);
- memset(buf, 0, len);
- SPI.transfer(buf, len);
- resetSS();
- } else { // chip == 55
- setSS();
- if (addr < 0x100) {
- // common registers 00nn
- cmd[0] = 0;
- cmd[1] = addr & 0xFF;
- cmd[2] = 0x00;
- } else if (addr < 0x8000) {
- // socket registers 10nn, 11nn, 12nn, 13nn, etc
- cmd[0] = 0;
- cmd[1] = addr & 0xFF;
- cmd[2] = ((addr >> 3) & 0xE0) | 0x08;
- } else if (addr < 0xC000) {
- // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc
- // 10## #nnn nnnn nnnn
- cmd[0] = addr >> 8;
- cmd[1] = addr & 0xFF;
- #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
- cmd[2] = 0x10; // 16K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
- cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
- cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers
- #else
- cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers
- #endif
- } else {
- // receive buffers
- cmd[0] = addr >> 8;
- cmd[1] = addr & 0xFF;
- #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
- cmd[2] = 0x18; // 16K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
- cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers
- #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
- cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers
- #else
- cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers
- #endif
- }
- SPI.transfer(cmd, 3);
- memset(buf, 0, len);
- SPI.transfer(buf, len);
- resetSS();
- }
- return len;
-}
-
-void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd)
-{
- // Send command to socket
- writeSnCR(s, _cmd);
- // Wait for command to complete
- while (readSnCR(s)) ;
-}
diff --git a/lib/Ethernet/src/utility/w5100.h b/lib/Ethernet/src/utility/w5100.h
deleted file mode 100644
index 210503a..0000000
--- a/lib/Ethernet/src/utility/w5100.h
+++ /dev/null
@@ -1,487 +0,0 @@
-/*
- * Copyright 2018 Paul Stoffregen
- * Copyright (c) 2010 by Cristian Maglie
- *
- * This file is free software; you can redistribute it and/or modify
- * it under the terms of either the GNU General Public License version 2
- * or the GNU Lesser General Public License version 2.1, both as
- * published by the Free Software Foundation.
- */
-
-// w5100.h contains private W5x00 hardware "driver" level definitions
-// which are not meant to be exposed to other libraries or Arduino users
-
-#ifndef W5100_H_INCLUDED
-#define W5100_H_INCLUDED
-
-#include
-#include
-
-// Safe for all chips
-#define SPI_ETHERNET_SETTINGS SPISettings(14000000, MSBFIRST, SPI_MODE0)
-
-// Safe for W5200 and W5500, but too fast for W5100
-// Uncomment this if you know you'll never need W5100 support.
-// Higher SPI clock only results in faster transfer to hosts on a LAN
-// or with very low packet latency. With ordinary internet latency,
-// the TCP window size & packet loss determine your overall speed.
-//#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0)
-
-
-// Require Ethernet.h, because we need MAX_SOCK_NUM
-#ifndef ethernet_h_
-#error "Ethernet.h must be included before w5100.h"
-#endif
-
-
-// Arduino 101's SPI can not run faster than 8 MHz.
-#if defined(ARDUINO_ARCH_ARC32)
-#undef SPI_ETHERNET_SETTINGS
-#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0)
-#endif
-
-// Arduino Zero can't use W5100-based shields faster than 8 MHz
-// https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848
-// W5500 does seem to work at 12 MHz. Delete this if only using W5500
-#if defined(__SAMD21G18A__)
-#undef SPI_ETHERNET_SETTINGS
-#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0)
-#endif
-
-
-typedef uint8_t SOCKET;
-
-class SnMR {
-public:
- static const uint8_t CLOSE = 0x00;
- static const uint8_t TCP = 0x21;
- static const uint8_t UDP = 0x02;
- static const uint8_t IPRAW = 0x03;
- static const uint8_t MACRAW = 0x04;
- static const uint8_t PPPOE = 0x05;
- static const uint8_t ND = 0x20;
- static const uint8_t MULTI = 0x80;
-};
-
-enum SockCMD {
- Sock_OPEN = 0x01,
- Sock_LISTEN = 0x02,
- Sock_CONNECT = 0x04,
- Sock_DISCON = 0x08,
- Sock_CLOSE = 0x10,
- Sock_SEND = 0x20,
- Sock_SEND_MAC = 0x21,
- Sock_SEND_KEEP = 0x22,
- Sock_RECV = 0x40
-};
-
-class SnIR {
-public:
- static const uint8_t SEND_OK = 0x10;
- static const uint8_t TIMEOUT = 0x08;
- static const uint8_t RECV = 0x04;
- static const uint8_t DISCON = 0x02;
- static const uint8_t CON = 0x01;
-};
-
-class SnSR {
-public:
- static const uint8_t CLOSED = 0x00;
- static const uint8_t INIT = 0x13;
- static const uint8_t LISTEN = 0x14;
- static const uint8_t SYNSENT = 0x15;
- static const uint8_t SYNRECV = 0x16;
- static const uint8_t ESTABLISHED = 0x17;
- static const uint8_t FIN_WAIT = 0x18;
- static const uint8_t CLOSING = 0x1A;
- static const uint8_t TIME_WAIT = 0x1B;
- static const uint8_t CLOSE_WAIT = 0x1C;
- static const uint8_t LAST_ACK = 0x1D;
- static const uint8_t UDP = 0x22;
- static const uint8_t IPRAW = 0x32;
- static const uint8_t MACRAW = 0x42;
- static const uint8_t PPPOE = 0x5F;
-};
-
-class IPPROTO {
-public:
- static const uint8_t IP = 0;
- static const uint8_t ICMP = 1;
- static const uint8_t IGMP = 2;
- static const uint8_t GGP = 3;
- static const uint8_t TCP = 6;
- static const uint8_t PUP = 12;
- static const uint8_t UDP = 17;
- static const uint8_t IDP = 22;
- static const uint8_t ND = 77;
- static const uint8_t RAW = 255;
-};
-
-enum W5100Linkstatus {
- UNKNOWN,
- LINK_ON,
- LINK_OFF
-};
-
-class W5100Class {
-
-public:
- static uint8_t init(void);
-
- inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); }
- inline void getGatewayIp(uint8_t * addr) { readGAR(addr); }
-
- inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); }
- inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); }
-
- inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); }
- inline void getMACAddress(uint8_t * addr) { readSHAR(addr); }
-
- inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); }
- inline void getIPAddress(uint8_t * addr) { readSIPR(addr); }
-
- inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); }
- inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); }
-
- static void execCmdSn(SOCKET s, SockCMD _cmd);
-
-
- // W5100 Registers
- // ---------------
-//private:
-public:
- static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len);
- static uint8_t write(uint16_t addr, uint8_t data) {
- return write(addr, &data, 1);
- }
- static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len);
- static uint8_t read(uint16_t addr) {
- uint8_t data;
- read(addr, &data, 1);
- return data;
- }
-
-#define __GP_REGISTER8(name, address) \
- static inline void write##name(uint8_t _data) { \
- write(address, _data); \
- } \
- static inline uint8_t read##name() { \
- return read(address); \
- }
-#define __GP_REGISTER16(name, address) \
- static void write##name(uint16_t _data) { \
- uint8_t buf[2]; \
- buf[0] = _data >> 8; \
- buf[1] = _data & 0xFF; \
- write(address, buf, 2); \
- } \
- static uint16_t read##name() { \
- uint8_t buf[2]; \
- read(address, buf, 2); \
- return (buf[0] << 8) | buf[1]; \
- }
-#define __GP_REGISTER_N(name, address, size) \
- static uint16_t write##name(const uint8_t *_buff) { \
- return write(address, _buff, size); \
- } \
- static uint16_t read##name(uint8_t *_buff) { \
- return read(address, _buff, size); \
- }
- static W5100Linkstatus getLinkStatus();
-
-public:
- __GP_REGISTER8 (MR, 0x0000); // Mode
- __GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address
- __GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address
- __GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address
- __GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address
- __GP_REGISTER8 (IR, 0x0015); // Interrupt
- __GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask
- __GP_REGISTER16(RTR, 0x0017); // Timeout address
- __GP_REGISTER8 (RCR, 0x0019); // Retry count
- __GP_REGISTER8 (RMSR, 0x001A); // Receive memory size (W5100 only)
- __GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size (W5100 only)
- __GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode
- __GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer
- __GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number
- __GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode (W5100 only)
- __GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode (W5100 only)
- __GP_REGISTER8 (VERSIONR_W5200,0x001F); // Chip Version Register (W5200 only)
- __GP_REGISTER8 (VERSIONR_W5500,0x0039); // Chip Version Register (W5500 only)
- __GP_REGISTER8 (PSTATUS_W5200, 0x0035); // PHY Status
- __GP_REGISTER8 (PHYCFGR_W5500, 0x002E); // PHY Configuration register, default: 10111xxx
-
-
-#undef __GP_REGISTER8
-#undef __GP_REGISTER16
-#undef __GP_REGISTER_N
-
- // W5100 Socket registers
- // ----------------------
-private:
- static uint16_t CH_BASE(void) {
- //if (chip == 55) return 0x1000;
- //if (chip == 52) return 0x4000;
- //return 0x0400;
- return CH_BASE_MSB << 8;
- }
- static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR
- static const uint16_t CH_SIZE = 0x0100;
-
- static inline uint8_t readSn(SOCKET s, uint16_t addr) {
- return read(CH_BASE() + s * CH_SIZE + addr);
- }
- static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) {
- return write(CH_BASE() + s * CH_SIZE + addr, data);
- }
- static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) {
- return read(CH_BASE() + s * CH_SIZE + addr, buf, len);
- }
- static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) {
- return write(CH_BASE() + s * CH_SIZE + addr, buf, len);
- }
-
-#define __SOCKET_REGISTER8(name, address) \
- static inline void write##name(SOCKET _s, uint8_t _data) { \
- writeSn(_s, address, _data); \
- } \
- static inline uint8_t read##name(SOCKET _s) { \
- return readSn(_s, address); \
- }
-#define __SOCKET_REGISTER16(name, address) \
- static void write##name(SOCKET _s, uint16_t _data) { \
- uint8_t buf[2]; \
- buf[0] = _data >> 8; \
- buf[1] = _data & 0xFF; \
- writeSn(_s, address, buf, 2); \
- } \
- static uint16_t read##name(SOCKET _s) { \
- uint8_t buf[2]; \
- readSn(_s, address, buf, 2); \
- return (buf[0] << 8) | buf[1]; \
- }
-#define __SOCKET_REGISTER_N(name, address, size) \
- static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \
- return writeSn(_s, address, _buff, size); \
- } \
- static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \
- return readSn(_s, address, _buff, size); \
- }
-
-public:
- __SOCKET_REGISTER8(SnMR, 0x0000) // Mode
- __SOCKET_REGISTER8(SnCR, 0x0001) // Command
- __SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt
- __SOCKET_REGISTER8(SnSR, 0x0003) // Status
- __SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port
- __SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr
- __SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr
- __SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port
- __SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size
- __SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode
- __SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS
- __SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL
- __SOCKET_REGISTER8(SnRX_SIZE, 0x001E) // RX Memory Size (W5200 only)
- __SOCKET_REGISTER8(SnTX_SIZE, 0x001F) // RX Memory Size (W5200 only)
- __SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size
- __SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer
- __SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer
- __SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size
- __SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer
- __SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?)
-
-#undef __SOCKET_REGISTER8
-#undef __SOCKET_REGISTER16
-#undef __SOCKET_REGISTER_N
-
-
-private:
- static uint8_t chip;
- static uint8_t ss_pin;
- static uint8_t sck_pin;
- static uint8_t miso_pin;
- static uint8_t mosi_pin;
- static uint8_t softReset(void);
- static uint8_t isW5100(void);
- static uint8_t isW5200(void);
- static uint8_t isW5500(void);
-
-public:
- static uint8_t getChip(void) { return chip; }
-#ifdef ETHERNET_LARGE_BUFFERS
- static uint16_t SSIZE;
- static uint16_t SMASK;
-#else
- static const uint16_t SSIZE = 2048;
- static const uint16_t SMASK = 0x07FF;
-#endif
- static uint16_t SBASE(uint8_t socknum) {
- if (chip == 51) {
- return socknum * SSIZE + 0x4000;
- } else {
- return socknum * SSIZE + 0x8000;
- }
- }
- static uint16_t RBASE(uint8_t socknum) {
- if (chip == 51) {
- return socknum * SSIZE + 0x6000;
- } else {
- return socknum * SSIZE + 0xC000;
- }
- }
-
- static bool hasOffsetAddressMapping(void) {
- if (chip == 55) return true;
- return false;
- }
- static void setSS(uint8_t pin) { ss_pin = pin; }
- static void setSPI(uint8_t sckpin, uint8_t misopin, uint8_t mosipin) {
- sck_pin = sckpin;
- miso_pin = misopin;
- mosi_pin = mosipin;
- }
-
-private:
-#if defined(__AVR__)
- static volatile uint8_t *ss_pin_reg;
- static uint8_t ss_pin_mask;
- inline static void initSS() {
- ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin));
- ss_pin_mask = digitalPinToBitMask(ss_pin);
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- *(ss_pin_reg) &= ~ss_pin_mask;
- }
- inline static void resetSS() {
- *(ss_pin_reg) |= ss_pin_mask;
- }
-#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__)
- static volatile uint8_t *ss_pin_reg;
- inline static void initSS() {
- ss_pin_reg = portOutputRegister(ss_pin);
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- *(ss_pin_reg+256) = 1;
- }
- inline static void resetSS() {
- *(ss_pin_reg+128) = 1;
- }
-#elif defined(__MKL26Z64__)
- static volatile uint8_t *ss_pin_reg;
- static uint8_t ss_pin_mask;
- inline static void initSS() {
- ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin));
- ss_pin_mask = digitalPinToBitMask(ss_pin);
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- *(ss_pin_reg+8) = ss_pin_mask;
- }
- inline static void resetSS() {
- *(ss_pin_reg+4) = ss_pin_mask;
- }
-#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__)
- static volatile uint32_t *ss_pin_reg;
- static uint32_t ss_pin_mask;
- inline static void initSS() {
- ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER);
- ss_pin_mask = digitalPinToBitMask(ss_pin);
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- *(ss_pin_reg+13) = ss_pin_mask;
- }
- inline static void resetSS() {
- *(ss_pin_reg+12) = ss_pin_mask;
- }
-#elif defined(__PIC32MX__)
- static volatile uint32_t *ss_pin_reg;
- static uint32_t ss_pin_mask;
- inline static void initSS() {
- ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin));
- ss_pin_mask = digitalPinToBitMask(ss_pin);
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- *(ss_pin_reg+8+1) = ss_pin_mask;
- }
- inline static void resetSS() {
- *(ss_pin_reg+8+2) = ss_pin_mask;
- }
-
-#elif defined(ARDUINO_ARCH_ESP8266)
- static volatile uint32_t *ss_pin_reg;
- static uint32_t ss_pin_mask;
- inline static void initSS() {
- ss_pin_reg = (volatile uint32_t*)GPO;
- ss_pin_mask = 1 << ss_pin;
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- GPOC = ss_pin_mask;
- }
- inline static void resetSS() {
- GPOS = ss_pin_mask;
- }
-
-#elif defined(__SAMD21G18A__)
- static volatile uint32_t *ss_pin_reg;
- static uint32_t ss_pin_mask;
- inline static void initSS() {
- ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin));
- ss_pin_mask = digitalPinToBitMask(ss_pin);
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- *(ss_pin_reg+5) = ss_pin_mask;
- }
- inline static void resetSS() {
- *(ss_pin_reg+6) = ss_pin_mask;
- }
-#else
- inline static void initSS() {
- pinMode(ss_pin, OUTPUT);
- }
- inline static void setSS() {
- digitalWrite(ss_pin, LOW);
- }
- inline static void resetSS() {
- digitalWrite(ss_pin, HIGH);
- }
-#endif
-};
-
-extern W5100Class W5100;
-
-
-
-#endif
-
-#ifndef UTIL_H
-#define UTIL_H
-
-#ifndef htons
-// The host order of the Arduino platform is little endian.
-// Sometimes it is desired to convert to big endian (or
-// network order)
-
-// Host to Network short
-#define htons(x) ( (((x)&0xFF)<<8) | (((x)>>8)&0xFF) )
-
-// Network to Host short
-#define ntohs(x) htons(x)
-
-// Host to Network long
-#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \
- ((x)<< 8 & 0x00FF0000UL) | \
- ((x)>> 8 & 0x0000FF00UL) | \
- ((x)>>24 & 0x000000FFUL) )
-
-// Network to Host long
-#define ntohl(x) htonl(x)
-
-#endif // !defined(htons)
-
-#endif
diff --git a/lib/HTTPClient/examples/Authorization/Authorization.ino b/lib/HTTPClient/examples/Authorization/Authorization.ino
deleted file mode 100644
index 02bf9ae..0000000
--- a/lib/HTTPClient/examples/Authorization/Authorization.ino
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * Authorization.ino
- *
- * Created on: 09.12.2015
- *
- */
-
-#include
-
-#include
-#include
-
-#include
-
-#define USE_SERIAL Serial
-
-WiFiMulti wifiMulti;
-
-void setup() {
-
- USE_SERIAL.begin(115200);
-
- USE_SERIAL.println();
- USE_SERIAL.println();
- USE_SERIAL.println();
-
- for (uint8_t t = 4; t > 0; t--) {
- USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
- USE_SERIAL.flush();
- delay(1000);
- }
-
- wifiMulti.addAP("SSID", "PASSWORD");
-}
-
-void loop() {
- // wait for WiFi connection
- if ((wifiMulti.run() == WL_CONNECTED)) {
-
- HTTPClient http;
-
- USE_SERIAL.print("[HTTP] begin...\n");
- // configure traged server and url
-
- http.begin("http://user:password@192.168.1.12/test.html");
-
- /*
- // or
- http.begin("http://192.168.1.12/test.html");
- http.setAuthorization("user", "password");
-
- // or
- http.begin("http://192.168.1.12/test.html");
- http.setAuthorization("dXNlcjpwYXN3b3Jk");
- */
-
- USE_SERIAL.print("[HTTP] GET...\n");
- // start connection and send HTTP header
- int httpCode = http.GET();
-
- // httpCode will be negative on error
- if (httpCode > 0) {
- // HTTP header has been send and Server response header has been handled
- USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
-
- // file found at server
- if (httpCode == HTTP_CODE_OK) {
- String payload = http.getString();
- USE_SERIAL.println(payload);
- }
- } else {
- USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
- }
-
- http.end();
- }
-
- delay(10000);
-}
diff --git a/lib/HTTPClient/examples/Authorization/ci.json b/lib/HTTPClient/examples/Authorization/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/HTTPClient/examples/Authorization/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino
deleted file mode 100644
index e8f5be6..0000000
--- a/lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * BasicHTTPClient.ino
- *
- * Created on: 24.05.2015
- *
- */
-
-#include
-
-#include
-#include
-
-#include
-
-#define USE_SERIAL Serial
-
-WiFiMulti wifiMulti;
-
-/*
-const char* ca = \
-"-----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() {
-
- USE_SERIAL.begin(115200);
-
- USE_SERIAL.println();
- USE_SERIAL.println();
- USE_SERIAL.println();
-
- for (uint8_t t = 4; t > 0; t--) {
- USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
- USE_SERIAL.flush();
- delay(1000);
- }
-
- wifiMulti.addAP("SSID", "PASSWORD");
-}
-
-void loop() {
- // wait for WiFi connection
- if ((wifiMulti.run() == WL_CONNECTED)) {
-
- HTTPClient http;
-
- USE_SERIAL.print("[HTTP] begin...\n");
- // configure traged server and url
- //http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS
- http.begin("http://example.com/index.html"); //HTTP
-
- USE_SERIAL.print("[HTTP] GET...\n");
- // start connection and send HTTP header
- int httpCode = http.GET();
-
- // httpCode will be negative on error
- if (httpCode > 0) {
- // HTTP header has been send and Server response header has been handled
- USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
-
- // file found at server
- if (httpCode == HTTP_CODE_OK) {
- String payload = http.getString();
- USE_SERIAL.println(payload);
- }
- } else {
- USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
- }
-
- http.end();
- }
-
- delay(5000);
-}
diff --git a/lib/HTTPClient/examples/BasicHttpClient/ci.json b/lib/HTTPClient/examples/BasicHttpClient/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/HTTPClient/examples/BasicHttpClient/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino
deleted file mode 100644
index eb6caef..0000000
--- a/lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- BasicHTTPSClient.ino
-
- Created on: 14.10.2018
-
-*/
-
-#include
-
-#include
-#include
-
-#include
-
-#include
-
-// This is a Baltimore CyberTrust cert, the root Certificate Authority that
-// signed the server certificate for the demo server https://jigsaw.w3.org in this
-// example. This certificate is valid until Mon, 12 May 2025 23:59:00 GMT
-const char *rootCACertificate = "-----BEGIN CERTIFICATE-----\n"
- "MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\n"
- "RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\n"
- "VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\n"
- "DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\n"
- "ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\n"
- "VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\n"
- "mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\n"
- "IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\n"
- "mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\n"
- "XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\n"
- "dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\n"
- "jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\n"
- "BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\n"
- "DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n"
- "9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\n"
- "jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\n"
- "Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\n"
- "ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\n"
- "R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n"
- "-----END CERTIFICATE-----\n";
-
-// Not sure if NetworkClientSecure checks the validity date of the certificate.
-// Setting clock just to be sure...
-void setClock() {
- configTime(0, 0, "pool.ntp.org");
-
- 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() {
- NetworkClientSecure *client = new NetworkClientSecure;
- if (client) {
- client->setCACert(rootCACertificate);
-
- {
- // Add a scoping block for HTTPClient https to make sure it is destroyed before NetworkClientSecure *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/lib/HTTPClient/examples/BasicHttpsClient/ci.json b/lib/HTTPClient/examples/BasicHttpsClient/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/HTTPClient/examples/BasicHttpsClient/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino b/lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino
deleted file mode 100644
index 7f1d1dd..0000000
--- a/lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino
+++ /dev/null
@@ -1,107 +0,0 @@
-/*|----------------------------------------------------------|*/
-/*|WORKING EXAMPLE FOR HTTP/HTTPS CONNECTION |*/
-/*|TESTED BOARDS: Devkit v1 DOIT, Devkitc v4 |*/
-/*|CORE: June 2018 |*/
-/*|----------------------------------------------------------|*/
-#include
-#include
-#if __has_include("esp_eap_client.h")
-#include "esp_eap_client.h"
-#else
-#include "esp_wpa2.h"
-#endif
-#include
-#define EAP_IDENTITY "identity" //if connecting from another corporation, use identity@organization.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
-#if __has_include("esp_eap_client.h")
- esp_eap_client_set_identity((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide identity
- esp_eap_client_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username
- esp_eap_client_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password
- esp_wifi_sta_enterprise_enable();
-#else
- 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_wifi_sta_wpa2_ent_enable();
-#endif
- 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 unsuccessful 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/lib/HTTPClient/examples/HTTPClientEnterprise/ci.json b/lib/HTTPClient/examples/HTTPClientEnterprise/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/HTTPClient/examples/HTTPClientEnterprise/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino b/lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino
deleted file mode 100644
index 5b3137a..0000000
--- a/lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * reuseConnection.ino
- *
- * Created on: 22.11.2015
- *
- */
-
-#include
-
-#include
-#include
-
-#include
-
-#define USE_SERIAL Serial
-
-WiFiMulti wifiMulti;
-
-HTTPClient http;
-
-void setup() {
-
- USE_SERIAL.begin(115200);
-
- USE_SERIAL.println();
- USE_SERIAL.println();
- USE_SERIAL.println();
-
- for (uint8_t t = 4; t > 0; t--) {
- USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
- USE_SERIAL.flush();
- delay(1000);
- }
-
- wifiMulti.addAP("SSID", "PASSWORD");
-
- // allow reuse (if server supports it)
- http.setReuse(true);
-}
-
-void loop() {
- // wait for WiFi connection
- if ((wifiMulti.run() == WL_CONNECTED)) {
-
- http.begin("http://192.168.1.12/test.html");
- //http.begin("192.168.1.12", 80, "/test.html");
-
- int httpCode = http.GET();
- if (httpCode > 0) {
- USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
-
- // file found at server
- if (httpCode == HTTP_CODE_OK) {
- http.writeToStream(&USE_SERIAL);
- }
- } else {
- USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
- }
-
- http.end();
- }
-
- delay(1000);
-}
diff --git a/lib/HTTPClient/examples/ReuseConnection/ci.json b/lib/HTTPClient/examples/ReuseConnection/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/HTTPClient/examples/ReuseConnection/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino b/lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino
deleted file mode 100644
index 187526f..0000000
--- a/lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * StreamHTTPClient.ino
- *
- * Created on: 24.05.2015
- *
- */
-
-#include
-
-#include
-#include
-
-#include
-
-#define USE_SERIAL Serial
-
-WiFiMulti wifiMulti;
-
-void setup() {
-
- USE_SERIAL.begin(115200);
-
- USE_SERIAL.println();
- USE_SERIAL.println();
- USE_SERIAL.println();
-
- for (uint8_t t = 4; t > 0; t--) {
- USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
- USE_SERIAL.flush();
- delay(1000);
- }
-
- wifiMulti.addAP("SSID", "PASSWORD");
-}
-
-void loop() {
- // wait for WiFi connection
- if ((wifiMulti.run() == WL_CONNECTED)) {
-
- HTTPClient http;
-
- USE_SERIAL.print("[HTTP] begin...\n");
-
- // configure server and url
- http.begin("http://192.168.1.12/test.html");
- //http.begin("192.168.1.12", 80, "/test.html");
-
- USE_SERIAL.print("[HTTP] GET...\n");
- // start connection and send HTTP header
- int httpCode = http.GET();
- if (httpCode > 0) {
- // HTTP header has been send and Server response header has been handled
- USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
-
- // file found at server
- if (httpCode == HTTP_CODE_OK) {
-
- // get length of document (is -1 when Server sends no Content-Length header)
- int len = http.getSize();
-
- // create buffer for read
- uint8_t buff[128] = {0};
-
- // get tcp stream
- NetworkClient *stream = http.getStreamPtr();
-
- // read all data from server
- while (http.connected() && (len > 0 || len == -1)) {
- // get available data size
- size_t size = stream->available();
-
- if (size) {
- // read up to 128 byte
- int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
-
- // write it to Serial
- USE_SERIAL.write(buff, c);
-
- if (len > 0) {
- len -= c;
- }
- }
- delay(1);
- }
-
- USE_SERIAL.println();
- USE_SERIAL.print("[HTTP] connection closed or file end.\n");
- }
- } else {
- USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
- }
-
- http.end();
- }
-
- delay(10000);
-}
diff --git a/lib/HTTPClient/examples/StreamHttpClient/ci.json b/lib/HTTPClient/examples/StreamHttpClient/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/HTTPClient/examples/StreamHttpClient/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/HTTPClient/library.properties b/lib/HTTPClient/library.properties
deleted file mode 100644
index eca8d22..0000000
--- a/lib/HTTPClient/library.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-name=HTTPClient
-version=3.0.3
-author=Markus Sattler
-maintainer=Markus Sattler
-sentence=HTTP Client for ESP32
-paragraph=
-category=Communication
-url=https://github.com/espressif/arduino-esp32/tree/master/libraries/HTTPClient
-architectures=esp32
diff --git a/lib/HTTPClient/src/HTTPClient.cpp b/lib/HTTPClient/src/HTTPClient.cpp
deleted file mode 100644
index 7881a87..0000000
--- a/lib/HTTPClient/src/HTTPClient.cpp
+++ /dev/null
@@ -1,1645 +0,0 @@
-#include
-/**
- * HTTPClient.cpp
- *
- * Created on: 02.11.2015
- *
- * Copyright (c) 2015 Markus Sattler. All rights reserved.
- * This file is part of the HTTPClient for Arduino.
- * Port to ESP32 by Evandro Luis Copercini (2017),
- * changed fingerprints to CA verification.
- *
- * 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
- *
- * Adapted in October 2018
- */
-
-#include
-#include
-#include
-#include
-#include "HTTPClient.h"
-
-/// Cookie jar support
-#include
-
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
-class TransportTraits {
-public:
- virtual ~TransportTraits() {}
-
- virtual std::unique_ptr create() {
- return std::unique_ptr(new NetworkClient());
- }
-
- virtual bool verify(NetworkClient &client, const char *host) {
- return true;
- }
-};
-
-#ifndef HTTPCLIENT_NOSECURE
-class TLSTraits : public TransportTraits {
-public:
- TLSTraits(const char *CAcert, const char *clicert = nullptr, const char *clikey = nullptr) : _cacert(CAcert), _clicert(clicert), _clikey(clikey) {}
-
- std::unique_ptr create() override {
- return std::unique_ptr(new NetworkClientSecure());
- }
-
- bool verify(NetworkClient &client, const char *host) override {
- NetworkClientSecure &wcs = static_cast(client);
- if (_cacert == nullptr) {
- wcs.setInsecure();
- } else {
- wcs.setCACert(_cacert);
- wcs.setCertificate(_clicert);
- wcs.setPrivateKey(_clikey);
- }
- return true;
- }
-
-protected:
- const char *_cacert;
- const char *_clicert;
- const char *_clikey;
-};
-#endif // HTTPCLIENT_NOSECURE
-#endif // HTTPCLIENT_1_1_COMPATIBLE
-
-/**
- * constructor
- */
-HTTPClient::HTTPClient() {}
-
-/**
- * destructor
- */
-HTTPClient::~HTTPClient() {
- if (_client) {
- _client->stop();
- }
- if (_currentHeaders) {
- delete[] _currentHeaders;
- }
- if (_tcpDeprecated) {
- _tcpDeprecated.reset(nullptr);
- }
- if (_transportTraits) {
- _transportTraits.reset(nullptr);
- }
-}
-
-void HTTPClient::clear() {
- _returnCode = 0;
- _size = -1;
- _headers = "";
-}
-
-/**
- * parsing the url for all needed parameters
- * @param client Client&
- * @param url String
- * @param https bool
- * @return success bool
- */
-bool HTTPClient::begin(NetworkClient &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);
- _secure = (protocol == "https");
-
-#ifdef HTTPCLIENT_NOSECURE
- if (_secure) {
- return false;
- }
-#endif // HTTPCLIENT_NOSECURE
- 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(NetworkClient &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");
- _secure = https;
-
-#ifdef HTTPCLIENT_NOSECURE
- return _secure ? false : true;
-#else
- return true;
-#endif // HTTPCLIENT_NOSECURE
-}
-
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
-#ifndef HTTPCLIENT_NOSECURE
-bool HTTPClient::begin(String url, const char *CAcert) {
- if (_client && !_tcpDeprecated) {
- log_d("mix up of new and deprecated api");
- _canReuse = false;
- end();
- }
-
- clear();
- _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;
-}
-#endif // HTTPCLIENT_NOSECURE
-
-/**
- * parsing the url for all needed parameters
- * @param url String
- */
-bool HTTPClient::begin(String url) {
- if (_client && !_tcpDeprecated) {
- log_d("mix up of new and deprecated api");
- _canReuse = false;
- end();
- }
-
- clear();
- _port = 80;
- if (!beginInternal(url, "http")) {
-#ifdef HTTPCLIENT_NOSECURE
- return false;
-#else
- return begin(url, (const char *)NULL);
-#endif // HTTPCLIENT_NOSECURE
- }
- _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) {
- log_v("url: %s", url.c_str());
-
- // check for : (http: or https:
- int index = url.indexOf(':');
- if (index < 0) {
- log_e("failed to parse protocol");
- return false;
- }
-
- _protocol = url.substring(0, index);
- if (_protocol != expectedProtocol) {
- log_d("unexpected protocol: %s, expected %s", _protocol.c_str(), expectedProtocol);
- return false;
- }
-
- url.remove(0, (index + 3)); // remove http:// or https://
-
- index = url.indexOf('/');
- if (index == -1) {
- index = url.length();
- url += '/';
- }
- String host = url.substring(0, index);
- url.remove(0, index); // remove host part
-
- // get Authorization
- index = host.indexOf('@');
- if (index >= 0) {
- // auth info
- String auth = host.substring(0, index);
- host.remove(0, index + 1); // remove auth part including @
- _base64Authorization = base64::encode(auth);
- }
-
- // get port
- index = host.indexOf(':');
- String the_host;
- if (index >= 0) {
- the_host = host.substring(0, index); // hostname
- host.remove(0, (index + 1)); // remove hostname + :
- _port = host.toInt(); // get port
- } else {
- the_host = host;
- }
- if (_host != the_host && connected()) {
- log_d("switching host from '%s' to '%s'. disconnecting first", _host.c_str(), the_host.c_str());
- _canReuse = false;
- disconnect(true);
- }
- _host = the_host;
- _uri = url;
- log_d("protocol: %s, host: %s port: %d url: %s", _protocol.c_str(), _host.c_str(), _port, _uri.c_str());
- 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;
- _uri = uri;
- _transportTraits = TransportTraitsPtr(new TransportTraits());
- log_d("host: %s port: %d uri: %s", host.c_str(), port, uri.c_str());
- return true;
-}
-
-#ifndef HTTPCLIENT_NOSECURE
-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;
- _uri = uri;
-
- if (strlen(CAcert) == 0) {
- return false;
- }
- _secure = true;
- _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert));
- return true;
-}
-
-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;
- _uri = uri;
-
- if (strlen(CAcert) == 0) {
- return false;
- }
- _secure = true;
- _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key));
- return true;
-}
-#endif // HTTPCLIENT_NOSECURE
-#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 (_client->available() > 0) {
- log_d("still data in buffer (%d), clean up.\n", _client->available());
- _client->flush();
- }
-
- if (_reuse && _canReuse) {
- log_d("tcp keep open for reuse");
- } else {
- log_d("tcp stop");
- _client->stop();
- if (!preserveClient) {
- _client = nullptr;
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
- if (_tcpDeprecated) {
- _transportTraits.reset(nullptr);
- _tcpDeprecated.reset(nullptr);
- }
-#endif
- }
- }
- } else {
- log_d("tcp is closed\n");
- }
-}
-
-/**
- * connected
- * @return connected status
- */
-bool HTTPClient::connected() {
- if (_client) {
- return ((_client->available() > 0) || _client->connected());
- }
- return false;
-}
-
-/**
- * try to reuse the connection to the server
- * keep-alive
- * @param reuse bool
- */
-void HTTPClient::setReuse(bool reuse) {
- _reuse = reuse;
-}
-
-/**
- * set User Agent
- * @param userAgent const char *
- */
-void HTTPClient::setUserAgent(const String &userAgent) {
- _userAgent = userAgent;
-}
-
-/**
- * set Accept Encoding Header
- * @param acceptEncoding const char *
- */
-void HTTPClient::setAcceptEncoding(const String &acceptEncoding) {
- _acceptEncoding = acceptEncoding;
-}
-
-/**
- * set the Authorizatio for the http request
- * @param user const char *
- * @param password const char *
- */
-void HTTPClient::setAuthorization(const char *user, const char *password) {
- if (user && password) {
- String auth = user;
- auth += ":";
- auth += password;
- _base64Authorization = base64::encode(auth);
- }
-}
-
-/**
- * set the Authorizatio for the http request
- * @param auth const char * base64
- */
-void HTTPClient::setAuthorization(const char *auth) {
- if (auth) {
- _base64Authorization = auth;
- }
-}
-
-/**
- * set the Authorization type for the http request
- * @param authType const char *
- */
-void HTTPClient::setAuthorizationType(const char *authType) {
- if (authType) {
- _authorizationType = authType;
- }
-}
-
-/**
- * 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
- */
-void HTTPClient::setTimeout(uint16_t timeout) {
- _tcpTimeout = timeout;
- if (connected()) {
- _client->setTimeout(timeout);
- }
-}
-
-/**
- * use HTTP1.0
- * @param use
- */
-void HTTPClient::useHTTP10(bool useHTTP10) {
- _useHTTP10 = useHTTP10;
- _reuse = !useHTTP10;
-}
-
-/**
- * send a GET request
- * @return http code
- */
-int HTTPClient::GET() {
- return sendRequest("GET");
-}
-
-/**
- * sends a post request to the server
- * @param payload uint8_t *
- * @param size size_t
- * @return http code
- */
-int HTTPClient::POST(uint8_t *payload, size_t size) {
- return sendRequest("POST", payload, size);
-}
-
-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 *
- * @param size size_t
- * @return http code
- */
-int HTTPClient::PUT(uint8_t *payload, size_t size) {
- return sendRequest("PUT", payload, size);
-}
-
-int HTTPClient::PUT(String payload) {
- return PUT((uint8_t *)payload.c_str(), payload.length());
-}
-
-/**
- * sendRequest
- * @param type const char * "GET", "POST", ....
- * @param payload String data for the message body
- * @return
- */
-int HTTPClient::sendRequest(const char *type, String payload) {
- return sendRequest(type, (uint8_t *)payload.c_str(), payload.length());
-}
-
-/**
- * sendRequest
- * @param type const char * "GET", "POST", ....
- * @param payload uint8_t * data for the message body if null not send
- * @param size size_t size for the message body if 0 not send
- * @return -1 if no info or > 0 when Content-Length is set by server
- */
-int HTTPClient::sendRequest(const char *type, uint8_t *payload, size_t size) {
- int code;
- bool redirect = false;
- uint16_t redirectCount = 0;
- do {
- // wipe out any existing headers from previous request
- for (size_t i = 0; i < _headerKeysCount; i++) {
- if (_currentHeaders[i].value.length() > 0) {
- _currentHeaders[i].value.clear();
- }
- }
-
- log_d("request type: '%s' redirCount: %d\n", type, redirectCount);
-
- // connect to server
- if (!connect()) {
- return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
- }
-
- if (payload && size > 0) {
- addHeader(F("Content-Length"), String(size));
- }
-
- // add cookies to header, if present
- String cookie_string;
- if (generateCookieString(&cookie_string)) {
- addHeader("Cookie", cookie_string);
- }
-
- // send Header
- if (!sendHeader(type)) {
- return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
- }
-
- // send Payload if needed
- if (payload && size > 0) {
- size_t sent_bytes = 0;
- while (sent_bytes < size) {
- size_t sent = _client->write(&payload[sent_bytes], size - sent_bytes);
- if (sent == 0) {
- log_w("Failed to send chunk! Lets wait a bit");
- delay(100);
- sent = _client->write(&payload[sent_bytes], size - sent_bytes);
- if (sent == 0) {
- log_e("Failed to send chunk!");
- break;
- }
- }
- sent_bytes += sent;
- }
- if (sent_bytes != size) {
- return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
- }
- }
-
- code = handleHeaderResponse();
- log_d("sendRequest code=%d\n", code);
-
- // Handle redirections as stated in RFC document:
- // https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
- //
- // Implementing HTTP_CODE_FOUND as redirection with GET method,
- // to follow most of existing user agent implementations.
- //
- redirect = false;
- if (_followRedirects != HTTPC_DISABLE_FOLLOW_REDIRECTS && redirectCount < _redirectLimit && _location.length() > 0) {
- switch (code) {
- // redirecting using the same method
- case HTTP_CODE_MOVED_PERMANENTLY:
- case HTTP_CODE_TEMPORARY_REDIRECT:
- {
- if (
- // allow to force redirections on other methods
- // (the RFC require user to accept the redirection)
- _followRedirects == HTTPC_FORCE_FOLLOW_REDIRECTS ||
- // allow GET and HEAD methods without force
- !strcmp(type, "GET") || !strcmp(type, "HEAD")) {
- redirectCount += 1;
- log_d("following redirect (the same method): '%s' redirCount: %d\n", _location.c_str(), redirectCount);
- if (!setURL(_location)) {
- log_d("failed setting URL for redirection\n");
- // no redirection
- break;
- }
- // redirect using the same request method and payload, different URL
- redirect = true;
- }
- break;
- }
- // redirecting with method dropped to GET or HEAD
- // note: it does not need `HTTPC_FORCE_FOLLOW_REDIRECTS` for any method
- case HTTP_CODE_FOUND:
- case HTTP_CODE_SEE_OTHER:
- {
- redirectCount += 1;
- log_d("following redirect (dropped to GET/HEAD): '%s' redirCount: %d\n", _location.c_str(), redirectCount);
- if (!setURL(_location)) {
- log_d("failed setting URL for redirection\n");
- // no redirection
- break;
- }
- // redirect after changing method to GET/HEAD and dropping payload
- type = "GET";
- payload = nullptr;
- size = 0;
- redirect = true;
- break;
- }
-
- default: break;
- }
- }
-
- } while (redirect);
- // handle Server Response (Header)
- return returnError(code);
-}
-
-/**
- * sendRequest
- * @param type const char * "GET", "POST", ....
- * @param stream Stream * data stream for the message body
- * @param size size_t size for the message body if 0 not Content-Length is send
- * @return -1 if no info or > 0 when Content-Length is set by server
- */
-int HTTPClient::sendRequest(const char *type, Stream *stream, size_t size) {
-
- if (!stream) {
- return returnError(HTTPC_ERROR_NO_STREAM);
- }
-
- // connect to server
- if (!connect()) {
- return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
- }
-
- if (size > 0) {
- addHeader("Content-Length", String(size));
- }
-
- // add cookies to header, if present
- String cookie_string;
- if (generateCookieString(&cookie_string)) {
- addHeader("Cookie", cookie_string);
- }
-
- // send Header
- if (!sendHeader(type)) {
- return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
- }
-
- int buff_size = HTTP_TCP_TX_BUFFER_SIZE;
-
- int len = size;
- int bytesWritten = 0;
-
- if (len == 0) {
- len = -1;
- }
-
- // if possible create smaller buffer then HTTP_TCP_TX_BUFFER_SIZE
- if ((len > 0) && (len < buff_size)) {
- buff_size = len;
- }
-
- // create buffer for read
- uint8_t *buff = (uint8_t *)malloc(buff_size);
-
- if (buff) {
- // read all data from stream and send it to server
- while (connected() && (stream->available() > -1) && (len > 0 || len == -1)) {
-
- // get available data size
- int sizeAvailable = stream->available();
-
- if (sizeAvailable) {
-
- int readBytes = sizeAvailable;
-
- // read only the asked bytes
- if (len > 0 && readBytes > len) {
- readBytes = len;
- }
-
- // not read more the buffer can handle
- if (readBytes > buff_size) {
- readBytes = buff_size;
- }
-
- // read data
- int bytesRead = stream->readBytes(buff, readBytes);
-
- // write it to Stream
- int bytesWrite = _client->write((const uint8_t *)buff, bytesRead);
- bytesWritten += bytesWrite;
-
- // are all Bytes a written to stream ?
- if (bytesWrite != bytesRead) {
- log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite);
-
- // check for write error
- if (_client->getWriteError()) {
- log_d("stream write error %d", _client->getWriteError());
-
- //reset write error for retry
- _client->clearWriteError();
- }
-
- // some time for the stream
- delay(1);
-
- int leftBytes = (readBytes - bytesWrite);
-
- // retry to send the missed bytes
- bytesWrite = _client->write((const uint8_t *)(buff + bytesWrite), leftBytes);
- bytesWritten += bytesWrite;
-
- if (bytesWrite != leftBytes) {
- // failed again
- log_d("short write, asked for %d but got %d failed.", leftBytes, bytesWrite);
- free(buff);
- return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
- }
- }
-
- // check for write error
- if (_client->getWriteError()) {
- log_d("stream write error %d", _client->getWriteError());
- free(buff);
- return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
- }
-
- // count bytes to read left
- if (len > 0) {
- len -= readBytes;
- }
-
- delay(0);
- } else {
- delay(1);
- }
- }
-
- free(buff);
-
- if (size && (int)size != bytesWritten) {
- log_d("Stream payload bytesWritten %d and size %d mismatch!.", bytesWritten, size);
- log_d("ERROR SEND PAYLOAD FAILED!");
- return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
- } else {
- log_d("Stream payload written: %d", bytesWritten);
- }
-
- } else {
- log_d("too less ram! need %d", buff_size);
- return returnError(HTTPC_ERROR_TOO_LESS_RAM);
- }
-
- // handle Server Response (Header)
- return returnError(handleHeaderResponse());
-}
-
-/**
- * size of message body / payload
- * @return -1 if no info or > 0 when Content-Length is set by server
- */
-int HTTPClient::getSize(void) {
- return _size;
-}
-
-/**
- * returns the stream of the tcp connection
- * @return NetworkClient
- */
-NetworkClient &HTTPClient::getStream(void) {
- if (connected()) {
- return *_client;
- }
-
- log_w("getStream: not connected");
- static NetworkClient empty;
- return empty;
-}
-
-/**
- * returns a pointer to the stream of the tcp connection
- * @return NetworkClient*
- */
-NetworkClient *HTTPClient::getStreamPtr(void) {
- if (connected()) {
- return _client;
- }
-
- log_w("getStreamPtr: not connected");
- return nullptr;
-}
-
-/**
- * write all message body / payload to Stream
- * @param stream Stream *
- * @return bytes written ( negative values are error codes )
- */
-int HTTPClient::writeToStream(Stream *stream) {
-
- if (!stream) {
- return returnError(HTTPC_ERROR_NO_STREAM);
- }
-
- if (!connected()) {
- return returnError(HTTPC_ERROR_NOT_CONNECTED);
- }
-
- // get length of document (is -1 when Server sends no Content-Length header)
- int len = _size;
- int ret = 0;
-
- if (_transferEncoding == HTTPC_TE_IDENTITY) {
- ret = writeToStreamDataBlock(stream, len);
-
- // have we an error?
- if (ret < 0) {
- return returnError(ret);
- }
- } else if (_transferEncoding == HTTPC_TE_CHUNKED) {
- int size = 0;
- while (1) {
- if (!connected()) {
- return returnError(HTTPC_ERROR_CONNECTION_LOST);
- }
- String chunkHeader = _client->readStringUntil('\n');
-
- if (chunkHeader.length() <= 0) {
- return returnError(HTTPC_ERROR_READ_TIMEOUT);
- }
-
- chunkHeader.trim(); // remove \r
-
- // read size of chunk
- len = (uint32_t)strtol((const char *)chunkHeader.c_str(), NULL, 16);
- size += len;
- log_v(" read chunk len: %d", len);
-
- // data left?
- if (len > 0) {
- int r = writeToStreamDataBlock(stream, len);
- if (r < 0) {
- // error in writeToStreamDataBlock
- return returnError(r);
- }
- ret += r;
- } else {
-
- // if no length Header use global chunk size
- if (_size <= 0) {
- _size = size;
- }
-
- // check if we have write all data out
- if (ret != _size) {
- return returnError(HTTPC_ERROR_STREAM_WRITE);
- }
- break;
- }
-
- // read trailing \r\n at the end of the chunk
- char 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);
- }
-
- delay(0);
- }
- } else {
- return returnError(HTTPC_ERROR_ENCODING);
- }
-
- // end();
- disconnect(true);
- return ret;
-}
-
-/**
- * return all payload as String (may need lot of ram or trigger out of memory!)
- * @return String
- */
-String HTTPClient::getString(void) {
- // _size can be -1 when Server sends no Content-Length header
- if (_size > 0 || _size == -1) {
- StreamString sstring;
- // try to reserve needed memory (noop if _size == -1)
- if (sstring.reserve((_size + 1))) {
- writeToStream(&sstring);
- return sstring;
- } else {
- log_d("not enough memory to reserve a string! need: %d", (_size + 1));
- }
- }
-
- return "";
-}
-
-/**
- * converts error code to String
- * @param error int
- * @return String
- */
-String HTTPClient::errorToString(int error) {
- switch (error) {
- case HTTPC_ERROR_CONNECTION_REFUSED: return F("connection refused");
- case HTTPC_ERROR_SEND_HEADER_FAILED: return F("send header failed");
- case HTTPC_ERROR_SEND_PAYLOAD_FAILED: return F("send payload failed");
- case HTTPC_ERROR_NOT_CONNECTED: return F("not connected");
- case HTTPC_ERROR_CONNECTION_LOST: return F("connection lost");
- case HTTPC_ERROR_NO_STREAM: return F("no stream");
- case HTTPC_ERROR_NO_HTTP_SERVER: return F("no HTTP server");
- case HTTPC_ERROR_TOO_LESS_RAM: return F("too less ram");
- case HTTPC_ERROR_ENCODING: return F("Transfer-Encoding not supported");
- case HTTPC_ERROR_STREAM_WRITE: return F("Stream write error");
- case HTTPC_ERROR_READ_TIMEOUT: return F("read Timeout");
- default: return String();
- }
-}
-
-/**
- * adds Header to the request
- * @param name
- * @param value
- * @param first
- */
-void HTTPClient::addHeader(const String &name, const String &value, bool first, bool replace) {
- // not allow set of Header handled by code
- if (!name.equalsIgnoreCase(F("Connection")) && !name.equalsIgnoreCase(F("User-Agent")) && !name.equalsIgnoreCase(F("Accept-Encoding"))
- && !name.equalsIgnoreCase(F("Host")) && !(name.equalsIgnoreCase(F("Authorization")) && _base64Authorization.length())) {
-
- String headerLine = name;
- headerLine += ": ";
-
- if (replace) {
- int headerStart = _headers.indexOf(headerLine);
- if (headerStart != -1 && (headerStart == 0 || _headers[headerStart - 1] == '\n')) {
- int headerEnd = _headers.indexOf('\n', headerStart);
- _headers = _headers.substring(0, headerStart) + _headers.substring(headerEnd + 1);
- }
- }
-
- headerLine += value;
- headerLine += "\r\n";
- if (first) {
- _headers = headerLine + _headers;
- } else {
- _headers += headerLine;
- }
- }
-}
-
-void HTTPClient::collectHeaders(const char *headerKeys[], const size_t headerKeysCount) {
- _headerKeysCount = headerKeysCount;
- if (_currentHeaders) {
- delete[] _currentHeaders;
- }
- _currentHeaders = new RequestArgument[_headerKeysCount];
- for (size_t i = 0; i < _headerKeysCount; i++) {
- _currentHeaders[i].key = headerKeys[i];
- }
-}
-
-String HTTPClient::header(const char *name) {
- for (size_t i = 0; i < _headerKeysCount; ++i) {
- if (_currentHeaders[i].key.equalsIgnoreCase(name)) {
- return _currentHeaders[i].value;
- }
- }
- return String();
-}
-
-String HTTPClient::header(size_t i) {
- if (i < _headerKeysCount) {
- return _currentHeaders[i].value;
- }
- return String();
-}
-
-String HTTPClient::headerName(size_t i) {
- if (i < _headerKeysCount) {
- return _currentHeaders[i].key;
- }
- return String();
-}
-
-int HTTPClient::headers() {
- return _headerKeysCount;
-}
-
-bool HTTPClient::hasHeader(const char *name) {
- for (size_t i = 0; i < _headerKeysCount; ++i) {
- if ((_currentHeaders[i].key.equalsIgnoreCase(name)) && (_currentHeaders[i].value.length() > 0)) {
- return true;
- }
- }
- return false;
-}
-
-/**
- * init TCP connection and handle ssl verify if needed
- * @return true if connection is ok
- */
-bool HTTPClient::connect(void) {
- if (connected()) {
- if (_reuse) {
- log_d("already connected, reusing connection");
- } else {
- log_d("already connected, try reuse!");
- }
- while (_client->available() > 0) {
- _client->read();
- }
- return true;
- }
-
-#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;
- }
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
- if (_tcpDeprecated && !_transportTraits->verify(*_client, _host.c_str())) {
- log_d("transport level verify failed");
- _client->stop();
- return false;
- }
-#endif
- if (!_client->connect(_host.c_str(), _port, _connectTimeout)) {
- log_d("failed connect to %s:%u", _host.c_str(), _port);
- return false;
- }
-
- // set Timeout for NetworkClient and for Stream::readBytesUntil() and Stream::readStringUntil()
- _client->setTimeout(_tcpTimeout);
-
- log_d(" connected to %s:%u", _host.c_str(), _port);
-
- /*
-#ifdef ESP8266
- _client->setNoDelay(true);
-#endif
- */
- return connected();
-}
-
-/**
- * sends HTTP request header
- * @param type (GET, POST, ...)
- * @return status
- */
-bool HTTPClient::sendHeader(const char *type) {
- if (!connected()) {
- return false;
- }
-
- String header = String(type) + " " + _uri + F(" HTTP/1.");
-
- if (_useHTTP10) {
- header += "0";
- } else {
- header += "1";
- }
-
- header += String(F("\r\nHost: ")) + _host;
- if (_port != 80 && _port != 443) {
- header += ':';
- header += String(_port);
- }
- header += String(F("\r\nUser-Agent: ")) + _userAgent + F("\r\nConnection: ");
-
- if (_reuse) {
- header += F("keep-alive");
- } else {
- header += F("close");
- }
- header += "\r\n";
-
- if (!_useHTTP10) {
- header += String(F("Accept-Encoding: ")) + _acceptEncoding + F("\r\n");
- }
-
- if (_base64Authorization.length()) {
- _base64Authorization.replace("\n", "");
- header += F("Authorization: ");
- header += _authorizationType;
- header += " ";
- header += _base64Authorization;
- header += "\r\n";
- }
-
- header += _headers + "\r\n";
-
- return (_client->write((const uint8_t *)header.c_str(), header.length()) == header.length());
-}
-
-/**
- * reads the response from the server
- * @return int http code
- */
-int HTTPClient::handleHeaderResponse() {
-
- if (!connected()) {
- return HTTPC_ERROR_NOT_CONNECTED;
- }
-
- _returnCode = 0;
- _size = -1;
- _canReuse = _reuse;
-
- String transferEncoding;
-
- _transferEncoding = HTTPC_TE_IDENTITY;
- unsigned long lastDataTime = millis();
- bool firstLine = true;
- String date;
-
- while (connected()) {
- size_t len = _client->available();
- if (len > 0) {
- String headerLine = _client->readStringUntil('\n');
- headerLine.trim(); // remove \r
-
- lastDataTime = millis();
-
- log_v("RX: '%s'", headerLine.c_str());
-
- if (firstLine) {
- firstLine = false;
- if (_canReuse && headerLine.startsWith("HTTP/1.")) {
- _canReuse = (headerLine[sizeof "HTTP/1." - 1] != '0');
- }
- int codePos = headerLine.indexOf(' ') + 1;
- _returnCode = headerLine.substring(codePos, headerLine.indexOf(' ', codePos)).toInt();
- } else if (headerLine.indexOf(':')) {
- String headerName = headerLine.substring(0, headerLine.indexOf(':'));
- String headerValue = headerLine.substring(headerLine.indexOf(':') + 1);
- headerValue.trim();
-
- if (headerName.equalsIgnoreCase("Date")) {
- date = headerValue;
- }
-
- if (headerName.equalsIgnoreCase("Content-Length")) {
- _size = headerValue.toInt();
- }
-
- if (_canReuse && headerName.equalsIgnoreCase("Connection")) {
- if (headerValue.indexOf("close") >= 0 && headerValue.indexOf("keep-alive") < 0) {
- _canReuse = false;
- }
- }
-
- if (headerName.equalsIgnoreCase("Transfer-Encoding")) {
- transferEncoding = headerValue;
- }
-
- if (headerName.equalsIgnoreCase("Location")) {
- _location = headerValue;
- }
-
- if (headerName.equalsIgnoreCase("Set-Cookie")) {
- setCookie(date, headerValue);
- }
-
- for (size_t i = 0; i < _headerKeysCount; i++) {
- if (_currentHeaders[i].key.equalsIgnoreCase(headerName)) {
- // Uncomment the following lines if you need to add support for multiple headers with the same key:
- // if (!_currentHeaders[i].value.isEmpty()) {
- // // Existing value, append this one with a comma
- // _currentHeaders[i].value += ',';
- // _currentHeaders[i].value += headerValue;
- // } else {
- _currentHeaders[i].value = headerValue;
- // }
- break; // We found a match, stop looking
- }
- }
- }
-
- if (headerLine == "") {
- log_d("code: %d", _returnCode);
-
- if (_size > 0) {
- log_d("size: %d", _size);
- }
-
- if (transferEncoding.length() > 0) {
- log_d("Transfer-Encoding: %s", transferEncoding.c_str());
- if (transferEncoding.equalsIgnoreCase("chunked")) {
- _transferEncoding = HTTPC_TE_CHUNKED;
- } else if (transferEncoding.equalsIgnoreCase("identity")) {
- _transferEncoding = HTTPC_TE_IDENTITY;
- } else {
- return HTTPC_ERROR_ENCODING;
- }
- } else {
- _transferEncoding = HTTPC_TE_IDENTITY;
- }
-
- if (_returnCode) {
- return _returnCode;
- } else {
- log_d("Remote host is not an HTTP Server!");
- return HTTPC_ERROR_NO_HTTP_SERVER;
- }
- }
-
- } else {
- if ((millis() - lastDataTime) > _tcpTimeout) {
- return HTTPC_ERROR_READ_TIMEOUT;
- }
- delay(10);
- }
- }
-
- return HTTPC_ERROR_CONNECTION_LOST;
-}
-
-/**
- * write one Data Block to Stream
- * @param stream Stream *
- * @param size int
- * @return < 0 = error >= 0 = size written
- */
-int HTTPClient::writeToStreamDataBlock(Stream *stream, int size) {
- int buff_size = HTTP_TCP_RX_BUFFER_SIZE;
- int len = size;
- int bytesWritten = 0;
-
- // if possible create smaller buffer then HTTP_TCP_RX_BUFFER_SIZE
- if ((len > 0) && (len < buff_size)) {
- buff_size = len;
- }
-
- // create buffer for read
- uint8_t *buff = (uint8_t *)malloc(buff_size);
-
- if (buff) {
- // read all data from server
- while (connected() && (len > 0 || len == -1)) {
-
- // get available data size
- size_t sizeAvailable = buff_size;
- if (len < 0) {
- sizeAvailable = _client->available();
- }
-
- if (sizeAvailable) {
-
- int readBytes = sizeAvailable;
-
- // read only the asked bytes
- if (len > 0 && readBytes > len) {
- readBytes = len;
- }
-
- // not read more the buffer can handle
- if (readBytes > buff_size) {
- readBytes = buff_size;
- }
-
- // stop if no more reading
- if (readBytes == 0) {
- break;
- }
-
- // read data
- int bytesRead = _client->readBytes(buff, readBytes);
-
- // write it to Stream
- int bytesWrite = stream->write(buff, bytesRead);
- bytesWritten += bytesWrite;
-
- // are all Bytes a written to stream ?
- if (bytesWrite != bytesRead) {
- log_d("short write asked for %d but got %d retry...", bytesRead, bytesWrite);
-
- // check for write error
- if (stream->getWriteError()) {
- log_d("stream write error %d", stream->getWriteError());
-
- //reset write error for retry
- stream->clearWriteError();
- }
-
- // some time for the stream
- delay(1);
-
- int leftBytes = (bytesRead - bytesWrite);
-
- // retry to send the missed bytes
- bytesWrite = stream->write((buff + bytesWrite), leftBytes);
- bytesWritten += bytesWrite;
-
- if (bytesWrite != leftBytes) {
- // failed again
- log_w("short write asked for %d but got %d failed.", leftBytes, bytesWrite);
- free(buff);
- return HTTPC_ERROR_STREAM_WRITE;
- }
- }
-
- // check for write error
- if (stream->getWriteError()) {
- log_w("stream write error %d", stream->getWriteError());
- free(buff);
- return HTTPC_ERROR_STREAM_WRITE;
- }
-
- // count bytes to read left
- if (len > 0) {
- len -= bytesRead;
- }
-
- delay(0);
- } else {
- delay(1);
- }
- }
-
- free(buff);
-
- log_v("connection closed or file end (written: %d).", bytesWritten);
-
- if ((size > 0) && (size != bytesWritten)) {
- log_d("bytesWritten %d and size %d mismatch!.", bytesWritten, size);
- return HTTPC_ERROR_STREAM_WRITE;
- }
-
- } else {
- log_w("too less ram! need %d", buff_size);
- return HTTPC_ERROR_TOO_LESS_RAM;
- }
-
- return bytesWritten;
-}
-
-/**
- * called to handle error return, may disconnect the connection if still exists
- * @param error
- * @return error
- */
-int HTTPClient::returnError(int error) {
- if (error < 0) {
- log_w("error(%d): %s", error, errorToString(error).c_str());
- if (connected()) {
- log_d("tcp stop");
- _client->stop();
- }
- }
- return error;
-}
-
-void HTTPClient::setFollowRedirects(followRedirects_t follow) {
- _followRedirects = follow;
-}
-
-void HTTPClient::setRedirectLimit(uint16_t limit) {
- _redirectLimit = limit;
-}
-
-/**
- * set the URL to a new value. Handy for following redirects.
- * @param url
- */
-bool HTTPClient::setURL(const String &url) {
- // if the new location is only a path then only update the URI
- if (url && url[0] == '/') {
- _uri = url;
- clear();
- return true;
- }
-
- if (!url.startsWith(_protocol + ':')) {
- log_d("new URL not the same protocol, expected '%s', URL: '%s'\n", _protocol.c_str(), url.c_str());
- return false;
- }
-
- // check if the port is specified
- int indexPort = url.indexOf(':', 6); // find the first ':' excluding the one from the protocol
- int indexURI = url.indexOf('/', 7); // find where the URI starts to make sure the ':' is not part of it
- if (indexPort == -1 || indexPort > indexURI) {
- // the port is not specified
- _port = (_protocol == "https" ? 443 : 80);
- }
-
- // disconnect but preserve _client.
- // Also have to keep the connection otherwise it will free some of the memory used by _client
- // and will blow up later when trying to do _client->available() or similar
- _canReuse = true;
- disconnect(true);
- return beginInternal(url, _protocol.c_str());
-}
-
-const String &HTTPClient::getLocation(void) {
- return _location;
-}
-
-void HTTPClient::setCookieJar(CookieJar *cookieJar) {
- _cookieJar = cookieJar;
-}
-
-void HTTPClient::resetCookieJar() {
- _cookieJar = nullptr;
-}
-
-void HTTPClient::clearAllCookies() {
- if (_cookieJar) {
- _cookieJar->clear();
- }
-}
-
-void HTTPClient::setCookie(String date, String headerValue) {
- if (!_cookieJar) {
- return;
- }
-#define HTTP_TIME_PATTERN "%a, %d %b %Y %H:%M:%S"
-
- Cookie cookie;
- String value;
- int pos1, pos2;
-
- struct tm tm;
- strptime(date.c_str(), HTTP_TIME_PATTERN, &tm);
- cookie.date = mktime(&tm);
-
- pos1 = headerValue.indexOf('=');
- pos2 = headerValue.indexOf(';');
-
- if (pos1 >= 0 && pos2 > pos1) {
- cookie.name = headerValue.substring(0, pos1);
- cookie.value = headerValue.substring(pos1 + 1, pos2);
- } else {
- return; // invalid cookie header
- }
-
- // only Cookie Attributes are case insensitive from this point on
- headerValue.toLowerCase();
-
- // expires
- if (headerValue.indexOf("expires=") >= 0) {
- pos1 = headerValue.indexOf("expires=") + strlen("expires=");
- pos2 = headerValue.indexOf(';', pos1);
-
- if (pos2 > pos1) {
- value = headerValue.substring(pos1, pos2);
- } else {
- value = headerValue.substring(pos1);
- }
-
- strptime(value.c_str(), HTTP_TIME_PATTERN, &tm);
- cookie.expires.date = mktime(&tm);
- cookie.expires.valid = true;
- }
-
- // max-age
- if (headerValue.indexOf("max-age=") >= 0) {
- pos1 = headerValue.indexOf("max-age=") + strlen("max-age=");
- pos2 = headerValue.indexOf(';', pos1);
-
- if (pos2 > pos1) {
- value = headerValue.substring(pos1, pos2);
- } else {
- value = headerValue.substring(pos1);
- }
-
- cookie.max_age.duration = value.toInt();
- cookie.max_age.valid = true;
- }
-
- // domain
- if (headerValue.indexOf("domain=") >= 0) {
- pos1 = headerValue.indexOf("domain=") + strlen("domain=");
- pos2 = headerValue.indexOf(';', pos1);
-
- if (pos2 > pos1) {
- value = headerValue.substring(pos1, pos2);
- } else {
- value = headerValue.substring(pos1);
- }
-
- if (value.startsWith(".")) {
- value.remove(0, 1);
- }
-
- if (_host.indexOf(value) >= 0) {
- cookie.domain = value;
- } else {
- return; // server tries to set a cookie on a different domain; ignore it
- }
- } else {
- pos1 = _host.lastIndexOf('.', _host.lastIndexOf('.') - 1);
- if (pos1 >= 0) {
- cookie.domain = _host.substring(pos1 + 1);
- } else {
- cookie.domain = _host;
- }
- }
-
- // path
- if (headerValue.indexOf("path=") >= 0) {
- pos1 = headerValue.indexOf("path=") + strlen("path=");
- pos2 = headerValue.indexOf(';', pos1);
-
- if (pos2 > pos1) {
- cookie.path = headerValue.substring(pos1, pos2);
- } else {
- cookie.path = headerValue.substring(pos1);
- }
- }
-
- // HttpOnly
- cookie.http_only = (headerValue.indexOf("httponly") >= 0);
-
- // secure
- cookie.secure = (headerValue.indexOf("secure") >= 0);
-
- // overwrite or delete cookie in/from cookie jar
- time_t now_local = time(NULL);
- time_t now_gmt = mktime(gmtime(&now_local));
-
- bool found = false;
-
- for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) {
- if (c->domain == cookie.domain && c->name == cookie.name) {
- // when evaluating, max-age takes precedence over expires if both are defined
- if ((cookie.max_age.valid && ((cookie.date + cookie.max_age.duration) < now_gmt)) || cookie.max_age.duration <= 0
- || (!cookie.max_age.valid && cookie.expires.valid && cookie.expires.date < now_gmt)) {
- _cookieJar->erase(c);
- c--;
- } else {
- *c = cookie;
- }
- found = true;
- }
- }
-
- // add cookie to jar
- if (!found && !(cookie.max_age.valid && cookie.max_age.duration <= 0)) {
- _cookieJar->push_back(cookie);
- }
-}
-
-bool HTTPClient::generateCookieString(String *cookieString) {
- time_t now_local = time(NULL);
- time_t now_gmt = mktime(gmtime(&now_local));
-
- *cookieString = "";
- bool found = false;
-
- if (!_cookieJar) {
- return false;
- }
- for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) {
- if ((c->max_age.valid && ((c->date + c->max_age.duration) < now_gmt)) || (!c->max_age.valid && c->expires.valid && c->expires.date < now_gmt)) {
- _cookieJar->erase(c);
- c--;
- } else if (_host.indexOf(c->domain) >= 0 && (!c->secure || _secure)) {
- if (*cookieString == "") {
- *cookieString = c->name + "=" + c->value;
- } else {
- *cookieString += " ;" + c->name + "=" + c->value;
- }
- found = true;
- }
- }
-
- return found;
-}
diff --git a/lib/HTTPClient/src/HTTPClient.h b/lib/HTTPClient/src/HTTPClient.h
deleted file mode 100644
index 80f6da2..0000000
--- a/lib/HTTPClient/src/HTTPClient.h
+++ /dev/null
@@ -1,322 +0,0 @@
-/**
- * HTTPClient.h
- *
- * Created on: 02.11.2015
- *
- * Copyright (c) 2015 Markus Sattler. All rights reserved.
- * This file is part of the HTTPClient for Arduino.
- * Port to ESP32 by Evandro Luis Copercini (2017),
- * changed fingerprints to CA verification.
- *
- * 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 HTTPClient_H_
-#define HTTPClient_H_
-
-#ifndef HTTPCLIENT_1_1_COMPATIBLE
-#define HTTPCLIENT_1_1_COMPATIBLE
-#endif
-
-#include
-#include
-#include
-#ifndef HTTPCLIENT_NOSECURE
-#include
-#endif // HTTPCLIENT_NOSECURE
-
-/// Cookie jar support
-#include
-
-#define HTTPCLIENT_DEFAULT_TCP_TIMEOUT (5000)
-
-/// HTTP client errors
-#define HTTPC_ERROR_CONNECTION_REFUSED (-1)
-#define HTTPC_ERROR_SEND_HEADER_FAILED (-2)
-#define HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
-#define HTTPC_ERROR_NOT_CONNECTED (-4)
-#define HTTPC_ERROR_CONNECTION_LOST (-5)
-#define HTTPC_ERROR_NO_STREAM (-6)
-#define HTTPC_ERROR_NO_HTTP_SERVER (-7)
-#define HTTPC_ERROR_TOO_LESS_RAM (-8)
-#define HTTPC_ERROR_ENCODING (-9)
-#define HTTPC_ERROR_STREAM_WRITE (-10)
-#define HTTPC_ERROR_READ_TIMEOUT (-11)
-
-/// size for the stream handling
-#define HTTP_TCP_RX_BUFFER_SIZE (4096)
-#define HTTP_TCP_TX_BUFFER_SIZE (1460)
-
-/// HTTP codes see RFC7231
-typedef enum {
- HTTP_CODE_CONTINUE = 100,
- HTTP_CODE_SWITCHING_PROTOCOLS = 101,
- HTTP_CODE_PROCESSING = 102,
- HTTP_CODE_OK = 200,
- HTTP_CODE_CREATED = 201,
- HTTP_CODE_ACCEPTED = 202,
- HTTP_CODE_NON_AUTHORITATIVE_INFORMATION = 203,
- HTTP_CODE_NO_CONTENT = 204,
- HTTP_CODE_RESET_CONTENT = 205,
- HTTP_CODE_PARTIAL_CONTENT = 206,
- HTTP_CODE_MULTI_STATUS = 207,
- HTTP_CODE_ALREADY_REPORTED = 208,
- HTTP_CODE_IM_USED = 226,
- HTTP_CODE_MULTIPLE_CHOICES = 300,
- HTTP_CODE_MOVED_PERMANENTLY = 301,
- HTTP_CODE_FOUND = 302,
- HTTP_CODE_SEE_OTHER = 303,
- HTTP_CODE_NOT_MODIFIED = 304,
- HTTP_CODE_USE_PROXY = 305,
- HTTP_CODE_TEMPORARY_REDIRECT = 307,
- HTTP_CODE_PERMANENT_REDIRECT = 308,
- HTTP_CODE_BAD_REQUEST = 400,
- HTTP_CODE_UNAUTHORIZED = 401,
- HTTP_CODE_PAYMENT_REQUIRED = 402,
- HTTP_CODE_FORBIDDEN = 403,
- HTTP_CODE_NOT_FOUND = 404,
- HTTP_CODE_METHOD_NOT_ALLOWED = 405,
- HTTP_CODE_NOT_ACCEPTABLE = 406,
- HTTP_CODE_PROXY_AUTHENTICATION_REQUIRED = 407,
- HTTP_CODE_REQUEST_TIMEOUT = 408,
- HTTP_CODE_CONFLICT = 409,
- HTTP_CODE_GONE = 410,
- HTTP_CODE_LENGTH_REQUIRED = 411,
- HTTP_CODE_PRECONDITION_FAILED = 412,
- HTTP_CODE_PAYLOAD_TOO_LARGE = 413,
- HTTP_CODE_URI_TOO_LONG = 414,
- HTTP_CODE_UNSUPPORTED_MEDIA_TYPE = 415,
- HTTP_CODE_RANGE_NOT_SATISFIABLE = 416,
- HTTP_CODE_EXPECTATION_FAILED = 417,
- HTTP_CODE_MISDIRECTED_REQUEST = 421,
- HTTP_CODE_UNPROCESSABLE_ENTITY = 422,
- HTTP_CODE_LOCKED = 423,
- HTTP_CODE_FAILED_DEPENDENCY = 424,
- HTTP_CODE_UPGRADE_REQUIRED = 426,
- HTTP_CODE_PRECONDITION_REQUIRED = 428,
- HTTP_CODE_TOO_MANY_REQUESTS = 429,
- HTTP_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
- HTTP_CODE_INTERNAL_SERVER_ERROR = 500,
- HTTP_CODE_NOT_IMPLEMENTED = 501,
- HTTP_CODE_BAD_GATEWAY = 502,
- HTTP_CODE_SERVICE_UNAVAILABLE = 503,
- HTTP_CODE_GATEWAY_TIMEOUT = 504,
- HTTP_CODE_HTTP_VERSION_NOT_SUPPORTED = 505,
- HTTP_CODE_VARIANT_ALSO_NEGOTIATES = 506,
- HTTP_CODE_INSUFFICIENT_STORAGE = 507,
- HTTP_CODE_LOOP_DETECTED = 508,
- HTTP_CODE_NOT_EXTENDED = 510,
- HTTP_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511
-} t_http_codes;
-
-typedef enum {
- HTTPC_TE_IDENTITY,
- HTTPC_TE_CHUNKED
-} transferEncoding_t;
-
-/**
- * redirection follow mode.
- * + `HTTPC_DISABLE_FOLLOW_REDIRECTS` - no redirection will be followed.
- * + `HTTPC_STRICT_FOLLOW_REDIRECTS` - strict RFC2616, only requests using
- * GET or HEAD methods will be redirected (using the same method),
- * since the RFC requires end-user confirmation in other cases.
- * + `HTTPC_FORCE_FOLLOW_REDIRECTS` - all redirections will be followed,
- * regardless of a used method. New request will use the same method,
- * and they will include the same body data and the same headers.
- * In the sense of the RFC, it's just like every redirection is confirmed.
- */
-typedef enum {
- HTTPC_DISABLE_FOLLOW_REDIRECTS,
- HTTPC_STRICT_FOLLOW_REDIRECTS,
- HTTPC_FORCE_FOLLOW_REDIRECTS
-} followRedirects_t;
-
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
-class TransportTraits;
-typedef std::unique_ptr TransportTraitsPtr;
-#endif
-
-// cookie jar support
-typedef struct {
- String host; // host which tries to set the cookie
- time_t date; // timestamp of the response that set the cookie
- String name;
- String value;
- String domain;
- String path = "";
- struct {
- time_t date = 0;
- bool valid = false;
- } expires;
- struct {
- time_t duration = 0;
- bool valid = false;
- } max_age;
- bool http_only = false;
- bool secure = false;
-} Cookie;
-typedef std::vector CookieJar;
-
-class HTTPClient {
-public:
- 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(NetworkClient &client, String url);
- bool begin(NetworkClient &client, String host, uint16_t port, String uri = "/", bool https = false);
-
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
- bool begin(String url);
- bool begin(String host, uint16_t port, String uri = "/");
-#ifndef HTTPCLIENT_NOSECURE
- bool begin(String url, const char *CAcert);
- 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);
-#else
- bool begin(String url, const char *CAcert) {
- return false;
- };
- bool begin(String host, uint16_t port, String uri, const char *CAcert) {
- return false;
- };
- bool begin(String host, uint16_t port, String uri, const char *CAcert, const char *cli_cert, const char *cli_key) {
- return false;
- };
-#endif // HTTPCLIENT_NOSECURE
-
-#endif
-
- void end(void);
-
- bool connected(void);
-
- void setReuse(bool reuse); /// keep-alive
- void setUserAgent(const String &userAgent);
- void setAcceptEncoding(const String &acceptEncoding);
- void setAuthorization(const char *user, const char *password);
- void setAuthorization(const char *auth);
- void setAuthorizationType(const char *authType);
- void setConnectTimeout(int32_t connectTimeout);
- void setTimeout(uint16_t timeout);
-
- // Redirections
- void setFollowRedirects(followRedirects_t follow);
- void setRedirectLimit(uint16_t limit); // max redirects to follow for a single request
-
- bool setURL(const String &url);
- 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);
- int PUT(String payload);
- int sendRequest(const char *type, String payload);
- int sendRequest(const char *type, uint8_t *payload = NULL, size_t size = 0);
- int sendRequest(const char *type, Stream *stream, size_t size = 0);
-
- void addHeader(const String &name, const String &value, bool first = false, bool replace = true);
-
- /// Response handling
- void collectHeaders(const char *headerKeys[], const size_t headerKeysCount);
- String header(const char *name); // get request header value by name
- String header(size_t i); // get request header value by number
- String headerName(size_t i); // get request header name by number
- int headers(); // get header count
- bool hasHeader(const char *name); // check if header exists
-
- int getSize(void);
- const String &getLocation(void);
-
- NetworkClient &getStream(void);
- NetworkClient *getStreamPtr(void);
- int writeToStream(Stream *stream);
- String getString(void);
-
- static String errorToString(int error);
-
- /// Cookie jar support
- void setCookieJar(CookieJar *cookieJar);
- void resetCookieJar();
- void clearAllCookies();
-
-protected:
- struct RequestArgument {
- String key;
- String value;
- };
-
- bool beginInternal(String url, const char *expectedProtocol);
- void disconnect(bool preserveClient = false);
- void clear();
- int returnError(int error);
- bool connect(void);
- bool sendHeader(const char *type);
- int handleHeaderResponse();
- int writeToStreamDataBlock(Stream *stream, int len);
-
- /// Cookie jar support
- void setCookie(String date, String headerValue);
- bool generateCookieString(String *cookieString);
-
-#ifdef HTTPCLIENT_1_1_COMPATIBLE
- TransportTraitsPtr _transportTraits;
- std::unique_ptr _tcpDeprecated;
-#endif
-
- NetworkClient *_client = nullptr;
-
- /// request handling
- String _host;
- uint16_t _port = 0;
- int32_t _connectTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT;
- bool _reuse = true;
- uint16_t _tcpTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT;
- bool _useHTTP10 = false;
- bool _secure = false;
-
- String _uri;
- String _protocol;
- String _headers;
- String _userAgent = "ESP32HTTPClient";
- String _base64Authorization;
- String _authorizationType = "Basic";
- String _acceptEncoding = "identity;q=1,chunked;q=0.1,*;q=0";
-
- /// Response handling
- RequestArgument *_currentHeaders = nullptr;
- size_t _headerKeysCount = 0;
-
- int _returnCode = 0;
- int _size = -1;
- bool _canReuse = false;
- followRedirects_t _followRedirects = HTTPC_DISABLE_FOLLOW_REDIRECTS;
- uint16_t _redirectLimit = 10;
- String _location;
- transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY;
-
- /// Cookie jar support
- CookieJar *_cookieJar = nullptr;
-};
-
-#endif /* HTTPClient_H_ */
diff --git a/lib/NetworkClientSecure/README.md b/lib/NetworkClientSecure/README.md
deleted file mode 100644
index 0710d3f..0000000
--- a/lib/NetworkClientSecure/README.md
+++ /dev/null
@@ -1,133 +0,0 @@
-NetworkClientSecure
-================
-
-The NetworkClientSecure class implements support for secure connections using TLS (SSL).
-It inherits from NetworkClient and thus implements a superset of that class' interface.
-There are three ways to establish a secure connection using the NetworkClientSecure 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 NetworkClientSecure use setCACert (or the appropriate connect method) to set the root cert of your
- CA or of the public CA
-- When NetworkClientSecure 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 NetworkClientSecure example.
-
-Using a bundle of root certificate authority certificates
----------------------------------------------------------
-This method is similar to the single root certificate verification above, but it uses a standard set of
-root certificates from Mozilla to authenticate against, while the previous method only accepts a single
-certificate for a given server. This allows the client to connect to all public SSL servers.
-
-To use this feature in PlatformIO:
-1. create a certificate bundle as described in the document below, or obtain a pre-built one you trust:
-https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_crt_bundle.html
-(gen_crt_bundle.py can be found in the /tools folder)
- a. note: the full bundle will take up around 64k of flash space, but has minimal RAM usage, as only
- the index of the certificates is kept in RAM
-2. Place the bundle under the file name "data/cert/x509_crt_bundle.bin" in your platformio project
-3. add "board_build.embed_files = data/cert/x509_crt_bundle.bin" in your platformio.ini
-4. add the following global declaration in your project:
- extern const uint8_t rootca_crt_bundle_start[] asm("_binary_data_cert_x509_crt_bundle_bin_start");
-5. before initiating the first SSL connection, call
- my_client.setCACertBundle(rootca_crt_bundle_start);
-
-To use this feature in Arduino IDE:
-If the Arduino IDE added support for embedding files in the meantime, then follow the instructions above.
-If not, you have three choices:
-1. convert your project to PlatformIO
-2. create a makefile where you can add the idf_component_register() declaration to include the certificate bundle
-3. Store the bundle as a SPIFFS file, but then you have to load it into RAM in runtime and waste 64k of precious memory
-
-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 NetworkClientSecure 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 NetworkClientSecure 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 NetworkClientSecure 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 NetworkClientSecure use setPreSharedKey (or the appropriate connect method) to
- set the id/key combo
-- When NetworkClientSecure 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 NetworkClientPSK example.
-
-Specifying the ALPN Protocol
-----------------------------
-
-Application-Layer Protocol Negotiation (ALPN) is a Transport Layer Security (TLS) extension that allows
-the application layer to negotiate which protocol should be performed over a secure connection in a manner
-that avoids additional round trips and which is independent of the application-layer protocols.
-
-For example, this is used with AWS IoT Custom Authorizers where an MQTT client must set the ALPN protocol to ```mqtt```:
-
-```
-const char *aws_protos[] = {"mqtt", NULL};
-...
-wiFiClient.setAlpnProtocols(aws_protos);
-```
-
-Examples
---------
-#### NetworkClientInsecure
-Demonstrates usage of insecure connection using `NetworkClientSecure::setInsecure()`
-#### NetworkClientPSK
-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
-#### NetworkClientSecure
-Wifi secure connection example for ESP32
-Running on TLS 1.2 using mbedTLS
-#### NetworkClientSecureEnterprise
-This example demonstrates a secure connection to a WiFi network using WPA/WPA2 Enterprise (for example eduroam),
-and establishing a secure HTTPS connection with an external server (for example arduino.php5.sk) using the defined anonymous identity, user identity, and password.
-
-.. note::
- This example is outdated and might not work. For more examples see [https://github.com/martinius96/ESP32-eduroam](https://github.com/martinius96/ESP32-eduroam)
-
-#### NetworkClientShowPeerCredentials
-Example of a establishing a secure connection and then showing the fingerprint of the certificate.
-This can be useful in an IoT setting to know for sure that you are connecting to the right server.
-Especially in situations where you cannot hardcode a trusted root certificate for long
-periods of time (as they tend to get replaced more often than the lifecycle of IoT hardware).
diff --git a/lib/NetworkClientSecure/examples/WiFiClientInsecure/WiFiClientInsecure.ino b/lib/NetworkClientSecure/examples/WiFiClientInsecure/WiFiClientInsecure.ino
deleted file mode 100644
index 95009c8..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientInsecure/WiFiClientInsecure.ino
+++ /dev/null
@@ -1,70 +0,0 @@
-#include
-#include
-
-/* This is a very INSECURE approach.
- * If for some reason the secure, proper example NetworkClientSecure
- * does not work for you; then you may want to check the
- * NetworkClientTrustOnFirstUse example first. It is less secure than
- * NetworkClientSecure, but a lot better than this totally insecure
- * approach shown below.
- */
-
-const char *ssid = "your-ssid"; // your network SSID (name of wifi network)
-const char *password = "your-password"; // your network password
-
-const char *server = "www.howsmyssl.com"; // Server URL
-
-NetworkClientSecure 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);
-
- Serial.println("\nStarting connection to server...");
- client.setInsecure(); //skip verification
- if (!client.connect(server, 443)) {
- Serial.println("Connection failed!");
- } else {
- Serial.println("Connected to server!");
- // Make a HTTP request:
- client.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
- client.println("Host: www.howsmyssl.com");
- 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/lib/NetworkClientSecure/examples/WiFiClientInsecure/ci.json b/lib/NetworkClientSecure/examples/WiFiClientInsecure/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientInsecure/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino b/lib/NetworkClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino
deleted file mode 100644
index 42bc886..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- 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
-#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)
-
-NetworkClientSecure 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/lib/NetworkClientSecure/examples/WiFiClientPSK/ci.json b/lib/NetworkClientSecure/examples/WiFiClientPSK/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientPSK/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino b/lib/NetworkClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino
deleted file mode 100644
index 0f95826..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- Wifi secure connection example for ESP32
- Running on TLS 1.2 using mbedTLS
- Supporting the following ciphersuites:
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CCM","TLS_DHE_RSA_WITH_AES_256_CCM","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8","TLS_DHE_RSA_WITH_AES_256_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CCM","TLS_DHE_RSA_WITH_AES_128_CCM","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8","TLS_DHE_RSA_WITH_AES_128_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_GCM_SHA384","TLS_DHE_PSK_WITH_AES_256_CCM","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384","TLS_DHE_PSK_WITH_AES_256_CBC_SHA384","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_DHE_WITH_AES_256_CCM_8","TLS_DHE_PSK_WITH_AES_128_GCM_SHA256","TLS_DHE_PSK_WITH_AES_128_CCM","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256","TLS_DHE_PSK_WITH_AES_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_DHE_WITH_AES_128_CCM_8","TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_256_CCM","TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_256_CCM_8","TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_WITH_AES_128_GCM_SHA256","TLS_RSA_WITH_AES_128_CCM","TLS_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_128_CCM_8","TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_RSA_PSK_WITH_AES_256_GCM_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_128_GCM_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA","TLS_PSK_WITH_AES_256_GCM_SHA384","TLS_PSK_WITH_AES_256_CCM","TLS_PSK_WITH_AES_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CBC_SHA","TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CCM_8","TLS_PSK_WITH_AES_128_GCM_SHA256","TLS_PSK_WITH_AES_128_CCM","TLS_PSK_WITH_AES_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CBC_SHA","TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CCM_8","TLS_PSK_WITH_3DES_EDE_CBC_SHA","TLS_EMPTY_RENEGOTIATION_INFO_SCSV"]
- 2017 - Evandro Copercini - Apache 2.0 License.
-*/
-
-#include
-#include
-
-const char *ssid = "your-ssid"; // your network SSID (name of wifi network)
-const char *password = "your-password"; // your network password
-
-const char *server = "www.howsmyssl.com"; // Server URL
-
-// www.howsmyssl.com root certificate authority, to verify the server
-// change it to your server root CA
-// SHA1 fingerprint is broken now!
-
-const char *test_root_ca = R"literal(
------BEGIN CERTIFICATE-----
-MIIFBTCCAu2gAwIBAgIQS6hSk/eaL6JzBkuoBI110DANBgkqhkiG9w0BAQsFADBP
-MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy
-Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yNDAzMTMwMDAwMDBa
-Fw0yNzAzMTIyMzU5NTlaMDMxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBF
-bmNyeXB0MQwwCgYDVQQDEwNSMTAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
-AoIBAQDPV+XmxFQS7bRH/sknWHZGUCiMHT6I3wWd1bUYKb3dtVq/+vbOo76vACFL
-YlpaPAEvxVgD9on/jhFD68G14BQHlo9vH9fnuoE5CXVlt8KvGFs3Jijno/QHK20a
-/6tYvJWuQP/py1fEtVt/eA0YYbwX51TGu0mRzW4Y0YCF7qZlNrx06rxQTOr8IfM4
-FpOUurDTazgGzRYSespSdcitdrLCnF2YRVxvYXvGLe48E1KGAdlX5jgc3421H5KR
-mudKHMxFqHJV8LDmowfs/acbZp4/SItxhHFYyTr6717yW0QrPHTnj7JHwQdqzZq3
-DZb3EoEmUVQK7GH29/Xi8orIlQ2NAgMBAAGjgfgwgfUwDgYDVR0PAQH/BAQDAgGG
-MB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATASBgNVHRMBAf8ECDAGAQH/
-AgEAMB0GA1UdDgQWBBS7vMNHpeS8qcbDpHIMEI2iNeHI6DAfBgNVHSMEGDAWgBR5
-tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAKG
-Fmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wEwYDVR0gBAwwCjAIBgZngQwBAgEwJwYD
-VR0fBCAwHjAcoBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzANBgkqhkiG9w0B
-AQsFAAOCAgEAkrHnQTfreZ2B5s3iJeE6IOmQRJWjgVzPw139vaBw1bGWKCIL0vIo
-zwzn1OZDjCQiHcFCktEJr59L9MhwTyAWsVrdAfYf+B9haxQnsHKNY67u4s5Lzzfd
-u6PUzeetUK29v+PsPmI2cJkxp+iN3epi4hKu9ZzUPSwMqtCceb7qPVxEbpYxY1p9
-1n5PJKBLBX9eb9LU6l8zSxPWV7bK3lG4XaMJgnT9x3ies7msFtpKK5bDtotij/l0
-GaKeA97pb5uwD9KgWvaFXMIEt8jVTjLEvwRdvCn294GPDF08U8lAkIv7tghluaQh
-1QnlE4SEN4LOECj8dsIGJXpGUk3aU3KkJz9icKy+aUgA+2cP21uh6NcDIS3XyfaZ
-QjmDQ993ChII8SXWupQZVBiIpcWO4RqZk3lr7Bz5MUCwzDIA359e57SSq5CCkY0N
-4B6Vulk7LktfwrdGNVI5BsC9qqxSwSKgRJeZ9wygIaehbHFHFhcBaMDKpiZlBHyz
-rsnnlFXCb5s8HKn5LsUgGvB24L7sGNZP2CX7dhHov+YhD+jozLW2p9W4959Bz2Ei
-RmqDtmiXLnzqTpXbI+suyCsohKRg6Un0RC47+cpiVwHiXZAW+cn8eiNIjqbVgXLx
-KPpdzvvtTnOPlC7SQZSYmdunr3Bf9b77AiC/ZidstK36dRILKz7OA54=
------END CERTIFICATE-----
-)literal";
-// 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
-
-NetworkClientSecure 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.setCACert(test_root_ca);
- //client.setCertificate(test_client_cert); // for client verification
- //client.setPrivateKey(test_client_key); // for client verification
-
- Serial.println("\nStarting connection to server...");
- if (!client.connect(server, 443)) {
- Serial.println("Connection failed!");
- } else {
- Serial.println("Connected to server!");
- // Make a HTTP request:
- client.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
- client.println("Host: www.howsmyssl.com");
- 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/lib/NetworkClientSecure/examples/WiFiClientSecure/ci.json b/lib/NetworkClientSecure/examples/WiFiClientSecure/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientSecure/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino b/lib/NetworkClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino
deleted file mode 100644
index a7149e0..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino
+++ /dev/null
@@ -1,132 +0,0 @@
-/*|-----------------------------------------------------------|*/
-/*|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 |*/
-/*|-----------------------------------------------------------|*/
-
-// This example demonstrates a secure connection to a WiFi network using WPA/WPA2 Enterprise (for example eduroam),
-// and establishing a secure HTTPS connection with an external server (for example arduino.php5.sk) using the defined anonymous identity, user identity, and password.
-
-// Note: this example is outdated and may not work!
-// For more examples see https://github.com/martinius96/ESP32-eduroam
-
-#include
-#include
-#if __has_include("esp_eap_client.h")
-#include "esp_eap_client.h"
-#else
-#include "esp_wpa2.h"
-#endif
-#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
-NetworkClientSecure 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
-#if __has_include("esp_eap_client.h")
- esp_eap_client_set_identity((uint8_t *)EAP_ANONYMOUS_IDENTITY, strlen(EAP_ANONYMOUS_IDENTITY)); //provide identity
- esp_eap_client_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username
- esp_eap_client_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password
- esp_wifi_sta_enterprise_enable();
-#else
- 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_wifi_sta_wpa2_ent_enable();
-#endif
- 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 unsuccessful connection)
- ESP.restart();
- }
- }
- client.setCACert(test_root_ca);
- //client.setCertificate(test_client_cert); // for client verification - certificate
- //client.setPrivateKey(test_client_key); // 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 unsuccessful");
- }
- delay(5000);
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientSecureEnterprise/ci.json b/lib/NetworkClientSecure/examples/WiFiClientSecureEnterprise/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientSecureEnterprise/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientSecureProtocolUpgrade/WiFiClientSecureProtocolUpgrade.ino b/lib/NetworkClientSecure/examples/WiFiClientSecureProtocolUpgrade/WiFiClientSecureProtocolUpgrade.ino
deleted file mode 100644
index a6f76cb..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientSecureProtocolUpgrade/WiFiClientSecureProtocolUpgrade.ino
+++ /dev/null
@@ -1,190 +0,0 @@
-/* STARTSSL example
-
- Inline upgrading from a clear-text connection to an SSL/TLS connection.
-
- Some protocols such as SMTP, XMPP, Mysql, Postgresql and others allow, or require,
- that you start the connection without encryption; and then send a command to switch
- over to encryption.
-
- E.g. a typical SMTP submission would entail a dialog such as this:
-
- 1. client connects to server in the clear
- 2. server says hello
- 3. client sents a EHLO
- 4. server tells the client that it supports SSL/TLS
- 5. client sends a 'STARTTLS' to make use of this faciltiy
- 6. client/server negiotiate a SSL or TLS connection.
- 7. client sends another EHLO
- 8. server now tells the client what (else) is supported; such as additional authentication options.
- ... conversation continues encrypted.
-
- This can be enabled in NetworkClientSecure by telling it to start in plaintext:
-
- client.setPlainStart();
-
- and client is than a plain, TCP, connection (just as NetworkClient would be); until the client calls
- the method:
-
- client.startTLS(); // returns zero on error; non zero on success.
-
- After which things switch to TLS/SSL.
-*/
-
-#include
-#include
-
-#ifndef WIFI_NETWORK
-#define WIFI_NETWORK "YOUR Wifi SSID"
-#endif
-
-#ifndef WIFI_PASSWD
-#define WIFI_PASSWD "your-secret-password"
-#endif
-
-#ifndef SMTP_HOST
-#define SMTP_HOST "smtp.gmail.com"
-#endif
-
-#ifndef SMTP_PORT
-#define SMTP_PORT (587) // Standard (plaintext) submission port
-#endif
-
-const char *ssid = WIFI_NETWORK; // your network SSID (name of wifi network)
-const char *password = WIFI_PASSWD; // your network password
-const char *server = SMTP_HOST; // Server URL
-const int submission_port = SMTP_PORT; // submission port.
-
-NetworkClientSecure client;
-
-static bool readAllSMTPLines();
-
-void setup() {
- int ret;
- //Initialize serial and wait for port to open:
- Serial.begin(115200);
- delay(100);
-
- Serial.print("Attempting to connect to SSID: ");
- Serial.print(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);
-
- Serial.printf("\nStarting connection to server: %s:%d\n", server, submission_port);
-
- // skip verification for this demo. In production one should at the very least
- // enable TOFU; or ideally hardcode a (CA) certificate that is trusted.
- client.setInsecure();
-
- // Enable a plain-test start.
- client.setPlainStart();
-
- if (!client.connect(server, SMTP_PORT)) {
- Serial.println("Connection failed!");
- return;
- };
-
- Serial.println("Connected to server (in the clear, in plaintest)");
-
- if (!readAllSMTPLines()) {
- goto err;
- }
-
- Serial.println("Sending : EHLO\t\tin the clear");
- client.print("EHLO there\r\n");
-
- if (!readAllSMTPLines()) {
- goto err;
- }
-
- Serial.println("Sending : STARTTLS\t\tin the clear");
- client.print("STARTTLS\r\n");
-
- if (!readAllSMTPLines()) {
- goto err;
- }
-
- Serial.println("Upgrading connection to TLS");
- if ((ret = client.startTLS()) <= 0) {
- Serial.printf("Upgrade connection failed: err %d\n", ret);
- goto err;
- }
-
- Serial.println("Sending : EHLO again\t\tover the now encrypted connection");
- client.print("EHLO again\r\n");
-
- if (!readAllSMTPLines()) {
- goto err;
- }
-
- // normally, as this point - we'd be authenticating and then be submitting
- // an email. This has been left out of this example.
-
- Serial.println("Sending : QUIT\t\t\tover the now encrypted connection");
- client.print("QUIT\r\n");
-
- if (!readAllSMTPLines()) {
- goto err;
- }
-
- Serial.println("Completed OK\n");
-err:
- Serial.println("Closing connection");
- client.stop();
-}
-
-// SMTP command repsponse start with three digits and a space;
-// or, for continuation, with three digits and a '-'.
-static bool readAllSMTPLines() {
- String s = "";
- int i;
-
- // blocking read; we cannot rely on a timeout
- // of a NetworkClientSecure read; as it is non
- // blocking.
- const unsigned long timeout = 15 * 1000;
- unsigned long start = millis(); // the timeout is for the entire CMD block response; not per character/line.
- while (1) {
- while ((i = client.available()) == 0 && millis() - start < timeout) {
- /* .. wait */
- };
- if (i == 0) {
- Serial.println("Timeout reading SMTP response");
- return false;
- };
- if (i < 0) {
- break;
- }
-
- i = client.read();
- if (i < 0) {
- break;
- }
-
- if (i > 31 && i < 128) {
- s += (char)i;
- }
- if (i == 0x0A) {
- Serial.print("Receiving: ");
- Serial.println(s);
- if (s.charAt(3) == ' ') {
- return true;
- }
- s = "";
- }
- }
- Serial.printf("Error reading SMTP command response line: %d\n", i);
- return false;
-}
-
-void loop() {
- // do nothing
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientSecureProtocolUpgrade/ci.json b/lib/NetworkClientSecure/examples/WiFiClientSecureProtocolUpgrade/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientSecureProtocolUpgrade/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientShowPeerCredentials/WiFiClientShowPeerCredentials.ino b/lib/NetworkClientSecure/examples/WiFiClientShowPeerCredentials/WiFiClientShowPeerCredentials.ino
deleted file mode 100644
index be12050..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientShowPeerCredentials/WiFiClientShowPeerCredentials.ino
+++ /dev/null
@@ -1,98 +0,0 @@
-// NetworkClientShowPeerCredentials
-//
-// Example of a establishing a secure connection and then
-// showing the fingerprint of the certificate. This can
-// be useful in an IoT setting to know for sure that you
-// are connecting to the right server. Especially in
-// situations where you cannot hardcode a trusted root
-// certificate for long periods of time (as they tend to
-// get replaced more often than the lifecycle of IoT
-// hardware).
-//
-
-#include
-#include
-#include
-
-#ifndef WIFI_NETWORK
-#define WIFI_NETWORK "MyWifiNetwork"
-#endif
-
-#ifndef WIFI_PASSWD
-#define WIFI_PASSWD "MySecretWifiPassword"
-#endif
-
-#define URL "https://arduino.cc"
-
-void demo() {
- NetworkClientSecure *client = new NetworkClientSecure;
- client->setInsecure(); //
-
- HTTPClient https;
- if (!https.begin(*client, URL)) {
- Serial.println("HTTPS setup failed");
- return;
- };
-
- https.setTimeout(5000);
-
- int httpCode = https.GET();
- if (httpCode != 200) {
- Serial.print("Connect failed: ");
- Serial.println(https.errorToString(httpCode));
- return;
- }
-
- const mbedtls_x509_crt *peer = client->getPeerCertificate();
-
- // Show general output / certificate information
- //
- char buf[1024];
- int l = mbedtls_x509_crt_info(buf, sizeof(buf), "", peer);
- if (l <= 0) {
- Serial.println("Peer conversion to printable buffer failed");
- return;
- };
- Serial.println();
- Serial.println(buf);
-
- uint8_t fingerprint_remote[32];
- if (!client->getFingerprintSHA256(fingerprint_remote)) {
- Serial.println("Failed to get the fingerprint");
- return;
- }
- // Fingerprint late 2021
- Serial.println("Expecting Fingerprint (SHA256): 70 CF A4 B7 5D 09 E9 2A 52 A8 B6 85 B5 0B D6 BE 83 47 83 5B 3A 4D 3C 3E 32 30 EC 1D 61 98 D7 0F");
- Serial.print(" Received Fingerprint (SHA256): ");
-
- for (int i = 0; i < 32; i++) {
- Serial.print(fingerprint_remote[i], HEX);
- Serial.print(" ");
- };
- Serial.println("");
-};
-
-void setup() {
- Serial.begin(115200);
- Serial.println("Started " __FILE__ " build " __DATE__ " " __TIME__);
-
- WiFi.mode(WIFI_STA);
- WiFi.begin(WIFI_NETWORK, WIFI_PASSWD);
-
- while (WiFi.waitForConnectResult() != WL_CONNECTED) {
- Serial.println("Wifi fail - rebooting");
- delay(5000);
- ESP.restart();
- }
-}
-
-void loop() {
- bool already_tried = false;
- if ((millis() < 1000) || already_tried) {
- return;
- }
- already_tried = true;
-
- // Run the test just once.
- demo();
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientShowPeerCredentials/ci.json b/lib/NetworkClientSecure/examples/WiFiClientShowPeerCredentials/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientShowPeerCredentials/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientTrustOnFirstUse/WiFiClientTrustOnFirstUse.ino b/lib/NetworkClientSecure/examples/WiFiClientTrustOnFirstUse/WiFiClientTrustOnFirstUse.ino
deleted file mode 100644
index 5b68381..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientTrustOnFirstUse/WiFiClientTrustOnFirstUse.ino
+++ /dev/null
@@ -1,270 +0,0 @@
-/* For any secure connection - it is (at least) essential for the
- the client to verify that it is talking with the server it
- thinks it is talking to. And not some (invisible) man in the middle.
-
- See https://en.wikipedia.org/wiki/Man-in-the-middle_attack,
- https://www.ai.rug.nl/mas/finishedprojects/2011/TLS/hermsencomputerservices.nl/mas/mitm.html or
- https://medium.com/@munteanu210/ssl-certificates-vs-man-in-the-middle-attacks-3fb7846fa5db
- for some background on this.
-
- Unfortunately this means that one needs to hardcode a server
- public key, certificate or some cryptographically strong hash
- thereoff into the code, to verify that you are indeed talking to
- the right server. This is sometimes somewhat impractical. Especially
- if you do not know the server in advance; or if your code needs to be
- stable ovr very long times - during which the server may change.
-
- However completely dispensing with any checks (See the WifiClientInSecure
- example) is also not a good idea either.
-
- This example gives you some middle ground; "Trust on First Use" --
- TOFU - see https://developer.mozilla.org/en-US/docs/Glossary/TOFU or
- https://en.wikipedia.org/wiki/Trust_on_first_use).
-
- In this scheme; we start the very first time without any security checks
- but once we have our first connection; we store the public crytpographic
- details (or a proxy, such as a sha256 of this). And then we use this for
- any subsequent connections.
-
- The assumption here is that we do our very first connection in a somewhat
- trusted network environment; where the chance of a man in the middle is
- very low; or one where the person doing the first run can check the
- details manually.
-
- So this is not quite as good as building a CA certificate into your
- code (as per the WifiClientSecure example). But not as bad as something
- with no trust management at all.
-
- To make it possible for the enduser to 'reset' this trust; the
- startup sequence checks if a certain GPIO is low (assumed to be wired
- to some physical button or jumper on the PCB). And we only allow
- the TOFU to be configured when this pin is LOW.
-*/
-#ifndef WIFI_NETWORK
-#define WIFI_NETWORK "Your Wifi SSID"
-#endif
-
-#ifndef WIFI_PASSWD
-#define WIFI_PASSWD "your-secret-wifi-password"
-#endif
-
-const char *ssid = WIFI_NETWORK; // your network SSID (name of wifi network)
-const char *password = WIFI_PASSWD; // your network password
-const char *server = "www.howsmyssl.com"; // Server to test with.
-
-const int TOFU_RESET_BUTTON = 35; /* Trust reset button wired between GPIO 35 and GND (pulldown) */
-
-#include
-#include
-#include
-
-/* Set aside some persistent memory (i.e. memory that is preserved on reboots and
- power cycling; and will generally survive software updates as well.
-*/
-EEPROMClass TOFU("tofu0");
-
-// Utility function; checks if a given buffer is entirely
-// with with 0 bytes over its full length. Returns 0 on
-// success; a non zero value on fail.
-//
-static int memcmpzero(unsigned char *ptr, size_t len) {
- while (len--) {
- if (0xff != *ptr++) {
- return -1;
- }
- }
- return 0;
-};
-
-static void printSHA256(unsigned char *ptr) {
- for (int i = 0; i < 32; i++) {
- Serial.printf("%s%02x", i ? ":" : "", ptr[i]);
- }
- Serial.println("");
-};
-
-NetworkClientSecure client;
-
-bool get_tofu();
-bool doTOFU_Protected_Connection(uint8_t *fingerprint_tofu);
-
-void setup() {
- bool tofu_reset = false;
- //Initialize serial and wait for port to open:
- Serial.begin(115200);
- delay(100);
-
- if (!TOFU.begin(32)) {
- Serial.println("Could not initialsize the EEPROM");
- return;
- }
- uint8_t fingerprint_tofu[32];
-
- // reset the trust if the tofu reset button is pressed.
- //
- pinMode(TOFU_RESET_BUTTON, INPUT_PULLUP);
- if (digitalRead(TOFU_RESET_BUTTON) == LOW) {
- Serial.println("The TOFU reset button is pressed.");
- tofu_reset = true;
- }
- /* if the button is not pressed; see if we can get the TOFU
- fingerprint from the EEPROM.
- */
- else if (32 != TOFU.readBytes(0, fingerprint_tofu, 32)) {
- Serial.println("Failed to get the fingerprint from memory.");
- tofu_reset = true;
- }
- /* And check that the EEPROM value is not all 0's; in which
- case we also need to do a TOFU.
- */
- else if (!memcmpzero(fingerprint_tofu, 32)) {
- Serial.println("TOFU fingerprint in memory all zero.");
- tofu_reset = true;
- };
- if (!tofu_reset) {
- Serial.print("TOFU pegged to fingerprint: SHA256=");
- printSHA256(fingerprint_tofu);
- Serial.print("Note: You can check this fingerprint by going to the URL\n"
- " and then click on the lock icon.\n");
- };
-
- // attempt to connect to Wifi network:
- Serial.print("Attempting to connect to SSID: ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- Serial.print(".");
- // wait 1 second for re-trying
- delay(1000);
- }
-
- Serial.print("Connected to ");
- Serial.println(ssid);
-
- if (tofu_reset) {
- Serial.println("Resetting trust fingerprint.");
- if (!get_tofu()) {
- Serial.println("Trust reset failed. Giving up");
- return;
- }
- Serial.println("(New) Trust of First used configured. Rebooting in 3 seconds");
- delay(3 * 1000);
- ESP.restart();
- };
-
- Serial.println("Trying to connect to a server; using TOFU details from the eeprom");
-
- if (doTOFU_Protected_Connection(fingerprint_tofu)) {
- Serial.println("ALL OK");
- }
-}
-
-bool get_tofu() {
- Serial.println("\nStarting our insecure connection to server...");
- client.setInsecure(); //skip verification
-
- if (!client.connect(server, 443)) {
- Serial.println("Connection failed!");
- client.stop();
- return false;
- };
-
- Serial.println("Connected to server. Extracting trust data.");
-
- // Now extract the data of the certificate and show it to
- // the user over the serial connection for optional
- // verification.
- const mbedtls_x509_crt *peer = client.getPeerCertificate();
- char buf[1024];
- int l = mbedtls_x509_crt_info(buf, sizeof(buf), "", peer);
- if (l <= 0) {
- Serial.println("Peer conversion to printable buffer failed");
- client.stop();
- return false;
- };
- Serial.println();
- Serial.println(buf);
-
- // Extract the fingerprint - and store this in our EEPROM
- // to be used for future validation.
-
- uint8_t fingerprint_remote[32];
- if (!client.getFingerprintSHA256(fingerprint_remote)) {
- Serial.println("Failed to get the fingerprint");
- client.stop();
- return false;
- }
- if ((32 != TOFU.writeBytes(0, fingerprint_remote, 32)) || (!TOFU.commit())) {
- Serial.println("Could not write the fingerprint to the EEPROM");
- client.stop();
- return false;
- };
- TOFU.end();
- client.stop();
-
- Serial.print("TOFU pegged to fingerprint: SHA256=");
- printSHA256(fingerprint_remote);
-
- return true;
-};
-
-bool doTOFU_Protected_Connection(uint8_t *fingerprint_tofu) {
-
- // As we're not using a (CA) certificate to check the
- // connection; but the hash of the peer - we need to initially
- // allow the connection to be set up without the CA check.
- client.setInsecure(); //skip verification
-
- if (!client.connect(server, 443)) {
- Serial.println("Connection failed!");
- client.stop();
- return false;
- };
-
- // Now that we're connected - we can check that we have
- // end to end trust - by comparing the fingerprint we (now)
- // see (of the server certificate) to the one we have stored
- // in our EEPROM as part of an earlier trust-on-first use.
- uint8_t fingerprint_remote[32];
- if (!client.getFingerprintSHA256(fingerprint_remote)) {
- Serial.println("Failed to get the fingerprint of the server");
- client.stop();
- return false;
- }
- if (memcmp(fingerprint_remote, fingerprint_tofu, 32)) {
- Serial.println("TOFU fingerprint not the same as the one from the server.");
- Serial.print("TOFU : SHA256=");
- printSHA256(fingerprint_tofu);
- Serial.print("Remote: SHA256=");
- printSHA256(fingerprint_remote);
- Serial.println(" : NOT identical -- Aborting!");
- client.stop();
- return false;
- };
-
- Serial.println("All well - you are talking to the same server as\n"
- "when you set up TOFU. So we can now do a GET.\n\n");
-
- client.println("GET /a/check HTTP/1.0");
- client.print("Host: ");
- client.println(server);
- client.println("Connection: close");
- client.println();
-
- bool inhdr = true;
- while (client.connected()) {
- String line = client.readStringUntil('\n');
- Serial.println(line);
- if (inhdr && line == "\r") {
- inhdr = false;
- Serial.println("-- headers received. Payload follows\n\n");
- }
- }
- Serial.println("\n\n-- Payload ended.");
- client.stop();
- return true;
-}
-
-void loop() {}
diff --git a/lib/NetworkClientSecure/examples/WiFiClientTrustOnFirstUse/ci.json b/lib/NetworkClientSecure/examples/WiFiClientTrustOnFirstUse/ci.json
deleted file mode 100644
index d8b3664..0000000
--- a/lib/NetworkClientSecure/examples/WiFiClientTrustOnFirstUse/ci.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "targets": {
- "esp32h2": false
- }
-}
diff --git a/lib/NetworkClientSecure/keywords.txt b/lib/NetworkClientSecure/keywords.txt
deleted file mode 100644
index 7b62f17..0000000
--- a/lib/NetworkClientSecure/keywords.txt
+++ /dev/null
@@ -1,36 +0,0 @@
-#######################################
-# Syntax Coloring Map For WiFi
-#######################################
-
-#######################################
-# Library (KEYWORD3)
-#######################################
-
-NetworkClientSecure KEYWORD3
-
-#######################################
-# Datatypes (KEYWORD1)
-#######################################
-
-NetworkClientSecure KEYWORD1
-
-#######################################
-# Methods and Functions (KEYWORD2)
-#######################################
-
-connect KEYWORD2
-write KEYWORD2
-available KEYWORD2
-config KEYWORD2
-read KEYWORD2
-flush KEYWORD2
-stop KEYWORD2
-connected KEYWORD2
-setCACert KEYWORD2
-setCertificate KEYWORD2
-setPrivateKey KEYWORD2
-setAlpnProtocols KEYWORD2
-
-#######################################
-# Constants (LITERAL1)
-#######################################
diff --git a/lib/NetworkClientSecure/library.properties b/lib/NetworkClientSecure/library.properties
deleted file mode 100644
index e7dab6a..0000000
--- a/lib/NetworkClientSecure/library.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-name=NetworkClientSecure
-version=3.0.3
-author=Evandro Luis Copercini
-maintainer=Github Community
-sentence=Enables secure network connection (local and Internet) using the ESP32 built-in WiFi.
-paragraph=With this library you can make a TLS or SSL connection to a remote server.
-category=Communication
-url=
-architectures=esp32
diff --git a/lib/NetworkClientSecure/src/NetworkClientSecure.cpp b/lib/NetworkClientSecure/src/NetworkClientSecure.cpp
deleted file mode 100644
index 908ddb2..0000000
--- a/lib/NetworkClientSecure/src/NetworkClientSecure.cpp
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
- NetworkClientSecure.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 "NetworkClientSecure.h"
-#include "esp_crt_bundle.h"
-#include
-#include
-#include
-
-#undef connect
-#undef write
-#undef read
-
-NetworkClientSecure::NetworkClientSecure() {
- _connected = false;
- _timeout = 30000; // Same default as ssl_client
-
- sslclient.reset(new sslclient_context, [](struct sslclient_context *sslclient) {
- stop_ssl_socket(sslclient);
- delete sslclient;
- });
- ssl_init(sslclient.get());
- sslclient->socket = -1;
- sslclient->handshake_timeout = 120000;
- _use_insecure = false;
- _stillinPlainStart = false;
- _ca_cert_free = false;
- _cert_free = false;
- _private_key_free = false;
- _CA_cert = NULL;
- _cert = NULL;
- _private_key = NULL;
- _pskIdent = NULL;
- _psKey = NULL;
- next = NULL;
- _alpn_protos = NULL;
- _use_ca_bundle = false;
-}
-
-NetworkClientSecure::NetworkClientSecure(int sock) {
- _connected = false;
- _timeout = 30000; // Same default as ssl_client
- _lastReadTimeout = 0;
- _lastWriteTimeout = 0;
-
- sslclient.reset(new sslclient_context, [](struct sslclient_context *sslclient) {
- stop_ssl_socket(sslclient);
- delete sslclient;
- });
- ssl_init(sslclient.get());
- sslclient->socket = sock;
- sslclient->handshake_timeout = 120000;
-
- if (sock >= 0) {
- _connected = true;
- }
-
- _use_insecure = false;
- _stillinPlainStart = false;
- _ca_cert_free = false;
- _cert_free = false;
- _private_key_free = false;
- _CA_cert = NULL;
- _cert = NULL;
- _private_key = NULL;
- _pskIdent = NULL;
- _psKey = NULL;
- next = NULL;
- _alpn_protos = NULL;
-}
-
-NetworkClientSecure::~NetworkClientSecure() {
- if (_ca_cert_free && _CA_cert) {
- free((void *)_CA_cert);
- }
- if (_cert_free && _cert) {
- free((void *)_cert);
- }
- if (_private_key_free && _private_key) {
- free((void *)_private_key);
- }
-}
-
-void NetworkClientSecure::stop() {
- stop_ssl_socket(sslclient.get());
-
- _connected = false;
- sslclient->peek_buf = -1;
- _lastReadTimeout = 0;
- _lastWriteTimeout = 0;
-}
-
-int NetworkClientSecure::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 NetworkClientSecure::connect(IPAddress ip, uint16_t port, int32_t timeout) {
- _timeout = timeout;
- return connect(ip, port);
-}
-
-int NetworkClientSecure::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 NetworkClientSecure::connect(const char *host, uint16_t port, int32_t timeout) {
- _timeout = timeout;
- return connect(host, port);
-}
-
-int NetworkClientSecure::connect(IPAddress ip, uint16_t port, const char *CA_cert, const char *cert, const char *private_key) {
- return connect(ip, port, NULL, CA_cert, cert, private_key);
-}
-
-int NetworkClientSecure::connect(const char *host, uint16_t port, const char *CA_cert, const char *cert, const char *private_key) {
- IPAddress address;
- if (!Network.hostByName(host, address)) {
- return 0;
- }
-
- return connect(address, port, host, CA_cert, cert, private_key);
-}
-
-int NetworkClientSecure::connect(IPAddress ip, uint16_t port, const char *host, const char *CA_cert, const char *cert, const char *private_key) {
- int ret = start_ssl_client(sslclient.get(), ip, port, host, _timeout, CA_cert, _use_ca_bundle, cert, private_key, NULL, NULL, _use_insecure, _alpn_protos);
-
- if (ret >= 0 && !_stillinPlainStart) {
- ret = ssl_starttls_handshake(sslclient.get());
- } else {
- log_i("Actual TLS start postponed.");
- }
-
- sslclient->last_error = ret;
-
- if (ret < 0) {
- log_e("start_ssl_client: connect failed: %d", ret);
- stop();
- return 0;
- }
- _connected = true;
- return 1;
-}
-
-int NetworkClientSecure::startTLS() {
- int ret = 1;
- if (_stillinPlainStart) {
- log_i("startTLS: starting TLS/SSL on this dplain connection");
- ret = ssl_starttls_handshake(sslclient.get());
- if (ret < 0) {
- log_e("startTLS: %d", ret);
- stop();
- return 0;
- };
- _stillinPlainStart = false;
- } else {
- log_i("startTLS: ignoring StartTLS - as we should be secure already");
- }
- return 1;
-}
-
-int NetworkClientSecure::connect(IPAddress ip, uint16_t port, const char *pskIdent, const char *psKey) {
- return connect(ip.toString().c_str(), port, pskIdent, psKey);
-}
-
-int NetworkClientSecure::connect(const char *host, uint16_t port, const char *pskIdent, const char *psKey) {
- log_v("start_ssl_client with PSK");
-
- IPAddress address;
- if (!Network.hostByName(host, address)) {
- return 0;
- }
-
- int ret = start_ssl_client(sslclient.get(), address, port, host, _timeout, NULL, false, NULL, NULL, pskIdent, psKey, _use_insecure, _alpn_protos);
- sslclient->last_error = ret;
- if (ret < 0) {
- log_e("start_ssl_client: connect failed %d", ret);
- stop();
- return 0;
- }
- _connected = true;
- return 1;
-}
-
-int NetworkClientSecure::peek() {
- if (sslclient->peek_buf >= 0) {
- return sslclient->peek_buf;
- }
- sslclient->peek_buf = timedRead();
- return sslclient->peek_buf;
-}
-
-size_t NetworkClientSecure::write(uint8_t data) {
- return write(&data, 1);
-}
-
-int NetworkClientSecure::read() {
- uint8_t data = -1;
- int res = read(&data, 1);
- return res < 0 ? res : data;
-}
-
-size_t NetworkClientSecure::write(const uint8_t *buf, size_t size) {
- if (!_connected) {
- return 0;
- }
-
- if (_stillinPlainStart) {
- return send_net_data(sslclient.get(), buf, size);
- }
-
- if (_lastWriteTimeout != _timeout) {
- struct timeval timeout_tv;
- timeout_tv.tv_sec = _timeout / 1000;
- timeout_tv.tv_usec = (_timeout % 1000) * 1000;
- if (setSocketOption(SO_SNDTIMEO, (char *)&timeout_tv, sizeof(struct timeval)) >= 0) {
- _lastWriteTimeout = _timeout;
- }
- }
- int res = send_ssl_data(sslclient.get(), buf, size);
- if (res < 0) {
- log_e("Closing connection on failed write");
- stop();
- res = 0;
- }
- return res;
-}
-
-int NetworkClientSecure::read(uint8_t *buf, size_t size) {
- if (_stillinPlainStart) {
- return get_net_receive(sslclient.get(), buf, size);
- }
-
- if (_lastReadTimeout != _timeout) {
- if (fd() >= 0) {
- struct timeval timeout_tv;
- timeout_tv.tv_sec = _timeout / 1000;
- timeout_tv.tv_usec = (_timeout % 1000) * 1000;
- if (setSocketOption(SO_RCVTIMEO, (char *)&timeout_tv, sizeof(struct timeval)) >= 0) {
- _lastReadTimeout = _timeout;
- }
- }
- }
-
- int peeked = 0, res = -1;
- int avail = available();
- if ((!buf && size) || avail <= 0) {
- return -1;
- }
- if (!size) {
- return 0;
- }
- if (sslclient->peek_buf >= 0) {
- buf[0] = sslclient->peek_buf;
- sslclient->peek_buf = -1;
- size--;
- avail--;
- if (!size || !avail) {
- return 1;
- }
- buf++;
- peeked = 1;
- }
- res = get_ssl_receive(sslclient.get(), buf, size);
-
- if (res < 0) {
- log_e("Closing connection on failed read");
- stop();
- return peeked ? peeked : res;
- }
- return res + peeked;
-}
-
-int NetworkClientSecure::available() {
- if (_stillinPlainStart) {
- return peek_net_receive(sslclient.get(), 0);
- }
-
- int peeked = (sslclient->peek_buf >= 0), res = -1;
- if (!_connected) {
- return peeked;
- }
- res = data_to_read(sslclient.get());
-
- if (res < 0 && !_stillinPlainStart) {
- if (res != MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
- log_e("Closing connection on failed available check");
- }
- stop();
- return peeked;
- }
- return res + peeked;
-}
-
-uint8_t NetworkClientSecure::connected() {
- uint8_t dummy = 0;
- read(&dummy, 0);
-
- return _connected;
-}
-
-void NetworkClientSecure::setInsecure() {
- _CA_cert = NULL;
- _cert = NULL;
- _private_key = NULL;
- _pskIdent = NULL;
- _psKey = NULL;
- _use_insecure = true;
-}
-
-void NetworkClientSecure::setCACert(const char *rootCA) {
- if (_ca_cert_free && _CA_cert) {
- free((void *)_CA_cert);
- _ca_cert_free = false;
- }
- _CA_cert = rootCA;
- _use_insecure = false;
-}
-
-void NetworkClientSecure::setCACertBundle(const uint8_t *bundle, size_t size) {
- if (bundle != NULL && size > 0) {
- esp_crt_bundle_set(bundle, size);
- attach_ssl_certificate_bundle(sslclient.get(), true);
- _use_ca_bundle = true;
- } else {
- esp_crt_bundle_detach(NULL);
- attach_ssl_certificate_bundle(sslclient.get(), false);
- _use_ca_bundle = false;
- }
-}
-
-void NetworkClientSecure::setDefaultCACertBundle() {
- attach_ssl_certificate_bundle(sslclient.get(), true);
- _use_ca_bundle = true;
-}
-
-void NetworkClientSecure::setCertificate(const char *client_ca) {
- if (_cert_free && _cert) {
- free((void *)_cert);
- _cert_free = false;
- }
- _cert = client_ca;
-}
-
-void NetworkClientSecure::setPrivateKey(const char *private_key) {
- if (_private_key_free && _private_key) {
- free((void *)_private_key);
- _private_key_free = false;
- }
- _private_key = private_key;
-}
-
-void NetworkClientSecure::setPreSharedKey(const char *pskIdent, const char *psKey) {
- _pskIdent = pskIdent;
- _psKey = psKey;
-}
-
-bool NetworkClientSecure::verify(const char *fp, const char *domain_name) {
- if (!sslclient) {
- return false;
- }
-
- return verify_ssl_fingerprint(sslclient.get(), fp, domain_name);
-}
-
-char *NetworkClientSecure::_streamLoad(Stream &stream, size_t size) {
- char *dest = (char *)malloc(size + 1);
- if (!dest) {
- return nullptr;
- }
- if (size != stream.readBytes(dest, size)) {
- free(dest);
- dest = nullptr;
- return nullptr;
- }
- dest[size] = '\0';
- return dest;
-}
-
-bool NetworkClientSecure::loadCACert(Stream &stream, size_t size) {
- if (_CA_cert != NULL) {
- free(const_cast(_CA_cert));
- }
- char *dest = _streamLoad(stream, size);
- bool ret = false;
- if (dest) {
- setCACert(dest);
- _ca_cert_free = true;
- ret = true;
- }
- return ret;
-}
-
-bool NetworkClientSecure::loadCertificate(Stream &stream, size_t size) {
- if (_cert != NULL) {
- free(const_cast(_cert));
- }
- char *dest = _streamLoad(stream, size);
- bool ret = false;
- if (dest) {
- setCertificate(dest);
- _cert_free = true;
- ret = true;
- }
- return ret;
-}
-
-bool NetworkClientSecure::loadPrivateKey(Stream &stream, size_t size) {
- if (_private_key != NULL) {
- free(const_cast(_private_key));
- }
- char *dest = _streamLoad(stream, size);
- bool ret = false;
- if (dest) {
- setPrivateKey(dest);
- _private_key_free = true;
- ret = true;
- }
- return ret;
-}
-
-int NetworkClientSecure::lastError(char *buf, const size_t size) {
- int lastError = sslclient->last_error;
- mbedtls_strerror(lastError, buf, size);
- return lastError;
-}
-
-void NetworkClientSecure::setHandshakeTimeout(unsigned long handshake_timeout) {
- sslclient->handshake_timeout = handshake_timeout * 1000;
-}
-
-void NetworkClientSecure::setAlpnProtocols(const char **alpn_protos) {
- _alpn_protos = alpn_protos;
-}
-
-int NetworkClientSecure::fd() const {
- return sslclient->socket;
-}
diff --git a/lib/NetworkClientSecure/src/NetworkClientSecure.h b/lib/NetworkClientSecure/src/NetworkClientSecure.h
deleted file mode 100644
index ebfcf76..0000000
--- a/lib/NetworkClientSecure/src/NetworkClientSecure.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- NetworkClientSecure.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 NetworkClientSecure_h
-#define NetworkClientSecure_h
-#include "Arduino.h"
-#include "IPAddress.h"
-#include "Network.h"
-#include "ssl_client.h"
-#include
-
-class NetworkClientSecure : public NetworkClient {
-protected:
- std::shared_ptr sslclient;
-
- bool _use_insecure;
- bool _stillinPlainStart;
- bool _ca_cert_free;
- bool _cert_free;
- bool _private_key_free;
- 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
- const char **_alpn_protos;
- bool _use_ca_bundle;
-
-public:
- NetworkClientSecure *next;
- NetworkClientSecure();
- NetworkClientSecure(int socket);
- ~NetworkClientSecure();
- 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 connect(IPAddress ip, uint16_t port, const char *host, const char *CA_cert, const char *cert, const char *private_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 setInsecure(); // Don't validate the chain, just accept whatever is given. VERY INSECURE!
- 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);
- void setCACertBundle(const uint8_t *bundle, size_t size);
- void setDefaultCACertBundle();
- 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);
- void setAlpnProtocols(const char **alpn_protos);
-
- // Certain protocols start in plain-text; and then have the client
- // give some STARTSSL command to `upgrade' the connection to TLS
- // or SSL. Setting PlainStart to true (the default is false) enables
- // this. It is up to the application code to then call 'startTLS()'
- // at the right point to initialize the SSL or TLS upgrade.
-
- void setPlainStart() {
- _stillinPlainStart = true;
- };
- bool stillInPlainStart() {
- return _stillinPlainStart;
- };
- int startTLS();
-
- const mbedtls_x509_crt *getPeerCertificate() {
- return mbedtls_ssl_get_peer_cert(&sslclient->ssl_ctx);
- };
- bool getFingerprintSHA256(uint8_t sha256_result[32]) {
- return get_peer_fingerprint(sslclient.get(), sha256_result);
- };
- int fd() const;
-
- operator bool() {
- return connected();
- }
-
- bool operator==(const bool value) {
- return bool() == value;
- }
- bool operator!=(const bool value) {
- return bool() != value;
- }
- bool operator==(const NetworkClientSecure &);
- bool operator!=(const NetworkClientSecure &rhs) {
- return !this->operator==(rhs);
- };
-
- int socket() {
- return sslclient->socket = -1;
- }
-
-private:
- char *_streamLoad(Stream &stream, size_t size);
-
- //friend class NetworkServer;
- using Print::write;
-};
-
-#endif /* _WIFICLIENT_H_ */
diff --git a/lib/NetworkClientSecure/src/WiFiClientSecure.h b/lib/NetworkClientSecure/src/WiFiClientSecure.h
deleted file mode 100644
index 56e7f28..0000000
--- a/lib/NetworkClientSecure/src/WiFiClientSecure.h
+++ /dev/null
@@ -1,3 +0,0 @@
-#pragma once
-#include "NetworkClientSecure.h"
-typedef NetworkClientSecure WiFiClientSecure;
diff --git a/lib/NetworkClientSecure/src/ssl_client.cpp b/lib/NetworkClientSecure/src/ssl_client.cpp
deleted file mode 100644
index 0f93f5c..0000000
--- a/lib/NetworkClientSecure/src/ssl_client.cpp
+++ /dev/null
@@ -1,633 +0,0 @@
-/* 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 "esp_crt_bundle.h"
-
-#if !defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && !defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
-#warning \
- "Please call `idf.py menuconfig` then go to Component config -> mbedTLS -> TLS Key Exchange Methods -> Enable pre-shared-key ciphersuites and then check `Enable PSK based ciphersuite modes`. Save and Quit."
-#else
-
-const char *pers = "esp32-tls";
-
-static int _handle_error(int err, const char *function, int line) {
- if (err == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
- return err;
- }
-#ifdef MBEDTLS_ERROR_C
- char error_buf[100];
- mbedtls_strerror(err, error_buf, 100);
- log_e("[%s():%d]: (%d) %s", function, line, err, error_buf);
-#else
- log_e("[%s():%d]: code %d", function, line, err);
-#endif
- return err;
-}
-
-#define handle_error(e) _handle_error(e, __FUNCTION__, __LINE__)
-
-void ssl_init(sslclient_context *ssl_client) {
- // reset embedded pointers to zero
- memset(ssl_client, 0, sizeof(sslclient_context));
- mbedtls_ssl_init(&ssl_client->ssl_ctx);
- mbedtls_ssl_config_init(&ssl_client->ssl_conf);
- mbedtls_ctr_drbg_init(&ssl_client->drbg_ctx);
- ssl_client->peek_buf = -1;
-}
-
-void attach_ssl_certificate_bundle(sslclient_context *ssl_client, bool att) {
- if (att) {
- ssl_client->bundle_attach_cb = &esp_crt_bundle_attach;
- } else {
- ssl_client->bundle_attach_cb = NULL;
- }
-}
-
-int start_ssl_client(
- sslclient_context *ssl_client, const IPAddress &ip, uint32_t port, const char *hostname, int timeout, const char *rootCABuff, bool useRootCABundle,
- const char *cli_cert, const char *cli_key, const char *pskIdent, const char *psKey, bool insecure, const char **alpn_protos
-) {
- int ret;
- int enable = 1;
- log_v("Free internal heap before TLS %u", ESP.getFreeHeap());
-
- if (rootCABuff == NULL && pskIdent == NULL && psKey == NULL && !insecure && !useRootCABundle) {
- return -1;
- }
-
- int domain = ip.type() == IPv6 ? AF_INET6 : AF_INET;
- log_v("Starting socket (domain %d)", domain);
- ssl_client->socket = -1;
-
- ssl_client->socket = lwip_socket(domain, SOCK_STREAM, IPPROTO_TCP);
- if (ssl_client->socket < 0) {
- log_e("ERROR opening socket");
- return ssl_client->socket;
- }
-
- fcntl(ssl_client->socket, F_SETFL, fcntl(ssl_client->socket, F_GETFL, 0) | O_NONBLOCK);
- struct sockaddr_storage serv_addr = {};
- if (domain == AF_INET6) {
- struct sockaddr_in6 *tmpaddr = (struct sockaddr_in6 *)&serv_addr;
- tmpaddr->sin6_family = AF_INET6;
- for (int index = 0; index < 16; index++) {
- tmpaddr->sin6_addr.s6_addr[index] = ip[index];
- }
- tmpaddr->sin6_port = htons(port);
- tmpaddr->sin6_scope_id = ip.zone();
- } else {
- struct sockaddr_in *tmpaddr = (struct sockaddr_in *)&serv_addr;
- tmpaddr->sin_family = AF_INET;
- tmpaddr->sin_addr.s_addr = ip;
- tmpaddr->sin_port = htons(port);
- }
-
- if (timeout <= 0) {
- timeout = 30000; // Milli seconds.
- }
-
- ssl_client->socket_timeout = timeout;
-
- fd_set fdset;
- struct timeval tv;
- FD_ZERO(&fdset);
- FD_SET(ssl_client->socket, &fdset);
- tv.tv_sec = timeout / 1000;
- tv.tv_usec = (timeout % 1000) * 1000;
-
- int res = lwip_connect(ssl_client->socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
- if (res < 0 && errno != EINPROGRESS) {
- log_e("connect on fd %d, errno: %d, \"%s\"", ssl_client->socket, errno, strerror(errno));
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- return -1;
- }
-
- res = select(ssl_client->socket + 1, nullptr, &fdset, nullptr, timeout < 0 ? nullptr : &tv);
- if (res < 0) {
- log_e("select on fd %d, errno: %d, \"%s\"", ssl_client->socket, errno, strerror(errno));
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- return -1;
- } else if (res == 0) {
- log_i("select returned due to timeout %d ms for fd %d", timeout, ssl_client->socket);
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- return -1;
- } else {
- int sockerr;
- socklen_t len = (socklen_t)sizeof(int);
- res = getsockopt(ssl_client->socket, SOL_SOCKET, SO_ERROR, &sockerr, &len);
-
- if (res < 0) {
- log_e("getsockopt on fd %d, errno: %d, \"%s\"", ssl_client->socket, errno, strerror(errno));
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- return -1;
- }
-
- if (sockerr != 0) {
- log_e("socket error on fd %d, errno: %d, \"%s\"", ssl_client->socket, sockerr, strerror(sockerr));
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- return -1;
- }
- }
-
-#define ROE(x, msg) \
- { \
- if (((x) < 0)) { \
- log_e("LWIP Socket config of " msg " failed."); \
- return -1; \
- } \
- }
- ROE(lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), "SO_RCVTIMEO");
- ROE(lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), "SO_SNDTIMEO");
-
- ROE(lwip_setsockopt(ssl_client->socket, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable)), "TCP_NODELAY");
- ROE(lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)), "SO_KEEPALIVE");
-
- 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);
- }
-
- if (alpn_protos != NULL) {
- log_v("Setting ALPN protocols");
- if ((ret = mbedtls_ssl_conf_alpn_protocols(&ssl_client->ssl_conf, alpn_protos)) != 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 (insecure) {
- mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_NONE);
- log_d("WARNING: Skipping SSL Verification. INSECURE!");
- } else 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) {
- // free the ca_cert in the case parse failed, otherwise, the old ca_cert still in the heap memory, that lead to "out of memory" crash.
- mbedtls_x509_crt_free(&ssl_client->ca_cert);
- return handle_error(ret);
- }
- } else if (useRootCABundle) {
- if (ssl_client->bundle_attach_cb != NULL) {
- log_v("Attaching root CA cert bundle");
- ret = ssl_client->bundle_attach_cb(&ssl_client->ssl_conf);
- if (ret < 0) {
- return handle_error(ret);
- }
- } else {
- log_e("useRootCABundle is set, but attach_ssl_certificate_bundle(ssl, true); was not called!");
- }
- } 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 < strlen(psKey); j += 2) {
- char c = psKey[j];
- 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 << 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 {
- return -1;
- }
-
- // Note - this check for BOTH key and cert is relied on
- // later during cleanup.
-
- if (!insecure && 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) {
- // free the client_cert in the case parse failed, otherwise, the old client_cert still in the heap memory, that lead to "out of memory" crash.
- mbedtls_x509_crt_free(&ssl_client->client_cert);
- return handle_error(ret);
- }
-
- log_v("Loading private key");
- mbedtls_ctr_drbg_context ctr_drbg;
- mbedtls_ctr_drbg_init(&ctr_drbg);
- ret = mbedtls_pk_parse_key(&ssl_client->client_key, (const unsigned char *)cli_key, strlen(cli_key) + 1, NULL, 0, mbedtls_ctr_drbg_random, &ctr_drbg);
- mbedtls_ctr_drbg_free(&ctr_drbg);
-
- if (ret != 0) {
- mbedtls_x509_crt_free(&ssl_client->client_cert); // cert+key are free'd in pair
- 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, hostname != NULL ? hostname : ip.toString().c_str())) != 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);
- return ssl_client->socket;
-}
-
-int ssl_starttls_handshake(sslclient_context *ssl_client) {
- char buf[512];
- int ret, flags;
-
- 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(2); //2 ticks
- }
-
- if (ssl_client->client_cert.version) {
- 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) {
- memset(buf, 0, sizeof(buf));
- mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags);
- log_e("Failed to verify peer certificate! verification info: %s", buf);
- return handle_error(ret);
- } else {
- log_v("Certificate verified.");
- }
-
- if (ssl_client->ca_cert.version) {
- mbedtls_x509_crt_free(&ssl_client->ca_cert);
- }
-
- // We know that we always have a client cert/key pair -- and we
- // cannot look into the private client_key pk struct for newer
- // versions of mbedtls. So rely on a public field of the cert
- // and infer that there is a key too.
- if (ssl_client->client_cert.version) {
- mbedtls_x509_crt_free(&ssl_client->client_cert);
- 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) {
- log_v("Cleaning SSL connection.");
-
- if (ssl_client->socket >= 0) {
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- }
-
- // avoid memory leak if ssl connection attempt failed
- // if (ssl_client->ssl_conf.ca_chain != NULL) {
- mbedtls_x509_crt_free(&ssl_client->ca_cert);
- // }
- // if (ssl_client->ssl_conf.key_cert != NULL) {
- mbedtls_x509_crt_free(&ssl_client->client_cert);
- mbedtls_pk_free(&ssl_client->client_key);
- // }
- 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);
-
- // save only interesting fields
- int handshake_timeout = ssl_client->handshake_timeout;
- int socket_timeout = ssl_client->socket_timeout;
- int last_err = ssl_client->last_error;
-
- // reset embedded pointers to zero
- memset(ssl_client, 0, sizeof(sslclient_context));
-
- ssl_client->handshake_timeout = handshake_timeout;
- ssl_client->socket_timeout = socket_timeout;
- ssl_client->last_error = last_err;
- ssl_client->peek_buf = -1;
-}
-
-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, size_t len) {
- unsigned long write_start_time = millis();
- int ret = -1;
-
- while ((ret = mbedtls_ssl_write(&ssl_client->ssl_ctx, data, len)) <= 0) {
- if ((millis() - write_start_time) > ssl_client->socket_timeout) {
- log_v("SSL write timed out.");
- return -1;
- }
-
- if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret < 0) {
- log_v("Handling error %d", ret); //for low level debug
- return handle_error(ret);
- }
-
- //wait for space to become available
- vTaskDelay(2);
- }
-
- return ret;
-}
-
-// Some protocols, such as SMTP, XMPP, MySQL/Posgress and various others
-// do a 'in-line' upgrade from plaintext to SSL or TLS (usually with some
-// sort of 'STARTTLS' textual command from client to sever). For this
-// we need to have access to the 'raw' socket; i.e. without TLS/SSL state
-// handling before the handshake starts; but after setting up the TLS
-// connection.
-//
-int peek_net_receive(sslclient_context *ssl_client, int timeout) {
-#if MBEDTLS_FIXED_LINKING_NET_POLL
- int ret = mbedtls_net_poll((mbedtls_net_context *)ssl_client, MBEDTLS_NET_POLL_READ, timeout);
- ret == MBEDTLS_NET_POLL_READ ? 1 : ret;
-#else
- // We should be using mbedtls_net_poll(); which is part of mbedtls and
- // included in the EspressifSDK. Unfortunately - it did not make it into
- // the statically linked library file. So, for now, we replace it by
- // substancially similar code.
- //
- struct timeval tv = {.tv_sec = timeout / 1000, .tv_usec = (timeout % 1000) * 1000};
-
- fd_set fdset;
- FD_SET(ssl_client->socket, &fdset);
-
- int ret = select(ssl_client->socket + 1, &fdset, nullptr, nullptr, timeout < 0 ? nullptr : &tv);
- if (ret < 0) {
- log_e("select on read fd %d, errno: %d, \"%s\"", ssl_client->socket, errno, strerror(errno));
- lwip_close(ssl_client->socket);
- ssl_client->socket = -1;
- return -1;
- };
-#endif
- return ret;
-};
-
-int get_net_receive(sslclient_context *ssl_client, uint8_t *data, int length) {
- int ret = peek_net_receive(ssl_client, ssl_client->socket_timeout);
- if (ret > 0) {
- ret = mbedtls_net_recv(ssl_client, data, length);
- }
-
- // log_v( "%d bytes NET read of %d", ret, length); //for low level debug
- return ret;
-}
-
-int send_net_data(sslclient_context *ssl_client, const uint8_t *data, size_t len) {
- int ret = mbedtls_net_send(ssl_client, data, len);
- // log_v("Net sending %d btes->ret %d", len, ret); //for low level debug
- return ret;
-}
-
-int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length) {
- int ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, data, length);
- // log_v( "%d bytes SSL 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);
- }
-
- // Calculate certificate's SHA256 fingerprint
- uint8_t fingerprint_remote[32];
- if (!get_peer_fingerprint(ssl_client, fingerprint_remote)) {
- return false;
- }
-
- // 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;
- }
-}
-
-bool get_peer_fingerprint(sslclient_context *ssl_client, uint8_t sha256[32]) {
- if (!ssl_client) {
- log_d("Invalid ssl_client pointer");
- return false;
- };
-
- const mbedtls_x509_crt *crt = mbedtls_ssl_get_peer_cert(&ssl_client->ssl_ctx);
- if (!crt) {
- log_d("Failed to get peer cert.");
- return false;
- };
-
- 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, sha256);
-
- 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;
-}
-#endif
diff --git a/lib/NetworkClientSecure/src/ssl_client.h b/lib/NetworkClientSecure/src/ssl_client.h
deleted file mode 100644
index 892adc8..0000000
--- a/lib/NetworkClientSecure/src/ssl_client.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* 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_sockets.h"
-#include "mbedtls/debug.h"
-#include "mbedtls/ssl.h"
-#include "mbedtls/entropy.h"
-#include "mbedtls/ctr_drbg.h"
-#include "mbedtls/error.h"
-
-typedef esp_err_t (*crt_bundle_attach_cb)(void *conf);
-
-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;
-
- crt_bundle_attach_cb bundle_attach_cb;
-
- unsigned long socket_timeout;
- unsigned long handshake_timeout;
-
- int last_error;
- int peek_buf;
-
-} sslclient_context;
-
-void ssl_init(sslclient_context *ssl_client);
-int start_ssl_client(
- sslclient_context *ssl_client, const IPAddress &ip, uint32_t port, const char *hostname, int timeout, const char *rootCABuff, bool useRootCABundle,
- const char *cli_cert, const char *cli_key, const char *pskIdent, const char *psKey, bool insecure, const char **alpn_protos
-);
-void attach_ssl_certificate_bundle(sslclient_context *ssl_client, bool att);
-int ssl_starttls_handshake(sslclient_context *ssl_client);
-void stop_ssl_socket(sslclient_context *ssl_client);
-int data_to_read(sslclient_context *ssl_client);
-int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, size_t len);
-int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length);
-int send_net_data(sslclient_context *ssl_client, const uint8_t *data, size_t len);
-int get_net_receive(sslclient_context *ssl_client, uint8_t *data, int length);
-int peek_net_receive(sslclient_context *ssl_client, int timeout);
-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);
-bool get_peer_fingerprint(sslclient_context *ssl_client, uint8_t sha256[32]);
-#endif
diff --git a/lib/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino b/lib/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino
deleted file mode 100644
index e8e8153..0000000
--- a/lib/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- 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();
- delay(2);//allow the cpu to switch to other tasks
-}
-
-void drawGraph() {
- String out = "";
- char temp[100];
- out += "\n";
-
- server.send(200, "image/svg+xml", out);
-}
diff --git a/lib/WebServer/examples/FSBrowser/FSBrowser.ino b/lib/WebServer/examples/FSBrowser/FSBrowser.ino
deleted file mode 100644
index f33f5db..0000000
--- a/lib/WebServer/examples/FSBrowser/FSBrowser.ino
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- 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();
- delay(2);//allow the cpu to switch to other tasks
-}
diff --git a/lib/WebServer/examples/FSBrowser/data/edit.htm.gz b/lib/WebServer/examples/FSBrowser/data/edit.htm.gz
deleted file mode 100644
index 69ce414..0000000
Binary files a/lib/WebServer/examples/FSBrowser/data/edit.htm.gz and /dev/null differ
diff --git a/lib/WebServer/examples/FSBrowser/data/favicon.ico b/lib/WebServer/examples/FSBrowser/data/favicon.ico
deleted file mode 100644
index 71b25fe..0000000
Binary files a/lib/WebServer/examples/FSBrowser/data/favicon.ico and /dev/null differ
diff --git a/lib/WebServer/examples/FSBrowser/data/graphs.js.gz b/lib/WebServer/examples/FSBrowser/data/graphs.js.gz
deleted file mode 100644
index 7243544..0000000
Binary files a/lib/WebServer/examples/FSBrowser/data/graphs.js.gz and /dev/null differ
diff --git a/lib/WebServer/examples/FSBrowser/data/index.htm b/lib/WebServer/examples/FSBrowser/data/index.htm
deleted file mode 100644
index 9cb560c..0000000
--- a/lib/WebServer/examples/FSBrowser/data/index.htm
+++ /dev/null
@@ -1,97 +0,0 @@
-
-
-
-
-
- ESP Monitor
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/lib/WebServer/examples/HelloServer/HelloServer.ino b/lib/WebServer/examples/HelloServer/HelloServer.ino
deleted file mode 100644
index d807ff0..0000000
--- a/lib/WebServer/examples/HelloServer/HelloServer.ino
+++ /dev/null
@@ -1,74 +0,0 @@
-#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 esp32!");
- 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();
- delay(2);//allow the cpu to switch to other tasks
-}
diff --git a/lib/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino b/lib/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino
deleted file mode 100644
index e2af955..0000000
--- a/lib/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- 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();
- delay(2);//allow the cpu to switch to other tasks
-}
diff --git a/lib/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino b/lib/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino
deleted file mode 100644
index a370a24..0000000
--- a/lib/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino
+++ /dev/null
@@ -1,42 +0,0 @@
-#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();
- delay(2);//allow the cpu to switch to other tasks
-}
diff --git a/lib/WebServer/examples/PathArgServer/PathArgServer.ino b/lib/WebServer/examples/PathArgServer/PathArgServer.ino
deleted file mode 100644
index 8482b2d..0000000
--- a/lib/WebServer/examples/PathArgServer/PathArgServer.ino
+++ /dev/null
@@ -1,57 +0,0 @@
-#include
-#include
-#include
-#include
-
-#include
-#include