Remove old and modified libs, switch to ESPAsyncWebserver, add support for ESP32-H2 and multiple Ethernet modules (#455)

* Asyncwebserver

* Squashed commit of the following:

commit 575ef02f593918ec6654c87407a4d11fc17071b8
Author: technyon <j.o.schuemann@gmx.de>
Date:   Mon Aug 12 17:56:11 2024 +0200

    merge master

commit 35e5adf4ecd80f9829e8801181f35dd2c1d94759
Merge: a2cc7be2 21adca01
Author: technyon <j.o.schuemann@gmx.de>
Date:   Mon Aug 12 17:41:04 2024 +0200

    Merge branch 'master' of github.com:technyon/nuki_hub into DM9051

commit a2cc7be2954cbd8767ab8186296c0b14134d1d0b
Author: technyon <j.o.schuemann@gmx.de>
Date:   Mon Aug 12 10:51:50 2024 +0200

    update nuki ble

commit 20c809f3dca28b29b219d1ff3a183f1981316de5
Author: technyon <j.o.schuemann@gmx.de>
Date:   Mon Aug 12 10:44:46 2024 +0200

    backup

commit dd41c218efb5270f5efeb734e64dff695920db16
Merge: 153000b5 e84b944a
Author: technyon <j.o.schuemann@gmx.de>
Date:   Mon Aug 12 10:40:03 2024 +0200

    Merge branch 'master' of github.com:technyon/nuki_hub into DM9051

commit 153000b5b1af7df1fbeb5263df94eb26f689cc0a
Author: technyon <j.o.schuemann@gmx.de>
Date:   Mon Aug 12 10:23:07 2024 +0200

    fix linker error

commit a93bbfbfc4301e46ff3696a763dd13c6c89efefb
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sun Aug 11 11:27:07 2024 +0200

    backup

commit f611c75ce8c35f829bcad6cf7e86188f4b3ec331
Merge: f1964917 063fbab6
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sun Aug 11 11:24:47 2024 +0200

    merge master

commit f1964917b4dade3920f1ecdb699c58630199e6da
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sat Aug 10 15:17:45 2024 +0200

    update platformio.ini

commit f448e5e8a7e93be38e09e2ab0b622199a3721af6
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sat Aug 10 11:28:09 2024 +0200

    add SPIClass instance for DM9051

commit 1f190e9aa08033535a2eb442a92e6e20409bbda1
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sat Aug 10 11:22:26 2024 +0200

    add definitions and constructor for DM9051

commit 726b3602ae91594ee1210ad5b6714f75cc5e42a7
Merge: 50a2eb13 4af90cbc
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sat Aug 10 10:19:34 2024 +0200

    merge master

commit 50a2eb136d75d90921f1c6974f18bc107bddc123
Author: technyon <j.o.schuemann@gmx.de>
Date:   Fri Aug 9 11:52:09 2024 +0200

    add comment

commit 9437e485cae169efdf8e5a7bf188a1c7e792d1e5
Author: technyon <j.o.schuemann@gmx.de>
Date:   Sun Aug 4 08:29:21 2024 +0200

    move LAN8720 definitions to seperate file

* Remove Core 2 Ethernet library

* Custom Ethernet

* GPIO and Preferences

* H2
This commit is contained in:
iranl
2024-08-16 13:02:37 +02:00
committed by GitHub
parent 346c5c65d1
commit 9a896a7ab1
206 changed files with 4055 additions and 20829 deletions

View File

@@ -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:

View File

@@ -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:

View File

@@ -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:

View File

@@ -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:

View File

@@ -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

View File

@@ -22,9 +22,6 @@ debug: $(DEBUG_BOARDS)
all: release updater debug
# Alias
.PHONY: esp32
esp32: esp32dev
esp%:
@echo "Building $@"
pio run --environment $@

View File

@@ -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.
<b>Not supported ESP32 devices:</b>
- 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).
<b>Supported Nuki devices:</b>
- Nuki Smart Lock 1.0
@@ -36,7 +35,7 @@ Feel free to join us on Discord: https://discord.gg/9nPq85bP4p
- Nuki Keypad 2.0
<b>Supported Ethernet devices:</b><br>
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:<br>
@@ -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.<br>
<br>
The firmware supports SSL encryption for MQTT, however most people and especially home users don't use this.<br>
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.<br>
Your settings will not be affected when updating using the above instructions (do not select erase device when updating using Webflash).<br>
## MQTT Encryption (optional; Wi-Fi and LAN8720 only)
## MQTT Encryption (optional)
The communication via MQTT can be SSL encrypted.<br>
To enable SSL encryption, supply the necessary information in the MQTT Configuration page.<br>
@@ -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.<Br>
Currently the Wiznet W5x00 Module (W5100, W5200, W5500), DN9051 and KSZ8851SNL chips are supported.<br>
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:<br>
- W5x00 SCK to GPIO18<br>
- W5x00 MISO to GPIO19<br>
- W5x00 MOSI to GPIO23<br>
- W5x00 CS/SS to GPIO5<br>
- Optionally connect:<br>
- W5x00 reset to GPIO33<br>
- Connect W5x00 to ESP32 SPI:<br>
- W5x00 SCK to GPIO 8<br>
- W5x00 MISO to GPIO 9<br>
- W5x00 MOSI to GPIO 10<br>
- W5x00 CS/SS to GPIO 5<br>
Optional:
- W5x00 RST to GPIO 4<br>
- W5x00 INT/IRQ to GPIO 3<br>
Now connect via Wi-Fi and change the network hardware to "Generic W5500".<br>
If the W5500 hwardware isn't detected, Wi-Fi is used as a fallback.<br>
If Ethernet hwardware isn't detected, Wi-Fi is used as a fallback, unless this is disabled in the settings.<br>
<br>
Note: Encrypted MQTT is only available for Wi-Fi and LAN8720 modules, W5x00 modules don't support encryption<br>
(that leaves Olimex, WT32-ETH01 and M5Stack PoESP32 Unit if encryption is desired).<br>
Note: LAN8720 modules are only supported on the ESP32, not on the ESP32-S3, ESP32-C3 or ESP-C6<br>
<br>
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<br>
## 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

View File

@@ -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

View File

@@ -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:

View File

@@ -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:

View File

@@ -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",

View File

@@ -1,5 +1,5 @@
name=ESPAsyncWebServer
version=3.1.2
version=3.1.5
author=Me-No-Dev
maintainer=Mathieu Carbou <mathieu.carbou@gmail.com>
sentence=Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040

View File

@@ -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

View File

@@ -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<bool(AsyncWebServerRequest* request)>;
@@ -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

View File

@@ -35,20 +35,20 @@
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#elif defined(TARGET_RP2040)
#include <WiFi.h>
#include <AsyncTCP_RP2040W.h>
#include <http_parser.h>
#include <HTTP_Method.h>
#include <WiFi.h>
#include <http_parser.h>
#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;

View File

@@ -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);
}

View File

@@ -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:

View File

@@ -28,6 +28,7 @@
#endif
#include <memory>
#include <vector>
#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<cbuf> _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;

View File

@@ -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;

View File

@@ -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

View File

@@ -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";

View File

@@ -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

View File

@@ -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

View File

@@ -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

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -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.
![Arduino UNO Pin map.](./arduino_uno_ethernet_pins.png)
![Arduino MEGA Pin map.](./arduino_mega_ethernet_pins.png)
To use this library
```
#include <SPI.h>
#include <Ethernet.h>
```

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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();
}
}
}

View File

@@ -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 <Ethernet.h>
// the sensor communicates using SPI, so include the library:
#include <SPI.h>
// 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("<br />");
client.print("Pressure: " + String(pressure));
client.print(" Pa");
client.println("<br />");
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);
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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);
}
}
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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;
}
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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();
}
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
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);
}

View File

@@ -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 <Ethernet.h>
// 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) */
}
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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);
}
}
}

View File

@@ -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 <Ethernet.h>
#include <EthernetUdp.h>
// 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();
}
*/

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// 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();
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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);
}
}
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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");
}
}

View File

@@ -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 <SPI.h>
#include <Ethernet.h>
// 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("<!DOCTYPE HTML>");
client.println("<html>");
// 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("<br />");
}
client.println("</html>");
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");
}
}

View File

@@ -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

View File

@@ -1,10 +0,0 @@
name=Ethernet
version=2.0.2
author=Various (see AUTHORS file for details)
maintainer=Arduino <info@arduino.cc>
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

View File

@@ -1,437 +0,0 @@
// DHCP Library v0.3 - April 25, 2009
// Author: Jordan Terrell - blog.jordanterrell.com
#include <Arduino.h>
#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);
}

View File

@@ -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

View File

@@ -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 <Arduino.h>
#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;
}

View File

@@ -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

View File

@@ -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 <Arduino.h>
#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;

View File

@@ -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 <Arduino.h>
#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

View File

@@ -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 <Arduino.h>
#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;
}

View File

@@ -1,3 +0,0 @@
// This file is in the public domain. No copyright is claimed.
#include "Ethernet.h"

View File

@@ -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 <Arduino.h>
#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;
}

View File

@@ -1,3 +0,0 @@
// This file is in the public domain. No copyright is claimed.
#include "Ethernet.h"

View File

@@ -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 <Arduino.h>
#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;
}

View File

@@ -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"

View File

@@ -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 <Arduino.h>
#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;
}

View File

@@ -1,481 +0,0 @@
/*
* Copyright 2018 Paul Stoffregen
* Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
*
* 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 <Arduino.h>
#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<MAX_SOCK_NUM; i++) {
writeSnRX_SIZE(i, SSIZE >> 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<MAX_SOCK_NUM; i++) {
writeSnRX_SIZE(i, SSIZE >> 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<len; i++) {
setSS();
SPI.transfer(0xF0);
SPI.transfer(addr >> 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)) ;
}

View File

@@ -1,487 +0,0 @@
/*
* Copyright 2018 Paul Stoffregen
* Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
*
* 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 <Arduino.h>
#include <SPI.h>
// 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

View File

@@ -1,79 +0,0 @@
/**
* Authorization.ino
*
* Created on: 09.12.2015
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#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);
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -1,100 +0,0 @@
/**
* BasicHTTPClient.ino
*
* Created on: 24.05.2015
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#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);
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -1,132 +0,0 @@
/**
BasicHTTPSClient.ino
Created on: 14.10.2018
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <NetworkClientSecure.h>
// 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);
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -1,107 +0,0 @@
/*|----------------------------------------------------------|*/
/*|WORKING EXAMPLE FOR HTTP/HTTPS CONNECTION |*/
/*|TESTED BOARDS: Devkit v1 DOIT, Devkitc v4 |*/
/*|CORE: June 2018 |*/
/*|----------------------------------------------------------|*/
#include <WiFi.h>
#include <HTTPClient.h>
#if __has_include("esp_eap_client.h")
#include "esp_eap_client.h"
#else
#include "esp_wpa2.h"
#endif
#include <Wire.h>
#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);
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -1,64 +0,0 @@
/**
* reuseConnection.ino
*
* Created on: 22.11.2015
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#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);
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -1,97 +0,0 @@
/**
* StreamHTTPClient.ino
*
* Created on: 24.05.2015
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#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);
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -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

File diff suppressed because it is too large Load Diff

View File

@@ -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 <memory>
#include <Arduino.h>
#include <NetworkClient.h>
#ifndef HTTPCLIENT_NOSECURE
#include <NetworkClientSecure.h>
#endif // HTTPCLIENT_NOSECURE
/// Cookie jar support
#include <vector>
#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<TransportTraits> 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<Cookie> 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<NetworkClient> _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_ */

View File

@@ -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).

View File

@@ -1,70 +0,0 @@
#include <NetworkClientSecure.h>
#include <WiFi.h>
/* 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
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

View File

@@ -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 <NetworkClientSecure.h>
#include <WiFi.h>
#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
}

View File

@@ -1,5 +0,0 @@
{
"targets": {
"esp32h2": false
}
}

Some files were not shown because too many files have changed in this diff Show More