From 6b0100fd61c5982e35aeb4c23b9f17362bd03365 Mon Sep 17 00:00:00 2001 From: iranl Date: Fri, 5 Jul 2024 18:45:39 +0200 Subject: [PATCH] Arduino Core 3 (#407) * Add and remove libs and components for Arduino Core 3 * Arduino Core 3 * Add back Solo1 * Change ESP32-S3 to 4MB build * Update README.md * Fix retain and number of retries * Fix rolling log * Fix defaults * Fix BleScanner on Solo1 * Export settings * Import settings * Fix HA Battery voltage * Change submodule * Update espMqttClient and AsyncTCP * Webserial and MQTT/Network reconnecting * Update nuki_ble --------- Co-authored-by: iranl --- .github/workflows/build.yml | 12 +- .github/workflows/stale-actions.yml | 4 +- .gitignore | 11 +- .gitmodules | 2 +- CMakeLists.txt | 150 +- Docker/Dockerfile_cmake | 45 - Docker/README.md | 11 +- Docker/build_with_docker_cmake.sh | 6 - Makefile | 14 +- README.md | 123 +- lib/AsyncTCP-esphome/.github/stale.yml | 31 - .../.github/workflows/push.yml | 29 - lib/AsyncTCP-esphome/.gitignore | 2 - lib/AsyncTCP-esphome/.piopm | 1 - lib/AsyncTCP-esphome/.travis.yml | 34 - lib/AsyncTCP-esphome/CMakeLists.txt | 15 - lib/AsyncTCP-esphome/Kconfig.projbuild | 30 - lib/AsyncTCP-esphome/README.md | 12 - lib/AsyncTCP-esphome/component.mk | 3 - lib/AsyncTCP-esphome/library.json | 23 - lib/AsyncTCP-esphome/src/AsyncTCP.cpp | 1464 -------------- lib/AsyncTCP-esphome/src/AsyncTCP.h | 247 --- .../.github/ISSUE_TEMPLATE/bug_report.md | 35 + .../.github/ISSUE_TEMPLATE/question.md | 10 + .../.github/dependabot.yml | 0 .../scripts/install-arduino-core-esp32.sh | 36 - .../.github/scripts/install-arduino-ide.sh | 220 --- .../.github/scripts/install-platformio.sh | 133 -- lib/AsyncTCP/.github/scripts/on-push.sh | 64 - lib/AsyncTCP/.github/workflows/push.yml | 52 +- lib/AsyncTCP/.gitignore | 6 +- lib/AsyncTCP/.travis.yml | 34 - lib/AsyncTCP/README.md | 49 +- lib/AsyncTCP/arduino-cli-dev.yaml | 25 + .../arduino-cli.yaml | 0 .../examples/ClientServer/Client/Client.ino | 0 .../examples/ClientServer/Client/config.h | 0 lib/AsyncTCP/library.json | 46 +- lib/AsyncTCP/library.properties | 8 +- lib/AsyncTCP/platformio.ini | 28 + lib/AsyncTCP/src/AsyncTCP.cpp | 321 ++- lib/AsyncTCP/src/AsyncTCP.h | 86 +- lib/AsyncTCP/src/IPv6Address.cpp | 90 - lib/AsyncTCP/src/IPv6Address.h | 94 - lib/BleScanner/src/BleScanner.cpp | 13 +- lib/Crc16/Crc16.h | 243 --- lib/ESP Async WebServer/.piopm | 1 + .../LICENSE | 4 +- lib/ESP Async WebServer/README.md | 117 ++ .../examples/CaptivePortal/CaptivePortal.ino | 57 + .../examples/Draft/Draft.ino | 37 + .../examples/Filters/Filters.ino | 111 ++ .../examples/SimpleServer/SimpleServer.ino | 77 + .../examples/StreamFiles/StreamConcat.h | 37 + .../examples/StreamFiles/StreamFiles.ino | 84 + .../examples/StreamFiles/StreamString.h | 40 + lib/ESP Async WebServer/library.json | 64 + lib/ESP Async WebServer/library.properties | 10 + .../src/AsyncEventSource.cpp | 402 ++++ .../src/AsyncEventSource.h | 158 ++ lib/ESP Async WebServer/src/AsyncJson.h | 281 +++ .../src/AsyncWebSocket.cpp | 1197 ++++++++++++ lib/ESP Async WebServer/src/AsyncWebSocket.h | 390 ++++ .../src/ESPAsyncWebServer.h | 652 +++++++ .../src/ESP_Async_WebServer.h | 2 + .../src/WebAuthentication.cpp | 245 +++ .../src/WebAuthentication.h | 39 + lib/ESP Async WebServer/src/WebHandlerImpl.h | 155 ++ lib/ESP Async WebServer/src/WebHandlers.cpp | 247 +++ lib/ESP Async WebServer/src/WebRequest.cpp | 1028 ++++++++++ lib/ESP Async WebServer/src/WebResponseImpl.h | 148 ++ lib/ESP Async WebServer/src/WebResponses.cpp | 751 +++++++ lib/ESP Async WebServer/src/WebServer.cpp | 217 +++ .../src/port/SHA1Builder.cpp | 284 +++ .../src/port/SHA1Builder.h | 39 + .../scripts/install-arduino-core-esp8266.sh | 29 - .../.github/scripts/install-arduino-ide.sh | 220 --- .../.github/scripts/install-platformio.sh | 133 -- .../.github/scripts/on-push.sh | 64 - lib/ESPAsyncTCP-esphome/.github/stale.yml | 31 - .../.github/workflows/push.yml | 32 - lib/ESPAsyncTCP-esphome/.gitignore | 2 - lib/ESPAsyncTCP-esphome/.piopm | 1 - lib/ESPAsyncTCP-esphome/LICENSE.txt | 165 -- lib/ESPAsyncTCP-esphome/README.md | 33 - .../examples/ClientServer/Client/Client.ino | 62 - .../examples/ClientServer/Client/config.h | 23 - .../examples/ClientServer/Server/Server.ino | 73 - .../examples/ClientServer/Server/config.h | 23 - .../examples/SyncClient/.esp31b.skip | 0 .../examples/SyncClient/SyncClient.ino | 54 - lib/ESPAsyncTCP-esphome/library.json | 22 - lib/ESPAsyncTCP-esphome/src/AsyncPrinter.cpp | 214 -- lib/ESPAsyncTCP-esphome/src/AsyncPrinter.h | 73 - .../src/DebugPrintMacros.h | 112 -- lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.cpp | 1406 -------------- lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.h | 324 ---- .../src/ESPAsyncTCPbuffer.cpp | 555 ------ .../src/ESPAsyncTCPbuffer.h | 118 -- lib/ESPAsyncTCP-esphome/src/SyncClient.cpp | 414 ---- lib/ESPAsyncTCP-esphome/src/SyncClient.h | 109 -- lib/ESPAsyncTCP-esphome/src/async_config.h | 42 - lib/ESPAsyncTCP-esphome/src/tcp_axtls.c | 613 ------ lib/ESPAsyncTCP-esphome/src/tcp_axtls.h | 98 - .../ssl/gen_server_cert.sh | 36 - lib/ESPAsyncTCP-esphome/ssl/server.cer | Bin 587 -> 0 bytes lib/ESPAsyncTCP-esphome/ssl/server.key | Bin 611 -> 0 bytes .../examples/Authorization/Authorization.ino | 79 + lib/HTTPClient/examples/Authorization/ci.json | 5 + .../BasicHttpClient/BasicHttpClient.ino | 100 + .../examples/BasicHttpClient/ci.json | 5 + .../BasicHttpsClient/BasicHttpsClient.ino | 145 ++ .../examples/BasicHttpsClient/ci.json | 5 + .../HTTPClientEnterprise.ino | 107 + .../examples/HTTPClientEnterprise/ci.json | 5 + .../ReuseConnection/ReuseConnection.ino | 64 + .../examples/ReuseConnection/ci.json | 5 + .../StreamHttpClient/StreamHttpClient.ino | 97 + .../examples/StreamHttpClient/ci.json | 5 + lib/HTTPClient/library.properties | 9 + lib/HTTPClient/src/HTTPClient.cpp | 1720 +++++++++++++++++ lib/HTTPClient/src/HTTPClient.h | 315 +++ lib/WebSerialLite/.clang-format | 21 + lib/WebSerialLite/.github/FUNDING.yml | 13 + lib/WebSerialLite/.github/dependabot.yml | 10 + lib/WebSerialLite/.github/workflows/ci.yml | 129 ++ .../.github/workflows/dependabot.yml | 19 + .../.github/workflows/stale.yaml | 24 + lib/WebSerialLite/.gitignore | 7 + lib/WebSerialLite/LICENSE | 674 +++++++ lib/WebSerialLite/README.md | 67 + lib/WebSerialLite/docs/_config.yml | 8 + lib/WebSerialLite/docs/index.md | 67 + lib/WebSerialLite/examples/Demo/Demo.ino | 87 + .../examples/Demo_AP/Demo_AP.ino | 80 + .../examples/HighPerf/HighPerf.ino | 69 + .../examples/Logging/Logging.ino | 55 + lib/WebSerialLite/frontend/README.md | 19 + lib/WebSerialLite/frontend/finalize.js | 66 + lib/WebSerialLite/frontend/index.html | 364 ++++ lib/WebSerialLite/frontend/package-lock.json | 240 +++ lib/WebSerialLite/frontend/package.json | 9 + lib/WebSerialLite/frontend/pnpm-lock.yaml | 177 ++ lib/WebSerialLite/library.json | 44 + lib/WebSerialLite/library.properties | 10 + lib/WebSerialLite/platformio.ini | 42 + lib/WebSerialLite/src/WebSerial.cpp | 150 ++ lib/WebSerialLite/src/WebSerial.h | 68 + lib/WebSerialLite/src/WebSerialLite.h | 1 + lib/WebSerialLite/src/WebSerialWebPage.h | 96 + lib/WebServer/src/WebServer.cpp | 6 + lib/WebServer/src/WebServer.h | 4 +- lib/WebServer/src/hardware/WifiEthClient.cpp | 3 +- lib/WebServer/src/hardware/WifiEthServer.cpp | 2 +- .../.github/ISSUE_TEMPLATE/bug_report.md | 34 + lib/espMqttClient/.github/etc/mosquitto.conf | 2 + .../.github/workflows/arduino-lint.yml | 9 + .../.github/workflows/build_arduino-ide.yml | 62 + .../.github/workflows/build_platformio.yml | 90 + .../.github/workflows/cppcheck.yml | 22 + .../.github/workflows/cpplint.yml | 22 + .../.github/workflows/test_platformio.yml | 29 + lib/espMqttClient/.gitignore | 5 + lib/espMqttClient/README.md | 8 +- lib/espMqttClient/docs/index.md | 26 +- .../examples/notask-esp32/notask-esp32.ino | 6 +- .../examples/simple-esp32-idf/main/main.cpp | 6 +- .../examples/simple-esp32/simple-esp32.ino | 6 +- .../simpleAsync-esp32/simpleAsync-esp32.ino | 6 +- .../examples/tls-esp32/tls-esp32.ino | 6 +- lib/espMqttClient/library.json | 16 +- lib/espMqttClient/library.properties | 2 +- lib/espMqttClient/platformio.ini | 1 + lib/espMqttClient/src/Config.h | 13 + lib/espMqttClient/src/MemoryPool/LICENSE | 21 + lib/espMqttClient/src/MemoryPool/README.md | 105 + lib/espMqttClient/src/MemoryPool/keywords.txt | 16 + lib/espMqttClient/src/MemoryPool/library.json | 21 + .../src/MemoryPool/library.properties | 10 + lib/espMqttClient/src/MemoryPool/src/Fixed.h | 119 ++ .../src/MemoryPool/src/MemoryPool.h | 12 + .../src/MemoryPool/src/Variable.h | 242 +++ lib/espMqttClient/src/MqttClient.cpp | 97 +- lib/espMqttClient/src/MqttClient.h | 10 +- lib/espMqttClient/src/Outbox.h | 48 +- lib/espMqttClient/src/Packets/Packet.cpp | 28 +- lib/espMqttClient/src/Packets/Packet.h | 10 +- .../test/test_outbox/test_outbox.cpp | 20 +- lib/gpio2go/src/Gpio2Go.cpp | 2 +- lib/nuki_ble | 2 +- partitions.csv | 2 +- pio_package.py | 20 +- platformio.ini | 68 +- {bin => resources}/boot_app0.bin | Bin .../how-to-flash.txt | 29 +- resources/style.css | 2 +- sdkconfig.defaults | 67 + src/CMakeLists.txt | 6 + src/Config.h | 27 +- src/Gpio.cpp | 2 +- src/Logger.h | 6 + src/MqttTopics.h | 3 +- src/NukiDeviceId.cpp | 1 + src/{Network.cpp => NukiNetwork.cpp} | 325 ++-- src/{Network.h => NukiNetwork.h} | 86 +- src/{NetworkLock.cpp => NukiNetworkLock.cpp} | 302 +-- src/{NetworkLock.h => NukiNetworkLock.h} | 10 +- ...etworkOpener.cpp => NukiNetworkOpener.cpp} | 258 +-- src/{NetworkOpener.h => NukiNetworkOpener.h} | 10 +- src/NukiOpenerWrapper.cpp | 260 +-- src/NukiOpenerWrapper.h | 7 +- src/NukiWrapper.cpp | 399 ++-- src/NukiWrapper.h | 7 +- src/PreferencesKeys.h | 90 +- src/PresenceDetection.cpp | 20 +- src/RestartReason.h | 10 +- src/WebCfgServer.cpp | 1148 ++++++++--- src/WebCfgServer.h | 58 +- src/WebCfgServerConstants.h | 2 +- src/main.cpp | 278 ++- src/networkDevices/EthLan8720Device.cpp | 32 +- src/networkDevices/EthLan8720Device.h | 33 +- src/networkDevices/NetworkDevice.cpp | 20 +- src/networkDevices/NetworkDevice.h | 13 +- src/networkDevices/W5500Device.cpp | 7 +- src/networkDevices/W5500Device.h | 2 + src/networkDevices/WifiDevice.cpp | 51 +- src/networkDevices/WifiDevice.h | 11 + updater/CMakeLists.txt | 4 + updater/partitions.csv | 1 + updater/pio_package.py | 44 + updater/pio_package_pre.py | 3 + updater/pio_package_pre_solo1.py | 32 + updater/platformio.ini | 85 + updater/sdkconfig.defaults | 13 + updater/src/CMakeLists.txt | 28 + 236 files changed, 16390 insertions(+), 9740 deletions(-) delete mode 100644 Docker/Dockerfile_cmake delete mode 100755 Docker/build_with_docker_cmake.sh delete mode 100644 lib/AsyncTCP-esphome/.github/stale.yml delete mode 100644 lib/AsyncTCP-esphome/.github/workflows/push.yml delete mode 100644 lib/AsyncTCP-esphome/.gitignore delete mode 100644 lib/AsyncTCP-esphome/.piopm delete mode 100644 lib/AsyncTCP-esphome/.travis.yml delete mode 100644 lib/AsyncTCP-esphome/CMakeLists.txt delete mode 100644 lib/AsyncTCP-esphome/Kconfig.projbuild delete mode 100644 lib/AsyncTCP-esphome/README.md delete mode 100644 lib/AsyncTCP-esphome/component.mk delete mode 100644 lib/AsyncTCP-esphome/library.json delete mode 100644 lib/AsyncTCP-esphome/src/AsyncTCP.cpp delete mode 100644 lib/AsyncTCP-esphome/src/AsyncTCP.h create mode 100644 lib/AsyncTCP/.github/ISSUE_TEMPLATE/bug_report.md create mode 100644 lib/AsyncTCP/.github/ISSUE_TEMPLATE/question.md rename lib/{AsyncTCP-esphome => AsyncTCP}/.github/dependabot.yml (100%) delete mode 100755 lib/AsyncTCP/.github/scripts/install-arduino-core-esp32.sh delete mode 100755 lib/AsyncTCP/.github/scripts/install-arduino-ide.sh delete mode 100644 lib/AsyncTCP/.github/scripts/install-platformio.sh delete mode 100755 lib/AsyncTCP/.github/scripts/on-push.sh delete mode 100644 lib/AsyncTCP/.travis.yml create mode 100644 lib/AsyncTCP/arduino-cli-dev.yaml rename lib/{AsyncTCP-esphome => AsyncTCP}/arduino-cli.yaml (100%) rename lib/{AsyncTCP-esphome => AsyncTCP}/examples/ClientServer/Client/Client.ino (100%) rename lib/{AsyncTCP-esphome => AsyncTCP}/examples/ClientServer/Client/config.h (100%) create mode 100644 lib/AsyncTCP/platformio.ini delete mode 100644 lib/AsyncTCP/src/IPv6Address.cpp delete mode 100644 lib/AsyncTCP/src/IPv6Address.h delete mode 100644 lib/Crc16/Crc16.h create mode 100644 lib/ESP Async WebServer/.piopm rename lib/{AsyncTCP-esphome => ESP Async WebServer}/LICENSE (98%) create mode 100644 lib/ESP Async WebServer/README.md create mode 100644 lib/ESP Async WebServer/examples/CaptivePortal/CaptivePortal.ino create mode 100644 lib/ESP Async WebServer/examples/Draft/Draft.ino create mode 100644 lib/ESP Async WebServer/examples/Filters/Filters.ino create mode 100644 lib/ESP Async WebServer/examples/SimpleServer/SimpleServer.ino create mode 100644 lib/ESP Async WebServer/examples/StreamFiles/StreamConcat.h create mode 100644 lib/ESP Async WebServer/examples/StreamFiles/StreamFiles.ino create mode 100644 lib/ESP Async WebServer/examples/StreamFiles/StreamString.h create mode 100644 lib/ESP Async WebServer/library.json create mode 100644 lib/ESP Async WebServer/library.properties create mode 100644 lib/ESP Async WebServer/src/AsyncEventSource.cpp create mode 100644 lib/ESP Async WebServer/src/AsyncEventSource.h create mode 100644 lib/ESP Async WebServer/src/AsyncJson.h create mode 100644 lib/ESP Async WebServer/src/AsyncWebSocket.cpp create mode 100644 lib/ESP Async WebServer/src/AsyncWebSocket.h create mode 100644 lib/ESP Async WebServer/src/ESPAsyncWebServer.h create mode 100644 lib/ESP Async WebServer/src/ESP_Async_WebServer.h create mode 100644 lib/ESP Async WebServer/src/WebAuthentication.cpp create mode 100644 lib/ESP Async WebServer/src/WebAuthentication.h create mode 100644 lib/ESP Async WebServer/src/WebHandlerImpl.h create mode 100644 lib/ESP Async WebServer/src/WebHandlers.cpp create mode 100644 lib/ESP Async WebServer/src/WebRequest.cpp create mode 100644 lib/ESP Async WebServer/src/WebResponseImpl.h create mode 100644 lib/ESP Async WebServer/src/WebResponses.cpp create mode 100644 lib/ESP Async WebServer/src/WebServer.cpp create mode 100644 lib/ESP Async WebServer/src/port/SHA1Builder.cpp create mode 100644 lib/ESP Async WebServer/src/port/SHA1Builder.h delete mode 100644 lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-core-esp8266.sh delete mode 100644 lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-ide.sh delete mode 100644 lib/ESPAsyncTCP-esphome/.github/scripts/install-platformio.sh delete mode 100644 lib/ESPAsyncTCP-esphome/.github/scripts/on-push.sh delete mode 100644 lib/ESPAsyncTCP-esphome/.github/stale.yml delete mode 100644 lib/ESPAsyncTCP-esphome/.github/workflows/push.yml delete mode 100644 lib/ESPAsyncTCP-esphome/.gitignore delete mode 100644 lib/ESPAsyncTCP-esphome/.piopm delete mode 100644 lib/ESPAsyncTCP-esphome/LICENSE.txt delete mode 100644 lib/ESPAsyncTCP-esphome/README.md delete mode 100644 lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/Client.ino delete mode 100644 lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/config.h delete mode 100644 lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/Server.ino delete mode 100644 lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/config.h delete mode 100644 lib/ESPAsyncTCP-esphome/examples/SyncClient/.esp31b.skip delete mode 100644 lib/ESPAsyncTCP-esphome/examples/SyncClient/SyncClient.ino delete mode 100644 lib/ESPAsyncTCP-esphome/library.json delete mode 100644 lib/ESPAsyncTCP-esphome/src/AsyncPrinter.cpp delete mode 100644 lib/ESPAsyncTCP-esphome/src/AsyncPrinter.h delete mode 100644 lib/ESPAsyncTCP-esphome/src/DebugPrintMacros.h delete mode 100644 lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.cpp delete mode 100644 lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.h delete mode 100644 lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.cpp delete mode 100644 lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.h delete mode 100644 lib/ESPAsyncTCP-esphome/src/SyncClient.cpp delete mode 100644 lib/ESPAsyncTCP-esphome/src/SyncClient.h delete mode 100644 lib/ESPAsyncTCP-esphome/src/async_config.h delete mode 100644 lib/ESPAsyncTCP-esphome/src/tcp_axtls.c delete mode 100644 lib/ESPAsyncTCP-esphome/src/tcp_axtls.h delete mode 100644 lib/ESPAsyncTCP-esphome/ssl/gen_server_cert.sh delete mode 100644 lib/ESPAsyncTCP-esphome/ssl/server.cer delete mode 100644 lib/ESPAsyncTCP-esphome/ssl/server.key create mode 100644 lib/HTTPClient/examples/Authorization/Authorization.ino create mode 100644 lib/HTTPClient/examples/Authorization/ci.json create mode 100644 lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino create mode 100644 lib/HTTPClient/examples/BasicHttpClient/ci.json create mode 100644 lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino create mode 100644 lib/HTTPClient/examples/BasicHttpsClient/ci.json create mode 100644 lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino create mode 100644 lib/HTTPClient/examples/HTTPClientEnterprise/ci.json create mode 100644 lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino create mode 100644 lib/HTTPClient/examples/ReuseConnection/ci.json create mode 100644 lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino create mode 100644 lib/HTTPClient/examples/StreamHttpClient/ci.json create mode 100644 lib/HTTPClient/library.properties create mode 100644 lib/HTTPClient/src/HTTPClient.cpp create mode 100644 lib/HTTPClient/src/HTTPClient.h create mode 100644 lib/WebSerialLite/.clang-format create mode 100644 lib/WebSerialLite/.github/FUNDING.yml create mode 100644 lib/WebSerialLite/.github/dependabot.yml create mode 100644 lib/WebSerialLite/.github/workflows/ci.yml create mode 100644 lib/WebSerialLite/.github/workflows/dependabot.yml create mode 100644 lib/WebSerialLite/.github/workflows/stale.yaml create mode 100644 lib/WebSerialLite/.gitignore create mode 100644 lib/WebSerialLite/LICENSE create mode 100644 lib/WebSerialLite/README.md create mode 100644 lib/WebSerialLite/docs/_config.yml create mode 100644 lib/WebSerialLite/docs/index.md create mode 100644 lib/WebSerialLite/examples/Demo/Demo.ino create mode 100644 lib/WebSerialLite/examples/Demo_AP/Demo_AP.ino create mode 100644 lib/WebSerialLite/examples/HighPerf/HighPerf.ino create mode 100644 lib/WebSerialLite/examples/Logging/Logging.ino create mode 100644 lib/WebSerialLite/frontend/README.md create mode 100644 lib/WebSerialLite/frontend/finalize.js create mode 100644 lib/WebSerialLite/frontend/index.html create mode 100644 lib/WebSerialLite/frontend/package-lock.json create mode 100644 lib/WebSerialLite/frontend/package.json create mode 100644 lib/WebSerialLite/frontend/pnpm-lock.yaml create mode 100644 lib/WebSerialLite/library.json create mode 100644 lib/WebSerialLite/library.properties create mode 100644 lib/WebSerialLite/platformio.ini create mode 100644 lib/WebSerialLite/src/WebSerial.cpp create mode 100644 lib/WebSerialLite/src/WebSerial.h create mode 100644 lib/WebSerialLite/src/WebSerialLite.h create mode 100644 lib/WebSerialLite/src/WebSerialWebPage.h create mode 100644 lib/espMqttClient/.github/ISSUE_TEMPLATE/bug_report.md create mode 100644 lib/espMqttClient/.github/etc/mosquitto.conf create mode 100644 lib/espMqttClient/.github/workflows/arduino-lint.yml create mode 100644 lib/espMqttClient/.github/workflows/build_arduino-ide.yml create mode 100644 lib/espMqttClient/.github/workflows/build_platformio.yml create mode 100644 lib/espMqttClient/.github/workflows/cppcheck.yml create mode 100644 lib/espMqttClient/.github/workflows/cpplint.yml create mode 100644 lib/espMqttClient/.github/workflows/test_platformio.yml create mode 100644 lib/espMqttClient/.gitignore create mode 100644 lib/espMqttClient/src/MemoryPool/LICENSE create mode 100644 lib/espMqttClient/src/MemoryPool/README.md create mode 100644 lib/espMqttClient/src/MemoryPool/keywords.txt create mode 100644 lib/espMqttClient/src/MemoryPool/library.json create mode 100644 lib/espMqttClient/src/MemoryPool/library.properties create mode 100644 lib/espMqttClient/src/MemoryPool/src/Fixed.h create mode 100644 lib/espMqttClient/src/MemoryPool/src/MemoryPool.h create mode 100644 lib/espMqttClient/src/MemoryPool/src/Variable.h rename {bin => resources}/boot_app0.bin (100%) rename how-to-flash.txt => resources/how-to-flash.txt (67%) create mode 100644 sdkconfig.defaults create mode 100644 src/CMakeLists.txt rename src/{Network.cpp => NukiNetwork.cpp} (94%) rename src/{Network.h => NukiNetwork.h} (95%) rename src/{NetworkLock.cpp => NukiNetworkLock.cpp} (84%) rename src/{NetworkLock.h => NukiNetworkLock.h} (96%) rename src/{NetworkOpener.cpp => NukiNetworkOpener.cpp} (85%) rename src/{NetworkOpener.h => NukiNetworkOpener.h} (95%) create mode 100644 updater/CMakeLists.txt create mode 100644 updater/partitions.csv create mode 100644 updater/pio_package.py create mode 100644 updater/pio_package_pre.py create mode 100644 updater/pio_package_pre_solo1.py create mode 100644 updater/platformio.ini create mode 100644 updater/sdkconfig.defaults create mode 100644 updater/src/CMakeLists.txt diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e3370a4..dfc22b6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,7 +19,7 @@ jobs: strategy: fail-fast: false matrix: - board: [esp32dev, esp32-s3, esp32-c3, esp32solo1] + board: [esp32dev, esp32-s3, esp32-c3, esp32-c6, esp32solo1] build: [release, debug] env: BOARD: ${{ matrix.board }} @@ -62,20 +62,20 @@ jobs: BOARD="${BOARD}_dbg" fi echo "::group::Building with PlatformIO" + if [ "$BUILD" = "release" ]; then + make updater_${BOARD} + fi make $BOARD echo "::endgroup::" - - name: Add flash script env: - DOC: how-to-flash.txt + DOC: resources/how-to-flash.txt FILES: ${{ format('{0}/{1}', env.BUILD, env.VARIANT) }} run: | BOARD=`echo $BOARD | tr '[:lower:]' '[:upper:]'` # fix for docs - if [ "$BOARD" = "ESP32SOLO1" ]; then - BOARD="ESP32Solo1" - elif [ "$BOARD" = "ESP32DEV" ]; then + if [ "$BOARD" = "ESP32DEV" ]; then BOARD="ESP32" fi diff --git a/.github/workflows/stale-actions.yml b/.github/workflows/stale-actions.yml index d6678d3..9d75f58 100644 --- a/.github/workflows/stale-actions.yml +++ b/.github/workflows/stale-actions.yml @@ -1,12 +1,12 @@ name: "Mark or close stale issues and PRs" on: schedule: - - cron: "30 * * * *" + - cron: "30 7 * * *" jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v6.0.1 + - uses: actions/stale@v9.0.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: 45 diff --git a/.gitignore b/.gitignore index 71bb2f3..da7d082 100644 --- a/.gitignore +++ b/.gitignore @@ -11,8 +11,15 @@ webflash/*.bin .pio .vscode .project - +managed_components +dependencies.lock +sdkconfig.esp32* +sdkconfig.updater_esp32* +updater/src/*.cpp +updater/src/*.h +updater/src/networkDevices/*.cpp +updater/src/networkDevices/*.h # Python venv /pyvenv.cfg /lib64 -/lib/python3* +/lib/python3* \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 7a73dd3..789cb4f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "lib/nuki_ble"] path = lib/nuki_ble - url = https://github.com/technyon/nuki_ble.git + url = https://github.com/I-Connect/NukiBleEsp32 diff --git a/CMakeLists.txt b/CMakeLists.txt index e33d3ad..39f885c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,147 +1,3 @@ -cmake_minimum_required(VERSION 3.0.0) - -if(NOT ARDUINO_BOARD) - set(ARDUINO_BOARD "ESP32 Dev Module [esp32.esp32]") -endif() - -project(nuki_hub CXX) - -# ARDUHAL_LOG_LEVEL_NONE, define ARDUHAL_LOG_LEVEL_ERROR, define ARDUHAL_LOG_LEVEL_WARN, define ARDUHAL_LOG_LEVEL_INFO, -# define ARDUHAL_LOG_LEVEL_DEBUG, define ARDUHAL_LOG_LEVEL_VERBOSE - -set(LOG_LEVEL ARDUHAL_LOG_LEVEL_NONE) - -#add_compile_definitions(DEBUG_SENSE_NUKI) -#add_compile_definitions(DEBUG_NUKI_COMMAND) -#add_compile_definitions(DEBUG_NUKI_CONNECT) -#add_compile_definitions(DEBUG_NUKI_COMMUNICATION) -#add_compile_definitions(DEBUG_NUKI_HEX_DATA) -#add_compile_definitions(DEBUG_NUKI_READABLE_DATA) - -# Length of char arrays to store certificates for MQTTS -add_compile_definitions(TLS_CA_MAX_SIZE=2200) -add_compile_definitions(TLS_CERT_MAX_SIZE=1500) -add_compile_definitions(TLS_KEY_MAX_SIZE=1800) -add_compile_definitions(ESP_PLATFORM) -add_compile_definitions(ESP32) -add_compile_definitions(ARDUINO_ARCH_ESP32) -# add_compile_definitions(CONFIG_BT_NIMBLE_PINNED_TO_CORE=1) - -include_directories(${PROJECT_NAME} - PRIVATE - lib/Crc16 - resources/NimBLE-Arduino/src - lib/BleScanner/src - lib/nuki_ble/src - lib/WiFiManager - lib/WebServer/src - lib/Ethernet/src - lib/MqttLogger/src - lib/espMqttClient/src - lib/AsyncTCP/src - lib/ArduinoJson/src -) - -set(SRCFILES - src/Config.h - src/NukiDeviceId.cpp - src/CharBuffer.cpp - src/Network.cpp - src/MqttReceiver.h - src/NetworkLock.cpp - src/NetworkOpener.cpp - src/networkDevices/NetworkDevice.h - src/networkDevices/NetworkDevice.cpp - src/networkDevices/WifiDevice.cpp - src/networkDevices/W5500Device.cpp - src/networkDevices/EthLan8720Device.cpp - src/networkDevices/ClientSyncW5500.cpp - src/networkDevices/espMqttClientW5500.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 - src/PreferencesKeys.h - src/Gpio.cpp - src/Logger.cpp - src/RestartReason.h -# include/RTOS.h - lib/WiFiManager/WiFiManager.cpp - lib/WiFiManager/wm_consts_en.h - lib/WiFiManager/wm_strings_en.h - lib/Crc16/Crc16.h - lib/nuki_ble/src/NukiBle.cpp - lib/nuki_ble/src/NukiBle.hpp - lib/nuki_ble/src/NukiLock.cpp - lib/nuki_ble/src/NukiOpener.cpp - lib/nuki_ble/src/NukiConstants.h - lib/nuki_ble/src/NukiOpenerConstants.h - lib/nuki_ble/src/NukiLockConstants.h - lib/nuki_ble/src/NukiDataTypes.h - lib/nuki_ble/src/NukiUtils.cpp - lib/nuki_ble/src/NukiLockUtils.cpp - lib/nuki_ble/src/NukiOpenerUtils.cpp - lib/gpio2go/src/Gpio2Go.cpp - lib/gpio2go/src/InterruptMode.h - lib/gpio2go/src/PinMode.h - lib/BleScanner/src/BleInterfaces.h - lib/BleScanner/src/BleScanner.cpp - lib/MqttLogger/src/MqttLogger.cpp - lib/AsyncTCP/src/AsyncTCP.cpp - ) - -file(GLOB_RECURSE SRCFILESREC - resources/NimBLE-Arduino/src/*.c - resources/NimBLE-Arduino/src/*.cpp - resources/NimBLE-Arduino/src/*.h - lib/WebServer/src/*.cpp - lib/WebServer/src/*.h - lib/Ethernet/src/*.cpp - lib/Ethernet/src/*.h - lib/espMqttClient/src/*.cpp - lib/espMqttClient/src/*.h - lib/espMqttClient/src/Packets/*.cpp - lib/espMqttClient/src/Packets/*.h - lib/espMqttClient/src/Transport/*.cpp - lib/espMqttClient/src/Transport/*.h - lib/ArduinoJson/src/*.h - lib/ArduinoJson/src/*.hpp -) - -add_executable(${PROJECT_NAME} - src/main.cpp - ${SRCFILES} - ${SRCFILESREC} - ) - -target_compile_definitions(${PROJECT_NAME} - PRIVATE - ARDUHAL_LOG_LEVEL=${LOG_LEVEL} - CORE_DEBUG_LEVEL=${LOG_LEVEL} - CONFIG_NIMBLE_CPP_LOG_LEVEL=0 - ) - -target_link_arduino_libraries(${PROJECT_NAME} - PRIVATE - core - BLE - WiFi - WiFiClientSecure - Update - DNSServer - Preferences - Ethernet - SPI -) - -target_link_arduino_libraries(DNSServer PUBLIC WiFi) - -# This is needed for the generation of HEX binary and uploading it -target_enable_arduino_upload(${PROJECT_NAME}) - +cmake_minimum_required(VERSION 3.16.0) +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(nukihub) \ No newline at end of file diff --git a/Docker/Dockerfile_cmake b/Docker/Dockerfile_cmake deleted file mode 100644 index bb6d25d..0000000 --- a/Docker/Dockerfile_cmake +++ /dev/null @@ -1,45 +0,0 @@ -FROM eclipse-temurin:11-jdk-jammy AS builder - -RUN set -ex && \ - apt-get update && \ - apt-get install -y git cmake xz-utils python3 python3-serial ninja-build - -RUN curl -L "https://downloads.arduino.cc/arduino-1.8.19-linux64.tar.xz" -o /tmp/arduino-ide.tar.xz -RUN tar -xf /tmp/arduino-ide.tar.xz --directory ~/ - -RUN cd ~/arduino* && \ - ./install.sh && \ - ./arduino --pref "boardsmanager.additional.urls=https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json" --save-prefs && \ - ./arduino --install-boards esp32:esp32:2.0.17 - -RUN git clone --recurse-submodules https://github.com/technyon/Arduino-CMake-Toolchain.git ~/Arduino-CMake-Toolchain - -COPY src /usr/src/nuki_hub/src -COPY lib /usr/src/nuki_hub/lib -COPY include /usr/src/nuki_hub/include -COPY CMakeLists.txt /usr/src/nuki_hub - -RUN mkdir -p /usr/src/nuki_hub/build - -RUN cd /usr/src/nuki_hub/build && \ - echo "# Espressif ESP32 Partition Table" > partitions.csv && \ - echo "# Name, Type, SubType, Offset, Size, Flags" >> partitions.csv && \ - echo "nvs, data, nvs, 0x9000, 0x5000," >> partitions.csv && \ - echo "otadata, data, ota, 0xe000, 0x2000," >> partitions.csv && \ - echo "app0, app, ota_0, 0x10000, 0x1E0000," >> partitions.csv && \ - echo "app1, app, ota_1, 0x1F0000,0x1E0000," >> partitions.csv && \ - echo "spiffs, data, spiffs, 0x3D0000,0x30000," >> partitions.csv - -RUN set -ex && \ - cd /usr/src/nuki_hub/build && \ - touch file_opts && \ - cmake -G Ninja -D CMAKE_TOOLCHAIN_FILE=~/Arduino-CMake-Toolchain/Arduino-toolchain.cmake .. && \ - ninja - -FROM builder AS runtime - -COPY --from=builder /usr/src/nuki_hub/build/nuki_hub.bin /usr/src/nuki_hub/build/release/nuki_hub.bin -COPY --from=builder /usr/src/nuki_hub/build/nuki_hub.partitions.bin /usr/src/nuki_hub/build/release/nuki_hub.partitions.bin -COPY --from=builder /root/.arduino15/packages/esp32/hardware/esp32/2.0.17/tools/partitions/boot_app0.bin /usr/src/nuki_hub/build/release/boot_app0.bin - -CMD ["/bin/bash"] \ No newline at end of file diff --git a/Docker/README.md b/Docker/README.md index 7ca1db8..210672b 100644 --- a/Docker/README.md +++ b/Docker/README.md @@ -2,7 +2,7 @@ You can build this project using Docker. Just run the following commands in the console: -## Build with PlatformIO (will build for the ESP32, ESP32-S3, ESP32-C3 and ESP32-solo1) +## Build with PlatformIO (will build for the ESP32, ESP32-S3, ESP32-C3 and ESP32-C6) ```console git clone https://github.com/technyon/nuki_hub --recursive cd nuki_hub/Docker @@ -10,12 +10,3 @@ cd nuki_hub/Docker ``` once the script is complete you will find the nuki_hub binaries in the `nuki_hub/release` folder. - -## Build with CMake (will only build for the ESP32) -```console -git clone https://github.com/technyon/nuki_hub --recursive -cd nuki_hub/Docker -./build_with_docker_cmake.sh -``` - -once the script is complete you will find the nuki_hub binary in the `nuki_hub/build_cmake` folder. diff --git a/Docker/build_with_docker_cmake.sh b/Docker/build_with_docker_cmake.sh deleted file mode 100755 index 7f1b43a..0000000 --- a/Docker/build_with_docker_cmake.sh +++ /dev/null @@ -1,6 +0,0 @@ -set -ex -docker build -f ./Dockerfile_cmake -t nuki_hub_cmake .. -docker create --name nuki_hub_cmake nuki_hub_cmake -rm -rf ../build_cmake -docker cp nuki_hub_cmake:/usr/src/nuki_hub/build/ ../build_cmake -docker rm -f nuki_hub_cmake \ No newline at end of file diff --git a/Makefile b/Makefile index 3a84ac1..4ac1b21 100644 --- a/Makefile +++ b/Makefile @@ -10,12 +10,15 @@ default: esp32 .PHONY: release release: $(BOARDS) +.PHONY: updater +release: updater_$(BOARDS) + .PHONY: debug debug: $(DEBUG_BOARDS) -# Target to build all boards in both release and debug modes +# Target to build all boards in release, updater and debug modes .PHONY: all -all: release debug +all: release updater debug # Alias .PHONY: esp32 @@ -25,6 +28,10 @@ esp%: @echo "Building $@" pio run --environment $@ +updater_esp%: + @echo "Building $@" + pio run -d updater --environment $@ + # Help target to display available build targets .PHONY: help help: @@ -36,13 +43,14 @@ help: @$(foreach board,$(DEBUG_BOARDS),echo " make $(board) - Build $(board) in debug mode";) @echo "Available boards:" @echo " $(BOARDS)" + @echo " updater_$(BOARDS)" @echo " $(DEBUG_BOARDS)" # Utility target to clean build artifacts .PHONY: clean clean: @echo "Cleaning build artifacts..." - @-rm -rf release debug .pio/build + @-rm -rf release debug .pio/build updater/.pio/build # Install dependencies .PHONY: deps diff --git a/README.md b/README.md index 95bdb55..df5f380 100644 --- a/README.md +++ b/README.md @@ -15,12 +15,14 @@ Feel free to join us on Discord: https://discord.gg/9nPq85bP4p ## Supported devices Supported ESP32 devices: -- All ESP32 models with WIFI and BLE which are supported by Arduino Core 2.0.17 should work. Tested builds are provided for the ESP32, ESP32-S3 and ESP32-C3. -- Untested builds are provided for the ESP32-Solo1. +- 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.1. +- Tested stable builds are provided for the ESP32, ESP32-S3 and ESP32-C3. +- Support for the ESP32-C6 is ***HIGHLY*** experimental. Expect frequent crashes, especially when running Nuki Hub paired as an app (when not using in Hybrid mode). Pairing is also not supported yet and needs to be done manually on the /advanced page of the web configurator. +- The ESP32-Solo1 is not supported by ESP-IDF 5.1 and as such can't be build using Arduino Core 3 and ESP-IDF 5.1. Untested build against Arduino Core 2.0.14 and ESP-IDF 4.4 are provided. Not supported ESP32 devices: - The ESP32-S2 has no BLE and as such can't run Nuki Hub. -- The ESP32-C6 and ESP32-H2 are not supported by Arduino Core 2.0.17 and as such Nuki Hub is not compiled against these targets (at this time). +- The ESP32-H2 has no Wi-FI and Nuki Hub is not compiled against this target because of this (at this time). Supported Nuki devices: - Nuki Smart Lock 1.0 @@ -43,8 +45,14 @@ 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/) -Note for users upgrading from Nuki Hub 8.21 or lower:
-Please go to "MQTT and Network Configuration" and select "Wi-Fi only" as the network device (unless you use other network hardware). +## 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:
+REF2P8WSFGJCN
+This will also give you a 10% discount on your order.
+
+This project is free to use for everyone. However if you feel like donating, you can buy me a coffee at ko-fi.com:
+[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/C0C1IDUBV) ## First time installation @@ -54,8 +62,6 @@ NOTE: Webflash is not available for the ESP32-Solo1

Alternatively download the latest release for your ESP32 model from https://github.com/technyon/nuki_hub/releases
Unpack the zip archive and read the included how-to-flash.txt for installation instructions for either "Espressif Flash Download Tools" or "esptool".
-
-Updates can be installed using the Nuki Hub web configurator ## Initial setup (Network and MQTT) @@ -65,7 +71,7 @@ Use the web interface to connect the ESP to your preferred Wi-Fi network.

After configuring Wi-Fi, the ESP should automatically connect to your network.

-To configure the connection to the MQTT broker first connect your client device to the same Wi-Fi network the ESP32 is connected to.
+To configure the connection to the MQTT broker, first connect your client device to the same Wi-Fi network the ESP32 is connected to.
In a browser navigate to the IP address assigned to the ESP32 via DHCP (often found in the web interface of your internet router).

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.

@@ -77,7 +83,7 @@ In that case leave all fields starting with "MQTT SSL" blank. Otherwise see the Enable pairing mode on the Nuki Lock or Opener (press the button on the Nuki device for a few seconds) and power on the ESP32.
Pairing should be automatic.

-When pairing is successful, the web interface should show "Paired: Yes" (it might be necessary to reload the page in your browser).
+When pairing is successful, the web interface should show "Paired: Yes".
MQTT nodes like lock state and battery level should now reflect the reported values from the lock.

Note: It is possible to run Nuki Hub alongside a Nuki Bridge. @@ -89,15 +95,6 @@ Enable "Register as app" before pairing to allow this. Otherwise the Bridge will Hybrid mode allows you to use the official Nuki MQTT implemenation on a Nuki Lock 3.0 Pro, Nuki Lock 4.0 or Nuki Lock 4.0 Pro in conjunction with Nuki Hub.
See [hybrid mode](/HYBRID.md) for more information. -## Support - -If you haven't ordered your Nuki product yet, you can support me by using my referrer code when placing your order:
-REF2P8WSFGJCN
-This will also give you a 10% discount on your order.
-
-This project is free to use for everyone. However if you feel like donating, you can buy me a coffee at ko-fi.com:
-[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/C0C1IDUBV) - ## Configuration In a browser navigate to the IP address assigned to the ESP32. @@ -124,13 +121,14 @@ In a browser navigate to the IP address assigned to the ESP32. - 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. - RSSI Publish interval: Set to a positive integer to set the amount of seconds between updates to the maintenance/wifiRssi MQTT topic with the current Wi-Fi RSSI, set to -1 to disable, default 60. -- Network Timeout until restart: Set to a positive integer to restart the Nuki Hub after the set amount of seconds has passed without an active connection to the MQTT broker, set to -1 to disable, default 60. -- Restart on disconnect: Enable to restart the Nuki Hub after 60 seconds without a connection to a network. +- MQTT Timeout until restart: Set to a positive integer to restart the Nuki Hub after the set amount of seconds has passed without an active connection to the MQTT broker, set to -1 to disable, default 60. +- Restart on disconnect: Enable to restart the Nuki Hub when disconnected from the network. - Enable MQTT logging: Enable to fill the maintenance/log MQTT topic with debug log information. - Check for Firmware Updates every 24h: Enable to allow the Nuki Hub to check the latest release of the Nuki Hub firmware on boot and every 24 hours. Requires the Nuki Hub to be able to connect to github.com. The latest version will be published to MQTT and will be visible on the main page of the Web Configurator. +- Allow updating using MQTT: Enable to allow starting the Nuki Hub update process using MQTT. Will also enable the Home Assistant update functionality if auto discovery is enabled. - Disable some extraneous non-JSON topics: Enable to not publish non-JSON keypad and config MQTT topics. -- Enable hybrid official MQTT and Nuki Hub setup: Enable to combine the official MQTT over Thread/WiFi with BLE. Improves speed of state changes. Needs the official MQTT to be setup first. Also requires Nuki Hub to be paired as app and unregistered as a bridge using the Nuki app. See [hybrid mode](/HYBRID.md) -- Enable sending actions through official MQTT: Enable to sent lock actions through the official MQTT topics (e.g. over Thread/WiFi) instead of using BLE. Needs "Enable hybrid official MQTT and Nuki Hub setup" to be enabled. See [hybrid mode](/HYBRID.md) +- Enable hybrid official MQTT and Nuki Hub setup: Enable to combine the official MQTT over Thread/Wi-Fi with BLE. Improves speed of state changes. Needs the official MQTT to be setup first. Also requires Nuki Hub to be paired as app and unregistered as a bridge using the Nuki app. See [hybrid mode](/HYBRID.md) +- Enable sending actions through official MQTT: Enable to sent lock actions through the official MQTT topics (e.g. over Thread/Wi-Fi) instead of using BLE. Needs "Enable hybrid official MQTT and Nuki Hub setup" to be enabled. See [hybrid mode](/HYBRID.md) - Time between status updates when official MQTT is offline (seconds): Set to a positive integer to set the maximum amount of seconds between actively querying the Nuki lock for the current lock state when the official MQTT is offline, default 600. #### IP Address assignment @@ -158,9 +156,9 @@ In a browser navigate to the IP address assigned to the ESP32. - Query interval keypad (Only available when a Keypad is detected): Set to a positive integer to set the maximum amount of seconds between actively querying the Nuki device for the current keypad state, default 1800. - Number of retries if command failed: Set to a positive integer to define the amount of times the Nuki Hub retries sending commands to the Nuki Lock or Opener when commands are not acknowledged by the device, default 3. - Delay between retries: Set to the amount of milliseconds the Nuki Hub waits between resending not acknowledged commands, default 100. -- Lock: Nuki Bridge is running alongside Nuki Hub: Enable to allow Nuki Hub to co-exist with a Nuki Bridge by registering Nuki Hub as an (smartphone) app instead of a bridge. Changing this setting will require re-pairing. Enabling this setting is strongly discouraged as described in the "[Pairing with a Nuki Lock or Opener](#pairing-with-a-nuki-lock-or-opener)" section of this README, ***unless when used in [Hybrid mode](/HYBRID.md)e (Official MQTT / Nuki Hub co-existance)*** +- Lock: Nuki Bridge is running alongside Nuki Hub: Enable to allow Nuki Hub to co-exist with a Nuki Bridge by registering Nuki Hub as an (smartphone) app instead of a bridge. Changing this setting will require re-pairing. Enabling this setting is strongly discouraged as described in the "[Pairing with a Nuki Lock or Opener](#pairing-with-a-nuki-lock-or-opener)" section of this README, ***unless when used in [Hybrid mode](/HYBRID.md) (Official MQTT / Nuki Hub co-existance)*** - Opener: Nuki Bridge is running alongside Nuki Hub: Enable to allow Nuki Hub to co-exist with a Nuki Bridge by registering Nuki Hub as an (smartphone) app instead of a bridge. Changing this setting will require re-pairing. Enabling this setting is strongly discouraged as described in the "[Pairing with a Nuki Lock or Opener](#pairing-with-a-nuki-lock-or-opener)" section of this README -- Presence detection timeout: Set to a positive integer to set the amount of seconds between updates to the presence/devices MQTT topic with the list of detected bluetooth devices, set to -1 to disable presence detection, default 60. +- Presence detection timeout: Set to a positive integer to set the amount of seconds between updates to the presence/devices MQTT topic with the list of detected bluetooth devices, set to -1 to disable presence detection, default -1. - Restart if bluetooth beacons not received: Set to a positive integer to restart the Nuki Hub after the set amount of seconds has passed without receiving a bluetooth beacon from the Nuki device, set to -1 to disable, default 60. Because the bluetooth stack of the ESP32 can silently fail it is not recommended to disable this setting. ### Access Level Configuration @@ -198,7 +196,7 @@ In a browser navigate to the IP address assigned to the ESP32. #### Factory reset Nuki Hub -- Type [4 DIGIT CODE] to confirm factory reset: Set to the shown randomly generated code to reset all Nuki Hub settings to default and unpair Nuki Lock and/or Opener. Optionally also reset WiFi settings to default by enabling the checkbox. +- Type [4 DIGIT CODE] to confirm factory reset: Set to the shown randomly generated code to reset all Nuki Hub settings to default and unpair Nuki Lock and/or Opener. Optionally also reset Wi-Fi settings to default (and reopen the Wi-Fi configurator) by enabling the checkbox. ### GPIO Configuration @@ -303,8 +301,9 @@ 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" or "LilyGO T-ETH-POE". +- 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/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. - maintenance/uptime: Uptime in minutes. - maintenance/wifiRssi: The Wi-Fi signal strength of the Wi-Fi Access Point as measured by the ESP32 and expressed by the RSSI Value in dBm. @@ -315,7 +314,7 @@ In a browser navigate to the IP address assigned to the ESP32. ### Misc -- presence/devices: List of detected bluetooth devices as CSV. Can be used for presence detection. +- presence/devices: List of detected bluetooth devices as CSV, which be used for presence detection (by a third party application, Nuki Hub has no mechanism in place to act on the presence of absence of device). Because Nuki Hub uses passive scanning (which has no impact on battery life of nearby devices) only device MAC addresses and RSSI values are available and not device names or other information about the devices. ## Changing Nuki Lock/Opener Configuration @@ -423,12 +422,27 @@ Example: If Home Assistant discovery is enabled (see the [Home Assistant Discovery](#home-assistant-discovery-optional) section of this README) Nuki Hub will create entities for almost all of the above settings. -## Over-the-air Update (OTA) +## Upgrading using Over-the-air Update (OTA) After the initial installation of the Nuki Hub firmware via serial connection, further updates can be deployed via OTA update from a browser.
-In the configuration portal, scroll down to "Firmware update" and click "Open".
-Then Click "Browse" and select the new "nuki_hub.bin" file and select "Upload file".
-After about a minute the new firmware should be installed afterwhich the ESP will reboot automatically. +In the configuration portal, select "Firmware update" from the main page.
+
+The easiest way to upgrade Nuki Hub, if Nuki Hub is connected to the internet, is to select "Auto Update".
+This will download the latest Nuki Hub and Nuki Hub updater and automatically upgrade both applications.
+Nuki Hub will reboot 3 times during this process, which will take about 5 minutes.
+If you have enabled "Allow updating using MQTT" you can also use the Home Assistant updater or write "1" to the `nukihub/maintanance/reset` topic to start the update process.
+
+Alternatively you can select a binary file from your file system to update Nuki Hub or the Nuki Hub updator manually
+You can only update Nuki Hub from the Nuki Hub updater and update the updater only from Nuki Hub
+You can reboot from Nuki Hub to the updater and vice versa by selecting the reboot option from the "Firware update" page
+When you are on the right application you can upload the new binary by clicking on "Browse" and select the new "nuki_hub\[board\].bin" or "nuki_hub_updater\[board\].bin" file and select "Upload file".
+After about a minute the new firmware should be installed afterwhich the ESP will reboot automatically to the updated binary.
+Selecting the wrong binary will lead to an unsuccessfull update
+
+ Note for users upgrading from Nuki Hub 8.35 or lower:
+Updating to version 8.36 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 8.36 from an earlier version.
+Your settings will not be affected when updating using the above instructions (do not select erase device when updating using Webflash).
## MQTT Encryption (optional; Wi-Fi and LAN8720 only) @@ -594,8 +608,6 @@ To enable GPIO control, go the the "GPIO Configuration" page where each GPIO can - General input (pull-up): The pin is configured in pull-up configuration and its state is published to the "gpio/pin_x/state" topic - Genral output: The pin is set to high or low depending on the "gpio/pin_x/state" topic -Note: The old setting "Enable control via GPIO" is removed. If you had enabled this setting before upgrading to 8.22, the PINs are automatically configured to be compatible with the previously hard-coded PINs. - ## 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), @@ -617,6 +629,7 @@ If the W5500 hwardware isn't detected, Wi-Fi is used as a fallback.

Note: Encrypted MQTT is only available for Wi-Fi and LAN8720 modules, W5x00 modules don't support encryption
(that leaves Olimex, WT32-ETH01 and M5Stack PoESP32 Unit if encryption is desired).
+Note: LAN8720 modules are only supported on the ESP32, not on the ESP32-S3, ESP32-C3 or ESP-C6

If encryption is needed, Olimex is the easiest option, since it has USB for flashing onboard. @@ -636,22 +649,13 @@ It will restart the ESP after a configured amount of time. First, make sure the firmware version of the Nuki device is up-to-date, older versions have issues pairing.
Next, try erasing the ESP32 flash and then (re-)flash the firmware.
To erase the flash, use the espressif download tool and click the "Erase" button.
-Afterwards flash the firmware as described in the readme within the 7z file.
+Afterwards flash the firmware as described in the "how-to-flash.txt" file or using Webflash.

-Also, there are reports that the ESP32 "DEVKIT1" module doesn't work and pairing is not possible. The reason is unknown, but if you use such a module, try a different one.
-
-Reported as working are: -- [M5Stack ATOM Lite](https://shop.m5stack.com/products/atom-lite-esp32-development-kit) -- ESP32-WROOM-32D (DEVKIT V4) -- ESP32-WROOM-32E -- ESP32-S3-WROOM-1 +Also, check that pairing is allowed. In the Nuki smartphone app, go to "Settings" --> "Features & Configuration" --> "Button & LED" and make sure "Bluetooh Pairing" is enabled.
+Next press the button for several seconds untill the LED light remains lit. -For more information check the related issue: https://github.com/technyon/nuki_hub/issues/39 - -Also, check that pairing is allowed. In the Nuki smartphone app, go to "Settings" --> "Features & Configuration" --> "Button & LED" and make sure "Bluetooh Pairing" is enabled. - -A note about the [M5Stack PoESP32 Unit](https://docs.m5stack.com/en/unit/poesp32). Here the initial Bluetooth reception is very poor (range less than one meter). The reason is that the module does not have an antenna on the PCB, but only an IPEX connector. By retrofitting an external SMA antenna (IPEX, or other names U.FL, IPAX, IPX, AMC, MHF, UMCC), bluetooth/Wifi works over several meters. +A note about the [M5Stack PoESP32 Unit](https://docs.m5stack.com/en/unit/poesp32). Here the initial Bluetooth reception is very poor (range less than one meter). The reason is that the module does not have an antenna on the PCB, but only an IPEX connector. By retrofitting an external SMA antenna (IPEX, or other names U.FL, IPAX, IPX, AMC, MHF, UMCC), Bluetooth/Wi-Fi works over several meters. ### In Home Assistant, the lock/opener is shown as unavailable @@ -661,17 +665,19 @@ This unfortunately means that older versions of Home Assistant are not supported ## FAQ -### Nuki Hub doesn't work when Wi-Fi on a Nuki Smartlock Pro (3.0 / 4.0) is turned on. +### Nuki Hub in bridge mode doesn't work when Wi-Fi on a Nuki Smartlock Pro (3.0 / 4.0) is turned on. According to Nuki this is by design and part of the specification of the Pro lock.
You can use either the built-in Wi-Fi or a Bridge (which Nuki Hub registers as).
+Or use Nuki Hub in Hybrid mode using Wi-Fi or Thread, see [hybrid mode](/HYBRID.md)
Using both at the same time is not supported. ### Certain functionality doesn't work (e. g. changing configuration, setting keypad codes) Some functionality is restricted by the Lock (or Opener) firmware and is only accessible when the PIN is provided.
When setting up the lock (or opener), you have to set a PIN in the Nuki smartphone app.
-Navigate to the Nuki Hub Credentials page, enter this PIN and click save. +Navigate to the Nuki Hub Credentials page, enter this PIN and click save.
+Check the main page of the configurator to see if the entered PIN is valid ### Authorization data isn't published @@ -717,28 +723,9 @@ cd nuki_hub make deps # build all binary boards +make updater make release ``` -
-VMWare image (Not preferred, not using the latest Arduino ESP32 release at this time)
-A virtual machine (VMWare image) that is setup to compile Nuki Hub is available for download at:
-https://drive.google.com/file/d/1fUVYHDtxXAZOAfQ321iRNIwkqFwuDsBp/view?usp=share_link
-
-User and password for the VM are both "nuki" and "nuki".
-The source is checked out at ~/projects/nuki_hub, the cmake build directory is build.
-
-To compile, run the following commands: -``` -cd projects/nuki_hub/build -ninja -``` - -To upload the image via serial port, run: -``` -ninja upload-nuki_hub -``` - -The serial device is defined in ~/.bashrc (Environment variable SERIAL_PORT), which you'll eventually have to adopt to your device. ## Disclaimer diff --git a/lib/AsyncTCP-esphome/.github/stale.yml b/lib/AsyncTCP-esphome/.github/stale.yml deleted file mode 100644 index ce7a8e3..0000000 --- a/lib/AsyncTCP-esphome/.github/stale.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Configuration for probot-stale - https://github.com/probot/stale - -daysUntilStale: 60 -daysUntilClose: 14 -limitPerRun: 30 -staleLabel: stale -exemptLabels: - - pinned - - security - - "to be implemented" - - "for reference" - - "move to PR" - - "enhancement" - -only: issues -onlyLabels: [] -exemptProjects: false -exemptMilestones: false -exemptAssignees: false - -markComment: > - [STALE_SET] This issue has been automatically marked as stale because it has not had - recent activity. It will be closed in 14 days if no further activity occurs. Thank you - for your contributions. - -unmarkComment: > - [STALE_CLR] This issue has been removed from the stale queue. Please ensure activity to keep it openin the future. - -closeComment: > - [STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions. - diff --git a/lib/AsyncTCP-esphome/.github/workflows/push.yml b/lib/AsyncTCP-esphome/.github/workflows/push.yml deleted file mode 100644 index b7b62c6..0000000 --- a/lib/AsyncTCP-esphome/.github/workflows/push.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: Async TCP CI - -on: - push: - branches: - pull_request: - -jobs: - - build-arduino: - name: Arduino on ${{ matrix.os }} - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest] - steps: - - uses: actions/checkout@v3 - - uses: arduino/setup-arduino-cli@v1 - - name: Download board - run: | - arduino-cli --config-file arduino-cli.yaml core update-index - arduino-cli --config-file arduino-cli.yaml board listall - arduino-cli --config-file arduino-cli.yaml core install esp32:esp32@2.0.2 - - name: Compile Sketch - run: arduino-cli --config-file arduino-cli.yaml --library ./src/ compile --fqbn esp32:esp32:esp32 ./examples/ClientServer/Client/Client.ino - - name: Compile Sketch with IPv6 - env: - LWIP_IPV6: true - run: arduino-cli --config-file arduino-cli.yaml --library ./src/ compile --fqbn esp32:esp32:esp32 ./examples/ClientServer/Client/Client.ino diff --git a/lib/AsyncTCP-esphome/.gitignore b/lib/AsyncTCP-esphome/.gitignore deleted file mode 100644 index 9bea433..0000000 --- a/lib/AsyncTCP-esphome/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ - -.DS_Store diff --git a/lib/AsyncTCP-esphome/.piopm b/lib/AsyncTCP-esphome/.piopm deleted file mode 100644 index cc235bc..0000000 --- a/lib/AsyncTCP-esphome/.piopm +++ /dev/null @@ -1 +0,0 @@ -{"type": "library", "name": "AsyncTCP-esphome", "version": "2.1.3", "spec": {"owner": "esphome", "id": 12172, "name": "AsyncTCP-esphome", "requirements": null, "uri": null}} \ No newline at end of file diff --git a/lib/AsyncTCP-esphome/.travis.yml b/lib/AsyncTCP-esphome/.travis.yml deleted file mode 100644 index dbfc064..0000000 --- a/lib/AsyncTCP-esphome/.travis.yml +++ /dev/null @@ -1,34 +0,0 @@ -sudo: false -language: python -os: - - linux - -git: - depth: false - -stages: - - build - -jobs: - include: - - - name: "Arduino Build" - if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) - stage: build - script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh - - - name: "PlatformIO Build" - if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) - stage: build - script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 1 1 - -notifications: - email: - on_success: change - on_failure: change - webhooks: - urls: - - https://webhooks.gitter.im/e/60e65d0c78ea0a920347 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: false # default: false diff --git a/lib/AsyncTCP-esphome/CMakeLists.txt b/lib/AsyncTCP-esphome/CMakeLists.txt deleted file mode 100644 index f52e1c9..0000000 --- a/lib/AsyncTCP-esphome/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -set(COMPONENT_SRCDIRS - "src" -) - -set(COMPONENT_ADD_INCLUDEDIRS - "src" -) - -set(COMPONENT_REQUIRES - "arduino-esp32" -) - -register_component() - -target_compile_options(${COMPONENT_TARGET} PRIVATE -fno-rtti) diff --git a/lib/AsyncTCP-esphome/Kconfig.projbuild b/lib/AsyncTCP-esphome/Kconfig.projbuild deleted file mode 100644 index 1774926..0000000 --- a/lib/AsyncTCP-esphome/Kconfig.projbuild +++ /dev/null @@ -1,30 +0,0 @@ -menu "AsyncTCP Configuration" - -choice ASYNC_TCP_RUNNING_CORE - bool "Core on which AsyncTCP's thread is running" - default ASYNC_TCP_RUN_CORE1 - help - Select on which core AsyncTCP is running - - config ASYNC_TCP_RUN_CORE0 - bool "CORE 0" - config ASYNC_TCP_RUN_CORE1 - bool "CORE 1" - config ASYNC_TCP_RUN_NO_AFFINITY - bool "BOTH" - -endchoice - -config ASYNC_TCP_RUNNING_CORE - int - default 0 if ASYNC_TCP_RUN_CORE0 - default 1 if ASYNC_TCP_RUN_CORE1 - default -1 if ASYNC_TCP_RUN_NO_AFFINITY - -config ASYNC_TCP_USE_WDT - bool "Enable WDT for the AsyncTCP task" - default "y" - help - Enable WDT for the AsyncTCP task, so it will trigger if a handler is locking the thread. - -endmenu diff --git a/lib/AsyncTCP-esphome/README.md b/lib/AsyncTCP-esphome/README.md deleted file mode 100644 index 17b145b..0000000 --- a/lib/AsyncTCP-esphome/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# AsyncTCP -![Build Status](https://github.com/esphome/AsyncTCP/actions/workflows/push.yml/badge.svg) -A fork of the [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) library by [@me-no-dev](https://github.com/me-no-dev) for [ESPHome](https://esphome.io). - -### Async TCP Library for ESP32 Arduino - -This is a fully asynchronous TCP library, aimed at enabling trouble-free, multi-connection network environment for Espressif's ESP32 MCUs. - -This library is the base for [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) - -## AsyncClient and AsyncServer -The base classes on which everything else is built. They expose all possible scenarios, but are really raw and require more skills to use. diff --git a/lib/AsyncTCP-esphome/component.mk b/lib/AsyncTCP-esphome/component.mk deleted file mode 100644 index bb5bb16..0000000 --- a/lib/AsyncTCP-esphome/component.mk +++ /dev/null @@ -1,3 +0,0 @@ -COMPONENT_ADD_INCLUDEDIRS := src -COMPONENT_SRCDIRS := src -CXXFLAGS += -fno-rtti diff --git a/lib/AsyncTCP-esphome/library.json b/lib/AsyncTCP-esphome/library.json deleted file mode 100644 index 52819dc..0000000 --- a/lib/AsyncTCP-esphome/library.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "AsyncTCP-esphome", - "description": "Asynchronous TCP Library for ESP32", - "keywords": "async,tcp", - "authors": { - "name": "Hristo Gochkov", - "maintainer": true - }, - "repository": { - "type": "git", - "url": "https://github.com/esphome/AsyncTCP.git" - }, - "version": "2.1.3", - "license": "LGPL-3.0", - "frameworks": "arduino", - "platforms": [ - "espressif32", - "libretiny" - ], - "build": { - "libCompatMode": 2 - } -} diff --git a/lib/AsyncTCP-esphome/src/AsyncTCP.cpp b/lib/AsyncTCP-esphome/src/AsyncTCP.cpp deleted file mode 100644 index 592cb38..0000000 --- a/lib/AsyncTCP-esphome/src/AsyncTCP.cpp +++ /dev/null @@ -1,1464 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "Arduino.h" - -#include "AsyncTCP.h" -extern "C"{ -#include "lwip/opt.h" -#include "lwip/tcp.h" -#include "lwip/inet.h" -#include "lwip/dns.h" -#include "lwip/err.h" -} -#if CONFIG_ASYNC_TCP_USE_WDT -#include "esp_task_wdt.h" -#endif - -/* - * TCP/IP Event Task - * */ - -typedef enum { - LWIP_TCP_SENT, LWIP_TCP_RECV, LWIP_TCP_FIN, LWIP_TCP_ERROR, LWIP_TCP_POLL, LWIP_TCP_CLEAR, LWIP_TCP_ACCEPT, LWIP_TCP_CONNECTED, LWIP_TCP_DNS -} lwip_event_t; - -typedef struct { - lwip_event_t event; - void *arg; - union { - struct { - void * pcb; - int8_t err; - } connected; - struct { - int8_t err; - } error; - struct { - tcp_pcb * pcb; - uint16_t len; - } sent; - struct { - tcp_pcb * pcb; - pbuf * pb; - int8_t err; - } recv; - struct { - tcp_pcb * pcb; - int8_t err; - } fin; - struct { - tcp_pcb * pcb; - } poll; - struct { - AsyncClient * client; - } accept; - struct { - const char * name; - ip_addr_t addr; - } dns; - }; -} lwip_event_packet_t; - -static QueueHandle_t _async_queue; -static TaskHandle_t _async_service_task_handle = NULL; - - -SemaphoreHandle_t _slots_lock; -const int _number_of_closed_slots = CONFIG_LWIP_MAX_ACTIVE_TCP; -static uint32_t _closed_slots[_number_of_closed_slots]; -static uint32_t _closed_index = []() { - _slots_lock = xSemaphoreCreateBinary(); - xSemaphoreGive(_slots_lock); - for (int i = 0; i < _number_of_closed_slots; ++ i) { - _closed_slots[i] = 1; - } - return 1; -}(); - - -static inline bool _init_async_event_queue(){ - if(!_async_queue){ - _async_queue = xQueueCreate(32, sizeof(lwip_event_packet_t *)); - if(!_async_queue){ - return false; - } - } - return true; -} - -static inline bool _send_async_event(lwip_event_packet_t ** e){ - return _async_queue && xQueueSend(_async_queue, e, portMAX_DELAY) == pdPASS; -} - -static inline bool _prepend_async_event(lwip_event_packet_t ** e){ - return _async_queue && xQueueSendToFront(_async_queue, e, portMAX_DELAY) == pdPASS; -} - -static inline bool _get_async_event(lwip_event_packet_t ** e){ - return _async_queue && xQueueReceive(_async_queue, e, portMAX_DELAY) == pdPASS; -} - -static bool _remove_events_with_arg(void * arg){ - lwip_event_packet_t * first_packet = NULL; - lwip_event_packet_t * packet = NULL; - - if(!_async_queue){ - return false; - } - //figure out which is the first packet so we can keep the order - while(!first_packet){ - if(xQueueReceive(_async_queue, &first_packet, 0) != pdPASS){ - return false; - } - //discard packet if matching - if((int)first_packet->arg == (int)arg){ - free(first_packet); - first_packet = NULL; - //return first packet to the back of the queue - } else if(xQueueSend(_async_queue, &first_packet, portMAX_DELAY) != pdPASS){ - return false; - } - } - - while(xQueuePeek(_async_queue, &packet, 0) == pdPASS && packet != first_packet){ - if(xQueueReceive(_async_queue, &packet, 0) != pdPASS){ - return false; - } - if((int)packet->arg == (int)arg){ - free(packet); - packet = NULL; - } else if(xQueueSend(_async_queue, &packet, portMAX_DELAY) != pdPASS){ - return false; - } - } - return true; -} - -static void _handle_async_event(lwip_event_packet_t * e){ - if(e->arg == NULL){ - // do nothing when arg is NULL - //ets_printf("event arg == NULL: 0x%08x\n", e->recv.pcb); - } else if(e->event == LWIP_TCP_CLEAR){ - _remove_events_with_arg(e->arg); - } else if(e->event == LWIP_TCP_RECV){ - //ets_printf("-R: 0x%08x\n", e->recv.pcb); - AsyncClient::_s_recv(e->arg, e->recv.pcb, e->recv.pb, e->recv.err); - } else if(e->event == LWIP_TCP_FIN){ - //ets_printf("-F: 0x%08x\n", e->fin.pcb); - AsyncClient::_s_fin(e->arg, e->fin.pcb, e->fin.err); - } else if(e->event == LWIP_TCP_SENT){ - //ets_printf("-S: 0x%08x\n", e->sent.pcb); - AsyncClient::_s_sent(e->arg, e->sent.pcb, e->sent.len); - } else if(e->event == LWIP_TCP_POLL){ - //ets_printf("-P: 0x%08x\n", e->poll.pcb); - AsyncClient::_s_poll(e->arg, e->poll.pcb); - } else if(e->event == LWIP_TCP_ERROR){ - //ets_printf("-E: 0x%08x %d\n", e->arg, e->error.err); - AsyncClient::_s_error(e->arg, e->error.err); - } else if(e->event == LWIP_TCP_CONNECTED){ - //ets_printf("C: 0x%08x 0x%08x %d\n", e->arg, e->connected.pcb, e->connected.err); - AsyncClient::_s_connected(e->arg, e->connected.pcb, e->connected.err); - } else if(e->event == LWIP_TCP_ACCEPT){ - //ets_printf("A: 0x%08x 0x%08x\n", e->arg, e->accept.client); - AsyncServer::_s_accepted(e->arg, e->accept.client); - } else if(e->event == LWIP_TCP_DNS){ - //ets_printf("D: 0x%08x %s = %s\n", e->arg, e->dns.name, ipaddr_ntoa(&e->dns.addr)); - AsyncClient::_s_dns_found(e->dns.name, &e->dns.addr, e->arg); - } - free((void*)(e)); -} - -static void _async_service_task(void *pvParameters){ - lwip_event_packet_t * packet = NULL; - for (;;) { - if(_get_async_event(&packet)){ -#if CONFIG_ASYNC_TCP_USE_WDT - if(esp_task_wdt_add(NULL) != ESP_OK){ - log_e("Failed to add async task to WDT"); - } -#endif - _handle_async_event(packet); -#if CONFIG_ASYNC_TCP_USE_WDT - if(esp_task_wdt_delete(NULL) != ESP_OK){ - log_e("Failed to remove loop task from WDT"); - } -#endif - } - } - vTaskDelete(NULL); - _async_service_task_handle = NULL; -} -/* -static void _stop_async_task(){ - if(_async_service_task_handle){ - vTaskDelete(_async_service_task_handle); - _async_service_task_handle = NULL; - } -} -*/ - -static bool customTaskCreateUniversal( - TaskFunction_t pxTaskCode, - const char * const pcName, - const uint32_t usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - const BaseType_t xCoreID) { -#ifndef CONFIG_FREERTOS_UNICORE - if(xCoreID >= 0 && xCoreID < 2) { - return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); - } else { -#endif - return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); -#ifndef CONFIG_FREERTOS_UNICORE - } -#endif -} - -static bool _start_async_task(){ - if(!_init_async_event_queue()){ - return false; - } - if(!_async_service_task_handle){ - customTaskCreateUniversal(_async_service_task, "async_tcp", CONFIG_ASYNC_TCP_STACK_SIZE, NULL, 3, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE); - if(!_async_service_task_handle){ - return false; - } - } - return true; -} - -/* - * LwIP Callbacks - * */ - -static int8_t _tcp_clear_events(void * arg) { - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->event = LWIP_TCP_CLEAR; - e->arg = arg; - if (!_prepend_async_event(&e)) { - free((void*)(e)); - } - return ERR_OK; -} - -static int8_t _tcp_connected(void * arg, tcp_pcb * pcb, int8_t err) { - //ets_printf("+C: 0x%08x\n", pcb); - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->event = LWIP_TCP_CONNECTED; - e->arg = arg; - e->connected.pcb = pcb; - e->connected.err = err; - if (!_prepend_async_event(&e)) { - free((void*)(e)); - } - return ERR_OK; -} - -static int8_t _tcp_poll(void * arg, struct tcp_pcb * pcb) { - //ets_printf("+P: 0x%08x\n", pcb); - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->event = LWIP_TCP_POLL; - e->arg = arg; - e->poll.pcb = pcb; - if (!_send_async_event(&e)) { - free((void*)(e)); - } - return ERR_OK; -} - -static int8_t _tcp_recv(void * arg, struct tcp_pcb * pcb, struct pbuf *pb, int8_t err) { - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->arg = arg; - if(pb){ - //ets_printf("+R: 0x%08x\n", pcb); - e->event = LWIP_TCP_RECV; - e->recv.pcb = pcb; - e->recv.pb = pb; - e->recv.err = err; - } else { - //ets_printf("+F: 0x%08x\n", pcb); - e->event = LWIP_TCP_FIN; - e->fin.pcb = pcb; - e->fin.err = err; - //close the PCB in LwIP thread - AsyncClient::_s_lwip_fin(e->arg, e->fin.pcb, e->fin.err); - } - if (!_send_async_event(&e)) { - free((void*)(e)); - } - return ERR_OK; -} - -static int8_t _tcp_sent(void * arg, struct tcp_pcb * pcb, uint16_t len) { - //ets_printf("+S: 0x%08x\n", pcb); - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->event = LWIP_TCP_SENT; - e->arg = arg; - e->sent.pcb = pcb; - e->sent.len = len; - if (!_send_async_event(&e)) { - free((void*)(e)); - } - return ERR_OK; -} - -static void _tcp_error(void * arg, int8_t err) { - //ets_printf("+E: 0x%08x\n", arg); - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->event = LWIP_TCP_ERROR; - e->arg = arg; - e->error.err = err; - if (!_send_async_event(&e)) { - free((void*)(e)); - } -} - -static void _tcp_dns_found(const char * name, struct ip_addr * ipaddr, void * arg) { - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - //ets_printf("+DNS: name=%s ipaddr=0x%08x arg=%x\n", name, ipaddr, arg); - e->event = LWIP_TCP_DNS; - e->arg = arg; - e->dns.name = name; - if (ipaddr) { - memcpy(&e->dns.addr, ipaddr, sizeof(struct ip_addr)); - } else { - memset(&e->dns.addr, 0, sizeof(e->dns.addr)); - } - if (!_send_async_event(&e)) { - free((void*)(e)); - } -} - -//Used to switch out from LwIP thread -static int8_t _tcp_accept(void * arg, AsyncClient * client) { - lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); - e->event = LWIP_TCP_ACCEPT; - e->arg = arg; - e->accept.client = client; - if (!_prepend_async_event(&e)) { - free((void*)(e)); - } - return ERR_OK; -} - -/* - * TCP/IP API Calls - * */ - -#include "lwip/priv/tcpip_priv.h" - -typedef struct { - struct tcpip_api_call_data call; - tcp_pcb * pcb; - int8_t closed_slot; - int8_t err; - union { - struct { - const char* data; - size_t size; - uint8_t apiflags; - } write; - size_t received; - struct { - ip_addr_t * addr; - uint16_t port; - tcp_connected_fn cb; - } connect; - struct { - ip_addr_t * addr; - uint16_t port; - } bind; - uint8_t backlog; - }; -} tcp_api_call_t; - -static err_t _tcp_output_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = ERR_CONN; - if(msg->closed_slot == -1 || !_closed_slots[msg->closed_slot]) { - msg->err = tcp_output(msg->pcb); - } - return msg->err; -} - -static esp_err_t _tcp_output(tcp_pcb * pcb, int8_t closed_slot) { - if(!pcb){ - return ERR_CONN; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = closed_slot; - tcpip_api_call(_tcp_output_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_write_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = ERR_CONN; - if(msg->closed_slot == -1 || !_closed_slots[msg->closed_slot]) { - msg->err = tcp_write(msg->pcb, msg->write.data, msg->write.size, msg->write.apiflags); - } - return msg->err; -} - -static esp_err_t _tcp_write(tcp_pcb * pcb, int8_t closed_slot, const char* data, size_t size, uint8_t apiflags) { - if(!pcb){ - return ERR_CONN; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = closed_slot; - msg.write.data = data; - msg.write.size = size; - msg.write.apiflags = apiflags; - tcpip_api_call(_tcp_write_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_recved_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = ERR_CONN; - if(msg->closed_slot == -1 || !_closed_slots[msg->closed_slot]) { - msg->err = 0; - tcp_recved(msg->pcb, msg->received); - } - return msg->err; -} - -static esp_err_t _tcp_recved(tcp_pcb * pcb, int8_t closed_slot, size_t len) { - if(!pcb){ - return ERR_CONN; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = closed_slot; - msg.received = len; - tcpip_api_call(_tcp_recved_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_close_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = ERR_CONN; - if(msg->closed_slot == -1 || !_closed_slots[msg->closed_slot]) { - msg->err = tcp_close(msg->pcb); - } - return msg->err; -} - -static esp_err_t _tcp_close(tcp_pcb * pcb, int8_t closed_slot) { - if(!pcb){ - return ERR_CONN; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = closed_slot; - tcpip_api_call(_tcp_close_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_abort_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = ERR_CONN; - if(msg->closed_slot == -1 || !_closed_slots[msg->closed_slot]) { - tcp_abort(msg->pcb); - } - return msg->err; -} - -static esp_err_t _tcp_abort(tcp_pcb * pcb, int8_t closed_slot) { - if(!pcb){ - return ERR_CONN; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = closed_slot; - tcpip_api_call(_tcp_abort_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_connect_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = tcp_connect(msg->pcb, msg->connect.addr, msg->connect.port, msg->connect.cb); - return msg->err; -} - -static esp_err_t _tcp_connect(tcp_pcb * pcb, int8_t closed_slot, ip_addr_t * addr, uint16_t port, tcp_connected_fn cb) { - if(!pcb){ - return ESP_FAIL; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = closed_slot; - msg.connect.addr = addr; - msg.connect.port = port; - msg.connect.cb = cb; - tcpip_api_call(_tcp_connect_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_bind_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = tcp_bind(msg->pcb, msg->bind.addr, msg->bind.port); - return msg->err; -} - -static esp_err_t _tcp_bind(tcp_pcb * pcb, ip_addr_t * addr, uint16_t port) { - if(!pcb){ - return ESP_FAIL; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = -1; - msg.bind.addr = addr; - msg.bind.port = port; - tcpip_api_call(_tcp_bind_api, (struct tcpip_api_call_data*)&msg); - return msg.err; -} - -static err_t _tcp_listen_api(struct tcpip_api_call_data *api_call_msg){ - tcp_api_call_t * msg = (tcp_api_call_t *)api_call_msg; - msg->err = 0; - msg->pcb = tcp_listen_with_backlog(msg->pcb, msg->backlog); - return msg->err; -} - -static tcp_pcb * _tcp_listen_with_backlog(tcp_pcb * pcb, uint8_t backlog) { - if(!pcb){ - return NULL; - } - tcp_api_call_t msg; - msg.pcb = pcb; - msg.closed_slot = -1; - msg.backlog = backlog?backlog:0xFF; - tcpip_api_call(_tcp_listen_api, (struct tcpip_api_call_data*)&msg); - return msg.pcb; -} - - - -/* - Async TCP Client - */ - -AsyncClient::AsyncClient(tcp_pcb* pcb) -: _connect_cb(0) -, _connect_cb_arg(0) -, _discard_cb(0) -, _discard_cb_arg(0) -, _sent_cb(0) -, _sent_cb_arg(0) -, _error_cb(0) -, _error_cb_arg(0) -, _recv_cb(0) -, _recv_cb_arg(0) -, _pb_cb(0) -, _pb_cb_arg(0) -, _timeout_cb(0) -, _timeout_cb_arg(0) -, _ack_pcb(true) -, _tx_last_packet(0) -, _rx_timeout(0) -, _rx_last_ack(0) -, _ack_timeout(ASYNC_MAX_ACK_TIME) -, _connect_port(0) -, prev(NULL) -, next(NULL) -{ - _pcb = pcb; - _closed_slot = -1; - if(_pcb){ - _allocate_closed_slot(); - _rx_last_packet = millis(); - tcp_arg(_pcb, this); - tcp_recv(_pcb, &_tcp_recv); - tcp_sent(_pcb, &_tcp_sent); - tcp_err(_pcb, &_tcp_error); - tcp_poll(_pcb, &_tcp_poll, 1); - } -} - -AsyncClient::~AsyncClient(){ - if(_pcb) { - _close(); - } - _free_closed_slot(); -} - -/* - * Operators - * */ - -AsyncClient& AsyncClient::operator=(const AsyncClient& other){ - if (_pcb) { - _close(); - } - - _pcb = other._pcb; - _closed_slot = other._closed_slot; - if (_pcb) { - _rx_last_packet = millis(); - tcp_arg(_pcb, this); - tcp_recv(_pcb, &_tcp_recv); - tcp_sent(_pcb, &_tcp_sent); - tcp_err(_pcb, &_tcp_error); - tcp_poll(_pcb, &_tcp_poll, 1); - } - return *this; -} - -bool AsyncClient::operator==(const AsyncClient &other) { - return _pcb == other._pcb; -} - -AsyncClient & AsyncClient::operator+=(const AsyncClient &other) { - if(next == NULL){ - next = (AsyncClient*)(&other); - next->prev = this; - } else { - AsyncClient *c = next; - while(c->next != NULL) { - c = c->next; - } - c->next =(AsyncClient*)(&other); - c->next->prev = c; - } - return *this; -} - -/* - * Callback Setters - * */ - -void AsyncClient::onConnect(AcConnectHandler cb, void* arg){ - _connect_cb = cb; - _connect_cb_arg = arg; -} - -void AsyncClient::onDisconnect(AcConnectHandler cb, void* arg){ - _discard_cb = cb; - _discard_cb_arg = arg; -} - -void AsyncClient::onAck(AcAckHandler cb, void* arg){ - _sent_cb = cb; - _sent_cb_arg = arg; -} - -void AsyncClient::onError(AcErrorHandler cb, void* arg){ - _error_cb = cb; - _error_cb_arg = arg; -} - -void AsyncClient::onData(AcDataHandler cb, void* arg){ - _recv_cb = cb; - _recv_cb_arg = arg; -} - -void AsyncClient::onPacket(AcPacketHandler cb, void* arg){ - _pb_cb = cb; - _pb_cb_arg = arg; -} - -void AsyncClient::onTimeout(AcTimeoutHandler cb, void* arg){ - _timeout_cb = cb; - _timeout_cb_arg = arg; -} - -void AsyncClient::onPoll(AcConnectHandler cb, void* arg){ - _poll_cb = cb; - _poll_cb_arg = arg; -} - -/* - * Main Public Methods - * */ - -bool AsyncClient::_connect(ip_addr_t addr, uint16_t port){ - if (_pcb){ - log_w("already connected, state %d", _pcb->state); - return false; - } - if(!_start_async_task()){ - log_e("failed to start task"); - return false; - } - - tcp_pcb* pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); - if (!pcb){ - log_e("pcb == NULL"); - return false; - } - - tcp_arg(pcb, this); - tcp_err(pcb, &_tcp_error); - tcp_recv(pcb, &_tcp_recv); - tcp_sent(pcb, &_tcp_sent); - tcp_poll(pcb, &_tcp_poll, 1); - _tcp_connect(pcb, _closed_slot, &addr, port,(tcp_connected_fn)&_tcp_connected); - return true; -} - -bool AsyncClient::connect(IPAddress ip, uint16_t port){ - ip_addr_t addr; - ip_addr_set_ip4_u32(&addr, ip); - - return _connect(addr, port); -} - -#if LWIP_IPV6 -bool AsyncClient::connect(IPv6Address ip, uint16_t port){ - ip_addr_t addr; - addr.type = IPADDR_TYPE_V6; - memcpy(addr.u_addr.ip6.addr, static_cast(ip), sizeof(uint32_t) * 4); - - return _connect(addr, port); -} -#endif - -bool AsyncClient::connect(const char* host, uint16_t port){ - ip_addr_t addr; - - if(!_start_async_task()){ - log_e("failed to start task"); - return false; - } - - err_t err = dns_gethostbyname(host, &addr, (dns_found_callback)&_tcp_dns_found, this); - if(err == ERR_OK) { -#if LWIP_IPV6 - if(addr.type == IPADDR_TYPE_V6) { - return connect(IPv6Address(addr.u_addr.ip6.addr), port); - } - return connect(IPAddress(addr.u_addr.ip4.addr), port); -#else - return connect(IPAddress(addr.addr), port); -#endif - } else if(err == ERR_INPROGRESS) { - _connect_port = port; - return true; - } - log_e("error: %d", err); - return false; -} - -void AsyncClient::close(bool now){ - if(_pcb){ - _tcp_recved(_pcb, _closed_slot, _rx_ack_len); - } - _close(); -} - -int8_t AsyncClient::abort(){ - if(_pcb) { - _tcp_abort(_pcb, _closed_slot ); - _pcb = NULL; - } - return ERR_ABRT; -} - -size_t AsyncClient::space(){ - if((_pcb != NULL) && (_pcb->state == 4)){ - return tcp_sndbuf(_pcb); - } - return 0; -} - -size_t AsyncClient::add(const char* data, size_t size, uint8_t apiflags) { - if(!_pcb || size == 0 || data == NULL) { - return 0; - } - size_t room = space(); - if(!room) { - return 0; - } - size_t will_send = (room < size) ? room : size; - int8_t err = ERR_OK; - err = _tcp_write(_pcb, _closed_slot, data, will_send, apiflags); - if(err != ERR_OK) { - return 0; - } - return will_send; -} - -bool AsyncClient::send(){ - auto backup = _tx_last_packet; - _tx_last_packet = millis(); - if (_tcp_output(_pcb, _closed_slot) == ERR_OK) { - return true; - } - _tx_last_packet = backup; - return false; -} - -size_t AsyncClient::ack(size_t len){ - if(len > _rx_ack_len) - len = _rx_ack_len; - if(len){ - _tcp_recved(_pcb, _closed_slot, len); - } - _rx_ack_len -= len; - return len; -} - -void AsyncClient::ackPacket(struct pbuf * pb){ - if(!pb){ - return; - } - _tcp_recved(_pcb, _closed_slot, pb->len); - pbuf_free(pb); -} - -/* - * Main Private Methods - * */ - -int8_t AsyncClient::_close(){ - //ets_printf("X: 0x%08x\n", (uint32_t)this); - int8_t err = ERR_OK; - if(_pcb) { - //log_i(""); - tcp_arg(_pcb, NULL); - tcp_sent(_pcb, NULL); - tcp_recv(_pcb, NULL); - tcp_err(_pcb, NULL); - tcp_poll(_pcb, NULL, 0); - _tcp_clear_events(this); - err = _tcp_close(_pcb, _closed_slot); - if(err != ERR_OK) { - err = abort(); - } - _pcb = NULL; - if(_discard_cb) { - _discard_cb(_discard_cb_arg, this); - } - } - return err; -} - -void AsyncClient::_allocate_closed_slot(){ - xSemaphoreTake(_slots_lock, portMAX_DELAY); - uint32_t closed_slot_min_index = 0; - for (int i = 0; i < _number_of_closed_slots; ++ i) { - if ((_closed_slot == -1 || _closed_slots[i] <= closed_slot_min_index) && _closed_slots[i] != 0) { - closed_slot_min_index = _closed_slots[i]; - _closed_slot = i; - } - } - if (_closed_slot != -1) { - _closed_slots[_closed_slot] = 0; - } - xSemaphoreGive(_slots_lock); -} - -void AsyncClient::_free_closed_slot(){ - if (_closed_slot != -1) { - _closed_slots[_closed_slot] = _closed_index; - _closed_slot = -1; - ++ _closed_index; - } -} - -/* - * Private Callbacks - * */ - -int8_t AsyncClient::_connected(void* pcb, int8_t err){ - _pcb = reinterpret_cast(pcb); - if(_pcb){ - _rx_last_packet = millis(); -// tcp_recv(_pcb, &_tcp_recv); -// tcp_sent(_pcb, &_tcp_sent); -// tcp_poll(_pcb, &_tcp_poll, 1); - } - if(_connect_cb) { - _connect_cb(_connect_cb_arg, this); - } - return ERR_OK; -} - -void AsyncClient::_error(int8_t err) { - if(_pcb){ - tcp_arg(_pcb, NULL); - if(_pcb->state == LISTEN) { - tcp_sent(_pcb, NULL); - tcp_recv(_pcb, NULL); - tcp_err(_pcb, NULL); - tcp_poll(_pcb, NULL, 0); - } - _pcb = NULL; - } - if(_error_cb) { - _error_cb(_error_cb_arg, this, err); - } - if(_discard_cb) { - _discard_cb(_discard_cb_arg, this); - } -} - -//In LwIP Thread -int8_t AsyncClient::_lwip_fin(tcp_pcb* pcb, int8_t err) { - if(!_pcb || pcb != _pcb){ - log_e("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); - return ERR_OK; - } - tcp_arg(_pcb, NULL); - if(_pcb->state == LISTEN) { - tcp_sent(_pcb, NULL); - tcp_recv(_pcb, NULL); - tcp_err(_pcb, NULL); - tcp_poll(_pcb, NULL, 0); - } - if(tcp_close(_pcb) != ERR_OK) { - tcp_abort(_pcb); - } - _free_closed_slot(); - _pcb = NULL; - return ERR_OK; -} - -//In Async Thread -int8_t AsyncClient::_fin(tcp_pcb* pcb, int8_t err) { - _tcp_clear_events(this); - if(_discard_cb) { - _discard_cb(_discard_cb_arg, this); - } - return ERR_OK; -} - -int8_t AsyncClient::_sent(tcp_pcb* pcb, uint16_t len) { - _rx_last_packet = millis(); - _rx_last_ack = millis(); - //log_i("%u", len); - if(_sent_cb) { - _sent_cb(_sent_cb_arg, this, len, (millis() - _tx_last_packet)); - } - return ERR_OK; -} - -int8_t AsyncClient::_recv(tcp_pcb* pcb, pbuf* pb, int8_t err) { - while(pb != NULL) { - _rx_last_packet = millis(); - //we should not ack before we assimilate the data - _ack_pcb = true; - pbuf *b = pb; - pb = b->next; - b->next = NULL; - if(_pb_cb){ - _pb_cb(_pb_cb_arg, this, b); - } else { - if(_recv_cb) { - _recv_cb(_recv_cb_arg, this, b->payload, b->len); - } - if(!_ack_pcb) { - _rx_ack_len += b->len; - } else if(_pcb) { - _tcp_recved(_pcb, _closed_slot, b->len); - } - pbuf_free(b); - } - } - return ERR_OK; -} - -int8_t AsyncClient::_poll(tcp_pcb* pcb){ - if(!_pcb){ - log_w("pcb is NULL"); - return ERR_OK; - } - if(pcb != _pcb){ - log_e("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); - return ERR_OK; - } - - uint32_t now = millis(); - - // ACK Timeout - if(_ack_timeout){ - const uint32_t one_day = 86400000; - bool last_tx_is_after_last_ack = (_rx_last_ack - _tx_last_packet + one_day) < one_day; - if(last_tx_is_after_last_ack && (now - _tx_last_packet) >= _ack_timeout) { - log_w("ack timeout %d", pcb->state); - if(_timeout_cb) - _timeout_cb(_timeout_cb_arg, this, (now - _tx_last_packet)); - return ERR_OK; - } - } - // RX Timeout - if(_rx_timeout && (now - _rx_last_packet) >= (_rx_timeout * 1000)) { - log_w("rx timeout %d", pcb->state); - _close(); - return ERR_OK; - } - // Everything is fine - if(_poll_cb) { - _poll_cb(_poll_cb_arg, this); - } - return ERR_OK; -} - -void AsyncClient::_dns_found(struct ip_addr *ipaddr){ - if(ipaddr && IP_IS_V4(ipaddr)){ - connect(IPAddress(ip_addr_get_ip4_u32(ipaddr)), _connect_port); -#if LWIP_IPV6 - } else if(ipaddr && ipaddr->u_addr.ip6.addr){ - connect(IPv6Address(ipaddr->u_addr.ip6.addr), _connect_port); -#endif - } else { - if(_error_cb) { - _error_cb(_error_cb_arg, this, -55); - } - if(_discard_cb) { - _discard_cb(_discard_cb_arg, this); - } - } -} - -/* - * Public Helper Methods - * */ - -void AsyncClient::stop() { - close(false); -} - -bool AsyncClient::free(){ - if(!_pcb) { - return true; - } - if(_pcb->state == 0 || _pcb->state > 4) { - return true; - } - return false; -} - -size_t AsyncClient::write(const char* data) { - if(data == NULL) { - return 0; - } - return write(data, strlen(data)); -} - -size_t AsyncClient::write(const char* data, size_t size, uint8_t apiflags) { - size_t will_send = add(data, size, apiflags); - if(!will_send || !send()) { - return 0; - } - return will_send; -} - -void AsyncClient::setRxTimeout(uint32_t timeout){ - _rx_timeout = timeout; -} - -uint32_t AsyncClient::getRxTimeout(){ - return _rx_timeout; -} - -uint32_t AsyncClient::getAckTimeout(){ - return _ack_timeout; -} - -void AsyncClient::setAckTimeout(uint32_t timeout){ - _ack_timeout = timeout; -} - -void AsyncClient::setNoDelay(bool nodelay){ - if(!_pcb) { - return; - } - if(nodelay) { - tcp_nagle_disable(_pcb); - } else { - tcp_nagle_enable(_pcb); - } -} - -bool AsyncClient::getNoDelay(){ - if(!_pcb) { - return false; - } - return tcp_nagle_disabled(_pcb); -} - -uint16_t AsyncClient::getMss(){ - if(!_pcb) { - return 0; - } - return tcp_mss(_pcb); -} - -uint32_t AsyncClient::getRemoteAddress() { - if(!_pcb) { - return 0; - } -#if LWIP_IPV4 && LWIP_IPV6 - return _pcb->remote_ip.u_addr.ip4.addr; -#else - return _pcb->remote_ip.addr; -#endif -} - -#if LWIP_IPV6 -ip6_addr_t AsyncClient::getRemoteAddress6() { - if(!_pcb) { - ip6_addr_t nulladdr; - ip6_addr_set_zero(&nulladdr); - return nulladdr; - } - return _pcb->remote_ip.u_addr.ip6; -} - -ip6_addr_t AsyncClient::getLocalAddress6() { - if(!_pcb) { - ip6_addr_t nulladdr; - ip6_addr_set_zero(&nulladdr); - return nulladdr; - } - return _pcb->local_ip.u_addr.ip6; -} - -IPv6Address AsyncClient::remoteIP6() { - return IPv6Address(getRemoteAddress6().addr); -} - -IPv6Address AsyncClient::localIP6() { - return IPv6Address(getLocalAddress6().addr); -} -#endif - -uint16_t AsyncClient::getRemotePort() { - if(!_pcb) { - return 0; - } - return _pcb->remote_port; -} - -uint32_t AsyncClient::getLocalAddress() { - if(!_pcb) { - return 0; - } -#if LWIP_IPV4 && LWIP_IPV6 - return _pcb->local_ip.u_addr.ip4.addr; -#else - return _pcb->local_ip.addr; -#endif -} - -uint16_t AsyncClient::getLocalPort() { - if(!_pcb) { - return 0; - } - return _pcb->local_port; -} - -IPAddress AsyncClient::remoteIP() { - return IPAddress(getRemoteAddress()); -} - -uint16_t AsyncClient::remotePort() { - return getRemotePort(); -} - -IPAddress AsyncClient::localIP() { - return IPAddress(getLocalAddress()); -} - - -uint16_t AsyncClient::localPort() { - return getLocalPort(); -} - -uint8_t AsyncClient::state() { - if(!_pcb) { - return 0; - } - return _pcb->state; -} - -bool AsyncClient::connected(){ - if (!_pcb) { - return false; - } - return _pcb->state == 4; -} - -bool AsyncClient::connecting(){ - if (!_pcb) { - return false; - } - return _pcb->state > 0 && _pcb->state < 4; -} - -bool AsyncClient::disconnecting(){ - if (!_pcb) { - return false; - } - return _pcb->state > 4 && _pcb->state < 10; -} - -bool AsyncClient::disconnected(){ - if (!_pcb) { - return true; - } - return _pcb->state == 0 || _pcb->state == 10; -} - -bool AsyncClient::freeable(){ - if (!_pcb) { - return true; - } - return _pcb->state == 0 || _pcb->state > 4; -} - -bool AsyncClient::canSend(){ - return space() > 0; -} - -const char * AsyncClient::errorToString(int8_t error){ - switch(error){ - case ERR_OK: return "OK"; - case ERR_MEM: return "Out of memory error"; - case ERR_BUF: return "Buffer error"; - case ERR_TIMEOUT: return "Timeout"; - case ERR_RTE: return "Routing problem"; - case ERR_INPROGRESS: return "Operation in progress"; - case ERR_VAL: return "Illegal value"; - case ERR_WOULDBLOCK: return "Operation would block"; - case ERR_USE: return "Address in use"; - case ERR_ALREADY: return "Already connected"; - case ERR_CONN: return "Not connected"; - case ERR_IF: return "Low-level netif error"; - case ERR_ABRT: return "Connection aborted"; - case ERR_RST: return "Connection reset"; - case ERR_CLSD: return "Connection closed"; - case ERR_ARG: return "Illegal argument"; - case -55: return "DNS failed"; - default: return "UNKNOWN"; - } -} - -const char * AsyncClient::stateToString(){ - switch(state()){ - case 0: return "Closed"; - case 1: return "Listen"; - case 2: return "SYN Sent"; - case 3: return "SYN Received"; - case 4: return "Established"; - case 5: return "FIN Wait 1"; - case 6: return "FIN Wait 2"; - case 7: return "Close Wait"; - case 8: return "Closing"; - case 9: return "Last ACK"; - case 10: return "Time Wait"; - default: return "UNKNOWN"; - } -} - -/* - * Static Callbacks (LwIP C2C++ interconnect) - * */ - -void AsyncClient::_s_dns_found(const char * name, struct ip_addr * ipaddr, void * arg){ - reinterpret_cast(arg)->_dns_found(ipaddr); -} - -int8_t AsyncClient::_s_poll(void * arg, struct tcp_pcb * pcb) { - return reinterpret_cast(arg)->_poll(pcb); -} - -int8_t AsyncClient::_s_recv(void * arg, struct tcp_pcb * pcb, struct pbuf *pb, int8_t err) { - return reinterpret_cast(arg)->_recv(pcb, pb, err); -} - -int8_t AsyncClient::_s_fin(void * arg, struct tcp_pcb * pcb, int8_t err) { - return reinterpret_cast(arg)->_fin(pcb, err); -} - -int8_t AsyncClient::_s_lwip_fin(void * arg, struct tcp_pcb * pcb, int8_t err) { - return reinterpret_cast(arg)->_lwip_fin(pcb, err); -} - -int8_t AsyncClient::_s_sent(void * arg, struct tcp_pcb * pcb, uint16_t len) { - return reinterpret_cast(arg)->_sent(pcb, len); -} - -void AsyncClient::_s_error(void * arg, int8_t err) { - reinterpret_cast(arg)->_error(err); -} - -int8_t AsyncClient::_s_connected(void * arg, void * pcb, int8_t err){ - return reinterpret_cast(arg)->_connected(pcb, err); -} - -/* - Async TCP Server - */ - -AsyncServer::AsyncServer(IPAddress addr, uint16_t port) -: _port(port) -, _bind4(true) -, _addr(addr) -, _noDelay(false) -, _pcb(0) -, _connect_cb(0) -, _connect_cb_arg(0) -{} - -AsyncServer::AsyncServer(IPv6Address addr, uint16_t port) -: _port(port) -, _bind6(true) -, _addr6(addr) -, _noDelay(false) -, _pcb(0) -, _connect_cb(0) -, _connect_cb_arg(0) -{} - -AsyncServer::AsyncServer(uint16_t port) -: _port(port) -, _bind4(true) -, _bind6(true) -, _addr((uint32_t) IPADDR_ANY) -, _addr6() -, _noDelay(false) -, _pcb(0) -, _connect_cb(0) -, _connect_cb_arg(0) -{} - -AsyncServer::~AsyncServer(){ - end(); -} - -void AsyncServer::onClient(AcConnectHandler cb, void* arg){ - _connect_cb = cb; - _connect_cb_arg = arg; -} - -void AsyncServer::begin(){ - if(_pcb) { - return; - } - - if(!_start_async_task()){ - log_e("failed to start task"); - return; - } - int8_t err, bind_type; - - if(_bind4 && _bind6) { - bind_type = IPADDR_TYPE_ANY; - } else if (_bind6) { - bind_type = IPADDR_TYPE_V6; - } else { - bind_type = IPADDR_TYPE_V4; - } - - _pcb = tcp_new_ip_type(bind_type); - if (!_pcb){ - log_e("_pcb == NULL"); - return; - } - - ip_addr_t local_addr; - ip_addr_set_ip4_u32(&local_addr, _addr); -/* local_addr.type = bind_type; - local_addr.u_addr.ip4.addr = (uint32_t) _addr; - memcpy(local_addr.u_addr.ip6.addr, static_cast(_addr6), sizeof(uint32_t) * 4); */ - err = _tcp_bind(_pcb, &local_addr, _port); - - if (err != ERR_OK) { - _tcp_close(_pcb, -1); - log_e("bind error: %d", err); - return; - } - - static uint8_t backlog = 5; - _pcb = _tcp_listen_with_backlog(_pcb, backlog); - if (!_pcb) { - log_e("listen_pcb == NULL"); - return; - } - tcp_arg(_pcb, (void*) this); - tcp_accept(_pcb, &_s_accept); -} - -void AsyncServer::end(){ - if(_pcb){ - tcp_arg(_pcb, NULL); - tcp_accept(_pcb, NULL); - if(tcp_close(_pcb) != ERR_OK){ - _tcp_abort(_pcb, -1); - } - _pcb = NULL; - } -} - -//runs on LwIP thread -int8_t AsyncServer::_accept(tcp_pcb* pcb, int8_t err){ - //ets_printf("+A: 0x%08x\n", pcb); - if(_connect_cb){ - AsyncClient *c = new AsyncClient(pcb); - if(c){ - c->setNoDelay(_noDelay); - return _tcp_accept(this, c); - } - } - if(tcp_close(pcb) != ERR_OK){ - tcp_abort(pcb); - } - log_e("FAIL"); - return ERR_OK; -} - -int8_t AsyncServer::_accepted(AsyncClient* client){ - if(_connect_cb){ - _connect_cb(_connect_cb_arg, client); - } - return ERR_OK; -} - -void AsyncServer::setNoDelay(bool nodelay){ - _noDelay = nodelay; -} - -bool AsyncServer::getNoDelay(){ - return _noDelay; -} - -uint8_t AsyncServer::status(){ - if (!_pcb) { - return 0; - } - return _pcb->state; -} - -int8_t AsyncServer::_s_accept(void * arg, tcp_pcb * pcb, int8_t err){ - return reinterpret_cast(arg)->_accept(pcb, err); -} - -int8_t AsyncServer::_s_accepted(void *arg, AsyncClient* client){ - return reinterpret_cast(arg)->_accepted(client); -} diff --git a/lib/AsyncTCP-esphome/src/AsyncTCP.h b/lib/AsyncTCP-esphome/src/AsyncTCP.h deleted file mode 100644 index 32edaa9..0000000 --- a/lib/AsyncTCP-esphome/src/AsyncTCP.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef ASYNCTCP_H_ -#define ASYNCTCP_H_ - -#include "IPAddress.h" -#include "IPv6Address.h" -#include -#include "lwip/ip_addr.h" -#include "lwip/ip6_addr.h" - -#ifndef LIBRETINY -#include "sdkconfig.h" -extern "C" { - #include "freertos/semphr.h" - #include "lwip/pbuf.h" -} -#else -extern "C" { - #include - #include -} -#define CONFIG_ASYNC_TCP_RUNNING_CORE -1 //any available core -#define CONFIG_ASYNC_TCP_USE_WDT 0 -#endif - -//If core is not defined, then we are running in Arduino or PIO -#ifndef CONFIG_ASYNC_TCP_RUNNING_CORE -#define CONFIG_ASYNC_TCP_RUNNING_CORE -1 //any available core -#define CONFIG_ASYNC_TCP_USE_WDT 1 //if enabled, adds between 33us and 200us per event -#endif - -#ifndef CONFIG_ASYNC_TCP_STACK_SIZE -#define CONFIG_ASYNC_TCP_STACK_SIZE 8192 * 2 -#endif - -class AsyncClient; - -#define ASYNC_MAX_ACK_TIME 5000 -#define ASYNC_WRITE_FLAG_COPY 0x01 //will allocate new buffer to hold the data while sending (else will hold reference to the data given) -#define ASYNC_WRITE_FLAG_MORE 0x02 //will not send PSH flag, meaning that there should be more data to be sent before the application should react. - -typedef std::function AcConnectHandler; -typedef std::function AcAckHandler; -typedef std::function AcErrorHandler; -typedef std::function AcDataHandler; -typedef std::function AcPacketHandler; -typedef std::function AcTimeoutHandler; - -struct tcp_pcb; -struct ip_addr; - -class AsyncClient { - public: - AsyncClient(tcp_pcb* pcb = 0); - ~AsyncClient(); - - AsyncClient & operator=(const AsyncClient &other); - AsyncClient & operator+=(const AsyncClient &other); - - bool operator==(const AsyncClient &other); - - bool operator!=(const AsyncClient &other) { - return !(*this == other); - } - bool connect(IPAddress ip, uint16_t port); - bool connect(IPv6Address ip, uint16_t port); - bool connect(const char *host, uint16_t port); - void close(bool now = false); - void stop(); - int8_t abort(); - bool free(); - - bool canSend();//ack is not pending - size_t space();//space available in the TCP window - size_t add(const char* data, size_t size, uint8_t apiflags=ASYNC_WRITE_FLAG_COPY);//add for sending - bool send();//send all data added with the method above - - //write equals add()+send() - size_t write(const char* data); - size_t write(const char* data, size_t size, uint8_t apiflags=ASYNC_WRITE_FLAG_COPY); //only when canSend() == true - - uint8_t state(); - bool connecting(); - bool connected(); - bool disconnecting(); - bool disconnected(); - bool freeable();//disconnected or disconnecting - - uint16_t getMss(); - - uint32_t getRxTimeout(); - void setRxTimeout(uint32_t timeout);//no RX data timeout for the connection in seconds - - uint32_t getAckTimeout(); - void setAckTimeout(uint32_t timeout);//no ACK timeout for the last sent packet in milliseconds - - void setNoDelay(bool nodelay); - bool getNoDelay(); - - uint32_t getRemoteAddress(); - uint16_t getRemotePort(); - uint32_t getLocalAddress(); - uint16_t getLocalPort(); -#if LWIP_IPV6 - ip6_addr_t getRemoteAddress6(); - ip6_addr_t getLocalAddress6(); - IPv6Address remoteIP6(); - IPv6Address localIP6(); -#endif - - //compatibility - IPAddress remoteIP(); - uint16_t remotePort(); - IPAddress localIP(); - uint16_t localPort(); - - void onConnect(AcConnectHandler cb, void* arg = 0); //on successful connect - void onDisconnect(AcConnectHandler cb, void* arg = 0); //disconnected - void onAck(AcAckHandler cb, void* arg = 0); //ack received - void onError(AcErrorHandler cb, void* arg = 0); //unsuccessful connect or error - void onData(AcDataHandler cb, void* arg = 0); //data received (called if onPacket is not used) - void onPacket(AcPacketHandler cb, void* arg = 0); //data received - void onTimeout(AcTimeoutHandler cb, void* arg = 0); //ack timeout - void onPoll(AcConnectHandler cb, void* arg = 0); //every 125ms when connected - - void ackPacket(struct pbuf * pb);//ack pbuf from onPacket - size_t ack(size_t len); //ack data that you have not acked using the method below - void ackLater(){ _ack_pcb = false; } //will not ack the current packet. Call from onData - - const char * errorToString(int8_t error); - const char * stateToString(); - - //Do not use any of the functions below! - static int8_t _s_poll(void *arg, struct tcp_pcb *tpcb); - static int8_t _s_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, int8_t err); - static int8_t _s_fin(void *arg, struct tcp_pcb *tpcb, int8_t err); - static int8_t _s_lwip_fin(void *arg, struct tcp_pcb *tpcb, int8_t err); - static void _s_error(void *arg, int8_t err); - static int8_t _s_sent(void *arg, struct tcp_pcb *tpcb, uint16_t len); - static int8_t _s_connected(void* arg, void* tpcb, int8_t err); - static void _s_dns_found(const char *name, struct ip_addr *ipaddr, void *arg); - - int8_t _recv(tcp_pcb* pcb, pbuf* pb, int8_t err); - tcp_pcb * pcb(){ return _pcb; } - - protected: - bool _connect(ip_addr_t addr, uint16_t port); - - tcp_pcb* _pcb; - int8_t _closed_slot; - - AcConnectHandler _connect_cb; - void* _connect_cb_arg; - AcConnectHandler _discard_cb; - void* _discard_cb_arg; - AcAckHandler _sent_cb; - void* _sent_cb_arg; - AcErrorHandler _error_cb; - void* _error_cb_arg; - AcDataHandler _recv_cb; - void* _recv_cb_arg; - AcPacketHandler _pb_cb; - void* _pb_cb_arg; - AcTimeoutHandler _timeout_cb; - void* _timeout_cb_arg; - AcConnectHandler _poll_cb; - void* _poll_cb_arg; - - bool _ack_pcb; - uint32_t _tx_last_packet; - uint32_t _rx_ack_len; - uint32_t _rx_last_packet; - uint32_t _rx_timeout; - uint32_t _rx_last_ack; - uint32_t _ack_timeout; - uint16_t _connect_port; - - int8_t _close(); - void _free_closed_slot(); - void _allocate_closed_slot(); - int8_t _connected(void* pcb, int8_t err); - void _error(int8_t err); - int8_t _poll(tcp_pcb* pcb); - int8_t _sent(tcp_pcb* pcb, uint16_t len); - int8_t _fin(tcp_pcb* pcb, int8_t err); - int8_t _lwip_fin(tcp_pcb* pcb, int8_t err); - void _dns_found(struct ip_addr *ipaddr); - - public: - AsyncClient* prev; - AsyncClient* next; -}; - -class AsyncServer { - public: - AsyncServer(IPAddress addr, uint16_t port); - AsyncServer(IPv6Address addr, uint16_t port); - AsyncServer(uint16_t port); - ~AsyncServer(); - void onClient(AcConnectHandler cb, void* arg); - void begin(); - void end(); - void setNoDelay(bool nodelay); - bool getNoDelay(); - uint8_t status(); - - //Do not use any of the functions below! - static int8_t _s_accept(void *arg, tcp_pcb* newpcb, int8_t err); - static int8_t _s_accepted(void *arg, AsyncClient* client); - - protected: - uint16_t _port; - bool _bind4 = false; - bool _bind6 = false; - IPAddress _addr; - IPv6Address _addr6; - bool _noDelay; - tcp_pcb* _pcb; - AcConnectHandler _connect_cb; - void* _connect_cb_arg; - - int8_t _accept(tcp_pcb* newpcb, int8_t err); - int8_t _accepted(AsyncClient* client); -}; - - -#endif /* ASYNCTCP_H_ */ diff --git a/lib/AsyncTCP/.github/ISSUE_TEMPLATE/bug_report.md b/lib/AsyncTCP/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..8e2c31c --- /dev/null +++ b/lib/AsyncTCP/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: bug +assignees: '' + +--- + +**Please make sure to go through the recommendations before opening a bug report:** + +[https://github.com/mathieucarbou/AsyncTCP?tab=readme-ov-file#important-recommendations](https://github.com/mathieucarbou/AsyncTCP?tab=readme-ov-file#important-recommendations) + +**Description** + +A clear and concise description of what the bug is. + +**Board** + +esp32dev, esp32s3, etc + +**Ethernet adapter used ?** + +If yes, please specify which one + +**Stack trace** + +Please provide the stack trace here taken with `monitor_filters = esp32_exception_decoder`. +**Any issue opened with a non readable stack trace will be ignored because not helpful at all.** + +As an alternative, you can use [https://maximeborges.github.io/esp-stacktrace-decoder/](https://maximeborges.github.io/esp-stacktrace-decoder/). + +**Additional notes** + +Add any other context about the problem here. diff --git a/lib/AsyncTCP/.github/ISSUE_TEMPLATE/question.md b/lib/AsyncTCP/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..634179c --- /dev/null +++ b/lib/AsyncTCP/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,10 @@ +--- +name: Question +about: Describe your question +title: "[Q]" +labels: question +assignees: '' + +--- + + diff --git a/lib/AsyncTCP-esphome/.github/dependabot.yml b/lib/AsyncTCP/.github/dependabot.yml similarity index 100% rename from lib/AsyncTCP-esphome/.github/dependabot.yml rename to lib/AsyncTCP/.github/dependabot.yml diff --git a/lib/AsyncTCP/.github/scripts/install-arduino-core-esp32.sh b/lib/AsyncTCP/.github/scripts/install-arduino-core-esp32.sh deleted file mode 100755 index cf1026d..0000000 --- a/lib/AsyncTCP/.github/scripts/install-arduino-core-esp32.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash - -export ARDUINO_ESP32_PATH="$ARDUINO_USR_PATH/hardware/espressif/esp32" -if [ ! -d "$ARDUINO_ESP32_PATH" ]; then - echo "Installing ESP32 Arduino Core ..." - script_init_path="$PWD" - mkdir -p "$ARDUINO_USR_PATH/hardware/espressif" - cd "$ARDUINO_USR_PATH/hardware/espressif" - - echo "Installing Python Serial ..." - pip install pyserial > /dev/null - - if [ "$OS_IS_WINDOWS" == "1" ]; then - echo "Installing Python Requests ..." - pip install requests > /dev/null - fi - - if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then - echo "Linking Core..." - ln -s $GITHUB_WORKSPACE esp32 - else - echo "Cloning Core Repository..." - git clone https://github.com/espressif/arduino-esp32.git esp32 > /dev/null 2>&1 - fi - - echo "Updating Submodules ..." - cd esp32 - git submodule update --init --recursive > /dev/null 2>&1 - - echo "Installing Platform Tools ..." - cd tools && python get.py - cd $script_init_path - - echo "ESP32 Arduino has been installed in '$ARDUINO_ESP32_PATH'" - echo "" -fi diff --git a/lib/AsyncTCP/.github/scripts/install-arduino-ide.sh b/lib/AsyncTCP/.github/scripts/install-arduino-ide.sh deleted file mode 100755 index 7e268b1..0000000 --- a/lib/AsyncTCP/.github/scripts/install-arduino-ide.sh +++ /dev/null @@ -1,220 +0,0 @@ -#!/bin/bash - -#OSTYPE: 'linux-gnu', ARCH: 'x86_64' => linux64 -#OSTYPE: 'msys', ARCH: 'x86_64' => win32 -#OSTYPE: 'darwin18', ARCH: 'i386' => macos - -OSBITS=`arch` -if [[ "$OSTYPE" == "linux"* ]]; then - export OS_IS_LINUX="1" - ARCHIVE_FORMAT="tar.xz" - if [[ "$OSBITS" == "i686" ]]; then - OS_NAME="linux32" - elif [[ "$OSBITS" == "x86_64" ]]; then - OS_NAME="linux64" - elif [[ "$OSBITS" == "armv7l" || "$OSBITS" == "aarch64" ]]; then - OS_NAME="linuxarm" - else - OS_NAME="$OSTYPE-$OSBITS" - echo "Unknown OS '$OS_NAME'" - exit 1 - fi -elif [[ "$OSTYPE" == "darwin"* ]]; then - export OS_IS_MACOS="1" - ARCHIVE_FORMAT="zip" - OS_NAME="macosx" -elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then - export OS_IS_WINDOWS="1" - ARCHIVE_FORMAT="zip" - OS_NAME="windows" -else - OS_NAME="$OSTYPE-$OSBITS" - echo "Unknown OS '$OS_NAME'" - exit 1 -fi -export OS_NAME - -ARDUINO_BUILD_DIR="$HOME/.arduino/build.tmp" -ARDUINO_CACHE_DIR="$HOME/.arduino/cache.tmp" - -if [ "$OS_IS_MACOS" == "1" ]; then - export ARDUINO_IDE_PATH="/Applications/Arduino.app/Contents/Java" - export ARDUINO_USR_PATH="$HOME/Documents/Arduino" -elif [ "$OS_IS_WINDOWS" == "1" ]; then - export ARDUINO_IDE_PATH="$HOME/arduino_ide" - export ARDUINO_USR_PATH="$HOME/Documents/Arduino" -else - export ARDUINO_IDE_PATH="$HOME/arduino_ide" - export ARDUINO_USR_PATH="$HOME/Arduino" -fi - -if [ ! -d "$ARDUINO_IDE_PATH" ]; then - echo "Installing Arduino IDE on $OS_NAME ..." - echo "Downloading 'arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT' to 'arduino.$ARCHIVE_FORMAT' ..." - if [ "$OS_IS_LINUX" == "1" ]; then - wget -O "arduino.$ARCHIVE_FORMAT" "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1 - echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..." - tar xf "arduino.$ARCHIVE_FORMAT" > /dev/null - mv arduino-nightly "$ARDUINO_IDE_PATH" - else - curl -o "arduino.$ARCHIVE_FORMAT" -L "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1 - echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..." - unzip "arduino.$ARCHIVE_FORMAT" > /dev/null - if [ "$OS_IS_MACOS" == "1" ]; then - mv "Arduino.app" "/Applications/Arduino.app" - else - mv arduino-nightly "$ARDUINO_IDE_PATH" - fi - fi - rm -rf "arduino.$ARCHIVE_FORMAT" - - mkdir -p "$ARDUINO_USR_PATH/libraries" - mkdir -p "$ARDUINO_USR_PATH/hardware" - - echo "Arduino IDE Installed in '$ARDUINO_IDE_PATH'" - echo "" -fi - -function build_sketch(){ # build_sketch [extra-options] - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_sketch [extra-options]" - return 1 - fi - - local fqbn="$1" - local sketch="$2" - local xtra_opts="$3" - local win_opts="" - if [ "$OS_IS_WINDOWS" == "1" ]; then - local ctags_version=`ls "$ARDUINO_IDE_PATH/tools-builder/ctags/"` - local preprocessor_version=`ls "$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/"` - win_opts="-prefs=runtime.tools.ctags.path=$ARDUINO_IDE_PATH/tools-builder/ctags/$ctags_version -prefs=runtime.tools.arduino-preprocessor.path=$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/$preprocessor_version" - fi - - echo "" - echo "Compiling '"$(basename "$sketch")"' ..." - mkdir -p "$ARDUINO_BUILD_DIR" - mkdir -p "$ARDUINO_CACHE_DIR" - $ARDUINO_IDE_PATH/arduino-builder -compile -logger=human -core-api-version=10810 \ - -fqbn=$fqbn \ - -warnings="all" \ - -tools "$ARDUINO_IDE_PATH/tools-builder" \ - -tools "$ARDUINO_IDE_PATH/tools" \ - -built-in-libraries "$ARDUINO_IDE_PATH/libraries" \ - -hardware "$ARDUINO_IDE_PATH/hardware" \ - -hardware "$ARDUINO_USR_PATH/hardware" \ - -libraries "$ARDUINO_USR_PATH/libraries" \ - -build-cache "$ARDUINO_CACHE_DIR" \ - -build-path "$ARDUINO_BUILD_DIR" \ - $win_opts $xtra_opts "$sketch" -} - -function count_sketches() # count_sketches -{ - local examples="$1" - rm -rf sketches.txt - if [ ! -d "$examples" ]; then - touch sketches.txt - return 0 - fi - local sketches=$(find $examples -name *.ino) - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then - continue - fi; - if [[ -f "$sketchdir/.test.skip" ]]; then - continue - fi - echo $sketch >> sketches.txt - sketchnum=$(($sketchnum + 1)) - done - return $sketchnum -} - -function build_sketches() # build_sketches [extra-options] -{ - local fqbn=$1 - local examples=$2 - local chunk_idex=$3 - local chunks_num=$4 - local xtra_opts=$5 - - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_sketches [ ] [extra-options]" - return 1 - fi - - if [ "$#" -lt 4 ]; then - chunk_idex="0" - chunks_num="1" - xtra_opts=$3 - fi - - if [ "$chunks_num" -le 0 ]; then - echo "ERROR: Chunks count must be positive number" - return 1 - fi - if [ "$chunk_idex" -ge "$chunks_num" ]; then - echo "ERROR: Chunk index must be less than chunks count" - return 1 - fi - - set +e - count_sketches "$examples" - local sketchcount=$? - set -e - local sketches=$(cat sketches.txt) - rm -rf sketches.txt - - local chunk_size=$(( $sketchcount / $chunks_num )) - local all_chunks=$(( $chunks_num * $chunk_size )) - if [ "$all_chunks" -lt "$sketchcount" ]; then - chunk_size=$(( $chunk_size + 1 )) - fi - - local start_index=$(( $chunk_idex * $chunk_size )) - if [ "$sketchcount" -le "$start_index" ]; then - echo "Skipping job" - return 0 - fi - - local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) - if [ "$end_index" -gt "$sketchcount" ]; then - end_index=$sketchcount - fi - - local start_num=$(( $start_index + 1 )) - echo "Found $sketchcount Sketches"; - echo "Chunk Count : $chunks_num" - echo "Chunk Size : $chunk_size" - echo "Start Sketch: $start_num" - echo "End Sketch : $end_index" - - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [ "${sketchdirname}.ino" != "$sketchname" ] \ - || [ -f "$sketchdir/.test.skip" ]; then - continue - fi - sketchnum=$(($sketchnum + 1)) - if [ "$sketchnum" -le "$start_index" ] \ - || [ "$sketchnum" -gt "$end_index" ]; then - continue - fi - build_sketch "$fqbn" "$sketch" "$xtra_opts" - local result=$? - if [ $result -ne 0 ]; then - return $result - fi - done - return 0 -} diff --git a/lib/AsyncTCP/.github/scripts/install-platformio.sh b/lib/AsyncTCP/.github/scripts/install-platformio.sh deleted file mode 100644 index 61c94fe..0000000 --- a/lib/AsyncTCP/.github/scripts/install-platformio.sh +++ /dev/null @@ -1,133 +0,0 @@ -#!/bin/bash - -echo "Installing Python Wheel ..." -pip install wheel > /dev/null 2>&1 - -echo "Installing PlatformIO ..." -pip install -U platformio > /dev/null 2>&1 - -echo "PlatformIO has been installed" -echo "" - - -function build_pio_sketch(){ # build_pio_sketch - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_pio_sketch " - return 1 - fi - - local board="$1" - local sketch="$2" - local sketch_dir=$(dirname "$sketch") - echo "" - echo "Compiling '"$(basename "$sketch")"' ..." - python -m platformio ci -l '.' --board "$board" "$sketch_dir" --project-option="board_build.partitions = huge_app.csv" -} - -function count_sketches() # count_sketches -{ - local examples="$1" - rm -rf sketches.txt - if [ ! -d "$examples" ]; then - touch sketches.txt - return 0 - fi - local sketches=$(find $examples -name *.ino) - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then - continue - fi; - if [[ -f "$sketchdir/.test.skip" ]]; then - continue - fi - echo $sketch >> sketches.txt - sketchnum=$(($sketchnum + 1)) - done - return $sketchnum -} - -function build_pio_sketches() # build_pio_sketches -{ - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_pio_sketches [ ]" - return 1 - fi - - local board=$1 - local examples=$2 - local chunk_idex=$3 - local chunks_num=$4 - - if [ "$#" -lt 4 ]; then - chunk_idex="0" - chunks_num="1" - fi - - if [ "$chunks_num" -le 0 ]; then - echo "ERROR: Chunks count must be positive number" - return 1 - fi - if [ "$chunk_idex" -ge "$chunks_num" ]; then - echo "ERROR: Chunk index must be less than chunks count" - return 1 - fi - - set +e - count_sketches "$examples" - local sketchcount=$? - set -e - local sketches=$(cat sketches.txt) - rm -rf sketches.txt - - local chunk_size=$(( $sketchcount / $chunks_num )) - local all_chunks=$(( $chunks_num * $chunk_size )) - if [ "$all_chunks" -lt "$sketchcount" ]; then - chunk_size=$(( $chunk_size + 1 )) - fi - - local start_index=$(( $chunk_idex * $chunk_size )) - if [ "$sketchcount" -le "$start_index" ]; then - echo "Skipping job" - return 0 - fi - - local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) - if [ "$end_index" -gt "$sketchcount" ]; then - end_index=$sketchcount - fi - - local start_num=$(( $start_index + 1 )) - echo "Found $sketchcount Sketches"; - echo "Chunk Count : $chunks_num" - echo "Chunk Size : $chunk_size" - echo "Start Sketch: $start_num" - echo "End Sketch : $end_index" - - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [ "${sketchdirname}.ino" != "$sketchname" ] \ - || [ -f "$sketchdir/.test.skip" ]; then - continue - fi - sketchnum=$(($sketchnum + 1)) - if [ "$sketchnum" -le "$start_index" ] \ - || [ "$sketchnum" -gt "$end_index" ]; then - continue - fi - build_pio_sketch "$board" "$sketch" - local result=$? - if [ $result -ne 0 ]; then - return $result - fi - done - return 0 -} diff --git a/lib/AsyncTCP/.github/scripts/on-push.sh b/lib/AsyncTCP/.github/scripts/on-push.sh deleted file mode 100755 index ece5d7a..0000000 --- a/lib/AsyncTCP/.github/scripts/on-push.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/bin/bash - -set -e - -if [ ! -z "$TRAVIS_BUILD_DIR" ]; then - export GITHUB_WORKSPACE="$TRAVIS_BUILD_DIR" - export GITHUB_REPOSITORY="$TRAVIS_REPO_SLUG" -elif [ -z "$GITHUB_WORKSPACE" ]; then - export GITHUB_WORKSPACE="$PWD" - export GITHUB_REPOSITORY="me-no-dev/AsyncTCP" -fi - -CHUNK_INDEX=$1 -CHUNKS_CNT=$2 -BUILD_PIO=0 -if [ "$#" -lt 2 ] || [ "$CHUNKS_CNT" -le 0 ]; then - CHUNK_INDEX=0 - CHUNKS_CNT=1 -elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ]; then - CHUNK_INDEX=$CHUNKS_CNT -elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then - BUILD_PIO=1 -fi - -if [ "$BUILD_PIO" -eq 0 ]; then - # ArduinoIDE Test - source ./.github/scripts/install-arduino-ide.sh - source ./.github/scripts/install-arduino-core-esp32.sh - - echo "Installing AsyncTCP ..." - cp -rf "$GITHUB_WORKSPACE" "$ARDUINO_USR_PATH/libraries/AsyncTCP" - - FQBN="espressif:esp32:esp32:PSRAM=enabled,PartitionScheme=huge_app" - build_sketches "$FQBN" "$GITHUB_WORKSPACE/examples" - if [ ! "$OS_IS_WINDOWS" == "1" ]; then - echo "Installing ESPAsyncWebServer ..." - git clone https://github.com/me-no-dev/ESPAsyncWebServer "$ARDUINO_USR_PATH/libraries/ESPAsyncWebServer" > /dev/null 2>&1 - - echo "Installing ArduinoJson ..." - git clone https://github.com/bblanchon/ArduinoJson "$ARDUINO_USR_PATH/libraries/ArduinoJson" > /dev/null 2>&1 - - build_sketches "$FQBN" "$ARDUINO_USR_PATH/libraries/ESPAsyncWebServer/examples" - fi -else - # PlatformIO Test - source ./.github/scripts/install-platformio.sh - - echo "Installing AsyncTCP ..." - python -m platformio lib --storage-dir "$GITHUB_WORKSPACE" install - - BOARD="esp32dev" - build_pio_sketches "$BOARD" "$GITHUB_WORKSPACE/examples" - - if [[ "$OSTYPE" != "cygwin" ]] && [[ "$OSTYPE" != "msys" ]] && [[ "$OSTYPE" != "win32" ]]; then - echo "Installing ESPAsyncWebServer ..." - python -m platformio lib -g install https://github.com/me-no-dev/ESPAsyncWebServer.git > /dev/null 2>&1 - git clone https://github.com/me-no-dev/ESPAsyncWebServer "$HOME/ESPAsyncWebServer" > /dev/null 2>&1 - - echo "Installing ArduinoJson ..." - python -m platformio lib -g install https://github.com/bblanchon/ArduinoJson.git > /dev/null 2>&1 - - build_pio_sketches "$BOARD" "$HOME/ESPAsyncWebServer/examples" - fi -fi diff --git a/lib/AsyncTCP/.github/workflows/push.yml b/lib/AsyncTCP/.github/workflows/push.yml index 15cd441..7e275f5 100644 --- a/lib/AsyncTCP/.github/workflows/push.yml +++ b/lib/AsyncTCP/.github/workflows/push.yml @@ -2,31 +2,51 @@ name: Async TCP CI on: push: - branches: - - master - - release/* pull_request: + workflow_dispatch: jobs: - build-arduino: - name: Arduino on ${{ matrix.os }} - runs-on: ${{ matrix.os }} + name: ${{ matrix.config }} + runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - os: [ubuntu-latest, macOS-latest] + config: [arduino-cli.yaml, arduino-cli-dev.yaml] steps: - - uses: actions/checkout@v1 - - name: Build Tests - run: bash ./.github/scripts/on-push.sh 0 1 + - uses: actions/checkout@v4 + - uses: arduino/setup-arduino-cli@v1 + - name: Download board + run: | + arduino-cli --config-file ${{ matrix.config }} core update-index + arduino-cli --config-file ${{ matrix.config }} board listall + arduino-cli --config-file ${{ matrix.config }} core install esp32:esp32 + - name: Compile Sketch + run: arduino-cli --config-file ${{ matrix.config }} --library ./src/ compile --fqbn esp32:esp32:esp32 ./examples/ClientServer/Client/Client.ino + - name: Compile Sketch with IPv6 + env: + LWIP_IPV6: true + run: arduino-cli --config-file ${{ matrix.config }} --library ./src/ compile --fqbn esp32:esp32:esp32 ./examples/ClientServer/Client/Client.ino build-pio: - name: PlatformIO on ${{ matrix.os }} - runs-on: ${{ matrix.os }} + name: ${{ matrix.board }} ${{ matrix.env }} + runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - os: [ubuntu-latest, macOS-latest] + board: [esp32dev, esp32-s3-devkitc-1] + env: [arduino-2, arduino-3] steps: - - uses: actions/checkout@v1 - - name: Build Tests - run: bash ./.github/scripts/on-push.sh 1 1 + - uses: actions/checkout@v4 + - uses: actions/cache@v4 + with: + path: | + ~/.platformio + ~/.cache/pip + key: ${{ matrix.env }} + - uses: actions/setup-python@v5 + with: + python-version: "3.x" + - run: pip install platformio + - run: sed -i -e 's/esp32dev/${{ matrix.board }}/g' platformio.ini + - run: pio run -e ${{ matrix.env }} diff --git a/lib/AsyncTCP/.gitignore b/lib/AsyncTCP/.gitignore index 9bea433..4ac15a4 100644 --- a/lib/AsyncTCP/.gitignore +++ b/lib/AsyncTCP/.gitignore @@ -1,2 +1,6 @@ - .DS_Store +.lh +/.pio +/.vscode/* +!/.vscode/settings.json +/logs diff --git a/lib/AsyncTCP/.travis.yml b/lib/AsyncTCP/.travis.yml deleted file mode 100644 index dbfc064..0000000 --- a/lib/AsyncTCP/.travis.yml +++ /dev/null @@ -1,34 +0,0 @@ -sudo: false -language: python -os: - - linux - -git: - depth: false - -stages: - - build - -jobs: - include: - - - name: "Arduino Build" - if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) - stage: build - script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh - - - name: "PlatformIO Build" - if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) - stage: build - script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 1 1 - -notifications: - email: - on_success: change - on_failure: change - webhooks: - urls: - - https://webhooks.gitter.im/e/60e65d0c78ea0a920347 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: false # default: false diff --git a/lib/AsyncTCP/README.md b/lib/AsyncTCP/README.md index 983aabd..fc76b63 100644 --- a/lib/AsyncTCP/README.md +++ b/lib/AsyncTCP/README.md @@ -1,13 +1,52 @@ -# AsyncTCP -[![Build Status](https://travis-ci.org/me-no-dev/AsyncTCP.svg?branch=master)](https://travis-ci.org/me-no-dev/AsyncTCP) ![](https://github.com/me-no-dev/AsyncTCP/workflows/Async%20TCP%20CI/badge.svg) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/2f7e4d1df8b446d192cbfec6dc174d2d)](https://www.codacy.com/manual/me-no-dev/AsyncTCP?utm_source=github.com&utm_medium=referral&utm_content=me-no-dev/AsyncTCP&utm_campaign=Badge_Grade) +# AsyncTCP + +[![License: LGPL 3.0](https://img.shields.io/badge/License-LGPL%203.0-yellow.svg)](https://opensource.org/license/lgpl-3-0/) +[![Continuous Integration](https://github.com/mathieucarbou/AsyncTCP/actions/workflows/push.yml/badge.svg)](https://github.com/mathieucarbou/AsyncTCP/actions/workflows/push.yml) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/Async%20TCP.svg)](https://registry.platformio.org/libraries/mathieucarbou/Async%20TCP) + +A fork of the [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) library by [@me-no-dev](https://github.com/me-no-dev) for [ESPHome](https://esphome.io). ### Async TCP Library for ESP32 Arduino -[![Join the chat at https://gitter.im/me-no-dev/ESPAsyncWebServer](https://badges.gitter.im/me-no-dev/ESPAsyncWebServer.svg)](https://gitter.im/me-no-dev/ESPAsyncWebServer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - This is a fully asynchronous TCP library, aimed at enabling trouble-free, multi-connection network environment for Espressif's ESP32 MCUs. -This library is the base for [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) +This library is the base for [ESPAsyncWebServer](https://github.com/mathieucarbou/ESPAsyncWebServer) ## AsyncClient and AsyncServer + The base classes on which everything else is built. They expose all possible scenarios, but are really raw and require more skills to use. + +## Changes in this fork + +- All improvements from [ESPHome fork](https://github.com/esphome/AsyncTCP) +- Reverted back `library.properties` for Arduino IDE users +- Arduino 3 / ESP-IDF 5 compatibility +- Changed lib name: `AsyncTCP` -> `Async TCP` +- Point to `mathieucarbou/Async TCP @ ^3.1.4` +- IPv6 support + +## Important recommendations + +Most of the crashes are caused by improper configuration of the library for the project. +Here are some recommendations to avoid them. + +1. Set the running core to be on the same core of your application (usually core 1) `-D CONFIG_ASYNC_TCP_RUNNING_CORE=1` +2. Set the stack size appropriately with `-D CONFIG_ASYNC_TCP_STACK_SIZE=16384`. + The default value of `16384` might be too much for your project. + You can look at the [MycilaTaskMonitor](https://oss.carbou.me/MycilaTaskMonitor) project to monitor the stack usage. +3. You can change **if you know what you are doing** the task priority with `-D CONFIG_ASYNC_TCP_PRIORITY=10`. + Default is `10`. +4. You can increase the queue size with `-D CONFIG_ASYNC_TCP_QUEUE_SIZE=128`. + Default is `64`. +5. You can decrease the maximum ack time `-D CONFIG_ASYNC_TCP_MAX_ACK_TIME=3000`. + Default is `5000`. + +I personally use the following configuration in my projects: + +```c++ + -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=3000 + -D CONFIG_ASYNC_TCP_PRIORITY=10 + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 +``` diff --git a/lib/AsyncTCP/arduino-cli-dev.yaml b/lib/AsyncTCP/arduino-cli-dev.yaml new file mode 100644 index 0000000..174df7a --- /dev/null +++ b/lib/AsyncTCP/arduino-cli-dev.yaml @@ -0,0 +1,25 @@ +board_manager: + additional_urls: + - https://espressif.github.io/arduino-esp32/package_esp32_dev_index.json +directories: + builtin.libraries: ./src/ +build_cache: + compilations_before_purge: 10 + ttl: 720h0m0s +daemon: + port: "50051" +library: + enable_unsafe_install: false +logging: + file: "" + format: text + level: info +metrics: + addr: :9090 + enabled: true +output: + no_color: false +sketch: + always_export_binaries: false +updater: + enable_notification: true diff --git a/lib/AsyncTCP-esphome/arduino-cli.yaml b/lib/AsyncTCP/arduino-cli.yaml similarity index 100% rename from lib/AsyncTCP-esphome/arduino-cli.yaml rename to lib/AsyncTCP/arduino-cli.yaml diff --git a/lib/AsyncTCP-esphome/examples/ClientServer/Client/Client.ino b/lib/AsyncTCP/examples/ClientServer/Client/Client.ino similarity index 100% rename from lib/AsyncTCP-esphome/examples/ClientServer/Client/Client.ino rename to lib/AsyncTCP/examples/ClientServer/Client/Client.ino diff --git a/lib/AsyncTCP-esphome/examples/ClientServer/Client/config.h b/lib/AsyncTCP/examples/ClientServer/Client/config.h similarity index 100% rename from lib/AsyncTCP-esphome/examples/ClientServer/Client/config.h rename to lib/AsyncTCP/examples/ClientServer/Client/config.h diff --git a/lib/AsyncTCP/library.json b/lib/AsyncTCP/library.json index 89f90e4..8a8c569 100644 --- a/lib/AsyncTCP/library.json +++ b/lib/AsyncTCP/library.json @@ -1,22 +1,38 @@ { - "name":"AsyncTCP", - "description":"Asynchronous TCP Library for ESP32", - "keywords":"async,tcp", - "authors": - { - "name": "Hristo Gochkov", - "maintainer": true - }, - "repository": - { + "name": "Async TCP", + "version": "3.1.4", + "description": "Asynchronous TCP Library for ESP32", + "keywords": "async,tcp", + "repository": { "type": "git", - "url": "https://github.com/me-no-dev/AsyncTCP.git" + "url": "https://github.com/mathieucarbou/AsyncTCP.git" }, - "version": "1.1.1", + "authors": [ + { + "name": "Hristo Gochkov" + }, + { + "name": "Mathieu Carbou", + "maintainer": true + } + ], "license": "LGPL-3.0", "frameworks": "arduino", - "platforms": "espressif32", + "platforms": [ + "espressif32", + "libretiny" + ], "build": { "libCompatMode": 2 - } -} + }, + "export": { + "include": [ + "examples", + "src", + "library.json", + "library.properties", + "LICENSE", + "README.md" + ] + } +} \ No newline at end of file diff --git a/lib/AsyncTCP/library.properties b/lib/AsyncTCP/library.properties index eb4e26e..9818aba 100644 --- a/lib/AsyncTCP/library.properties +++ b/lib/AsyncTCP/library.properties @@ -1,9 +1,9 @@ -name=AsyncTCP -version=1.1.1 +name=Async TCP +version=3.1.4 author=Me-No-Dev -maintainer=Me-No-Dev +maintainer=Mathieu Carbou sentence=Async TCP Library for ESP32 paragraph=Async TCP Library for ESP32 category=Other -url=https://github.com/me-no-dev/AsyncTCP +url=https://github.com/mathieucarbou/AsyncTCP.git architectures=* diff --git a/lib/AsyncTCP/platformio.ini b/lib/AsyncTCP/platformio.ini new file mode 100644 index 0000000..f96351b --- /dev/null +++ b/lib/AsyncTCP/platformio.ini @@ -0,0 +1,28 @@ +[env] +framework = arduino +build_flags = + -Wall -Wextra + -D CONFIG_ARDUHAL_LOG_COLORS + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG +upload_protocol = esptool +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder, log2file + +[platformio] +lib_dir = . +src_dir = examples/ClientServer/Client + +[env:arduino] +platform = espressif32 +board = esp32dev + +[env:arduino-2] +platform = espressif32@6.7.0 +board = esp32dev + +[env:arduino-3] +platform = espressif32 +platform_packages= + platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.2 + platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.2/esp32-arduino-libs-3.0.2.zip +board = esp32dev diff --git a/lib/AsyncTCP/src/AsyncTCP.cpp b/lib/AsyncTCP/src/AsyncTCP.cpp index 89ff6ee..135ba8c 100644 --- a/lib/AsyncTCP/src/AsyncTCP.cpp +++ b/lib/AsyncTCP/src/AsyncTCP.cpp @@ -29,7 +29,9 @@ extern "C"{ #include "lwip/dns.h" #include "lwip/err.h" } +#if CONFIG_ASYNC_TCP_USE_WDT #include "esp_task_wdt.h" +#endif /* * TCP/IP Event Task @@ -44,7 +46,7 @@ typedef struct { void *arg; union { struct { - void * pcb; + tcp_pcb * pcb; int8_t err; } connected; struct { @@ -76,7 +78,7 @@ typedef struct { }; } lwip_event_packet_t; -static xQueueHandle _async_queue; +static QueueHandle_t _async_queue; static TaskHandle_t _async_service_task_handle = NULL; @@ -95,7 +97,7 @@ static uint32_t _closed_index = []() { static inline bool _init_async_event_queue(){ if(!_async_queue){ - _async_queue = xQueueCreate(32, sizeof(lwip_event_packet_t *)); + _async_queue = xQueueCreate(CONFIG_ASYNC_TCP_QUEUE_SIZE, sizeof(lwip_event_packet_t *)); if(!_async_queue){ return false; } @@ -213,12 +215,32 @@ static void _stop_async_task(){ } } */ + +static bool customTaskCreateUniversal( + TaskFunction_t pxTaskCode, + const char * const pcName, + const uint32_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + const BaseType_t xCoreID) { +#ifndef CONFIG_FREERTOS_UNICORE + if(xCoreID >= 0 && xCoreID < 2) { + return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); + } else { +#endif + return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); +#ifndef CONFIG_FREERTOS_UNICORE + } +#endif +} + static bool _start_async_task(){ if(!_init_async_event_queue()){ return false; } if(!_async_service_task_handle){ - xTaskCreateUniversal(_async_service_task, "async_tcp", 8192 * 2, NULL, 3, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE); + customTaskCreateUniversal(_async_service_task, "async_tcp", CONFIG_ASYNC_TCP_STACK_SIZE, NULL, CONFIG_ASYNC_TCP_PRIORITY, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE); if(!_async_service_task_handle){ return false; } @@ -555,12 +577,11 @@ AsyncClient::AsyncClient(tcp_pcb* pcb) , _pb_cb_arg(0) , _timeout_cb(0) , _timeout_cb_arg(0) -, _pcb_busy(false) -, _pcb_sent_at(0) , _ack_pcb(true) -, _rx_last_packet(0) -, _rx_since_timeout(0) -, _ack_timeout(ASYNC_MAX_ACK_TIME) +, _tx_last_packet(0) +, _rx_timeout(0) +, _rx_last_ack(0) +, _ack_timeout(CONFIG_ASYNC_TCP_MAX_ACK_TIME) , _connect_port(0) , prev(NULL) , next(NULL) @@ -568,13 +589,15 @@ AsyncClient::AsyncClient(tcp_pcb* pcb) _pcb = pcb; _closed_slot = -1; if(_pcb){ - _allocate_closed_slot(); _rx_last_packet = millis(); tcp_arg(_pcb, this); tcp_recv(_pcb, &_tcp_recv); tcp_sent(_pcb, &_tcp_sent); tcp_err(_pcb, &_tcp_error); tcp_poll(_pcb, &_tcp_poll, 1); + if(!_allocate_closed_slot()) { + _close(); + } } } @@ -674,9 +697,9 @@ void AsyncClient::onPoll(AcConnectHandler cb, void* arg){ * Main Public Methods * */ -bool AsyncClient::connect(IPAddress ip, uint16_t port){ +bool AsyncClient::_connect(ip_addr_t addr, uint16_t port){ if (_pcb){ - log_w("already connected, state %d", _pcb->state); + log_d("already connected, state %d", _pcb->state); return false; } if(!_start_async_task()){ @@ -684,11 +707,12 @@ bool AsyncClient::connect(IPAddress ip, uint16_t port){ return false; } - ip_addr_t addr; - addr.type = IPADDR_TYPE_V4; - addr.u_addr.ip4.addr = ip; + if(!_allocate_closed_slot()) { + log_e("failed to allocate: closed slot full"); + return false; + } - tcp_pcb* pcb = tcp_new_ip_type(IPADDR_TYPE_V4); + tcp_pcb* pcb = tcp_new_ip_type(addr.type); if (!pcb){ log_e("pcb == NULL"); return false; @@ -699,27 +723,59 @@ bool AsyncClient::connect(IPAddress ip, uint16_t port){ tcp_recv(pcb, &_tcp_recv); tcp_sent(pcb, &_tcp_sent); tcp_poll(pcb, &_tcp_poll, 1); - //_tcp_connect(pcb, &addr, port,(tcp_connected_fn)&_s_connected); _tcp_connect(pcb, _closed_slot, &addr, port,(tcp_connected_fn)&_tcp_connected); return true; } +bool AsyncClient::connect(const IPAddress& ip, uint16_t port){ + ip_addr_t addr; +#if ESP_IDF_VERSION_MAJOR < 5 + addr.u_addr.ip4.addr = ip; + addr.type = IPADDR_TYPE_V4; +#else + ip.to_ip_addr_t(&addr); +#endif + + return _connect(addr, port); +} + +#if LWIP_IPV6 && ESP_IDF_VERSION_MAJOR < 5 +bool AsyncClient::connect(const IPv6Address& ip, uint16_t port){ + ip_addr_t addr; + addr.type = IPADDR_TYPE_V6; + memcpy(addr.u_addr.ip6.addr, static_cast(ip), sizeof(uint32_t) * 4); + + return _connect(addr, port); +} +#endif + bool AsyncClient::connect(const char* host, uint16_t port){ ip_addr_t addr; - + if(!_start_async_task()){ log_e("failed to start task"); return false; } - + err_t err = dns_gethostbyname(host, &addr, (dns_found_callback)&_tcp_dns_found, this); if(err == ERR_OK) { +#if ESP_IDF_VERSION_MAJOR < 5 +#if LWIP_IPV6 + if(addr.type == IPADDR_TYPE_V6) { + return connect(IPv6Address(addr.u_addr.ip6.addr), port); + } return connect(IPAddress(addr.u_addr.ip4.addr), port); +#else + return connect(IPAddress(addr.addr), port); +#endif +#else + return _connect(addr, port); +#endif } else if(err == ERR_INPROGRESS) { _connect_port = port; return true; } - log_e("error: %d", err); + log_d("error: %d", err); return false; } @@ -763,13 +819,12 @@ size_t AsyncClient::add(const char* data, size_t size, uint8_t apiflags) { } bool AsyncClient::send(){ - int8_t err = ERR_OK; - err = _tcp_output(_pcb, _closed_slot); - if(err == ERR_OK){ - _pcb_busy = true; - _pcb_sent_at = millis(); + auto backup = _tx_last_packet; + _tx_last_packet = millis(); + if (_tcp_output(_pcb, _closed_slot) == ERR_OK) { return true; } + _tx_last_packet = backup; return false; } @@ -799,7 +854,6 @@ int8_t AsyncClient::_close(){ //ets_printf("X: 0x%08x\n", (uint32_t)this); int8_t err = ERR_OK; if(_pcb) { - //log_i(""); tcp_arg(_pcb, NULL); tcp_sent(_pcb, NULL); tcp_recv(_pcb, NULL); @@ -810,6 +864,7 @@ int8_t AsyncClient::_close(){ if(err != ERR_OK) { err = abort(); } + _free_closed_slot(); _pcb = NULL; if(_discard_cb) { _discard_cb(_discard_cb_arg, this); @@ -818,7 +873,10 @@ int8_t AsyncClient::_close(){ return err; } -void AsyncClient::_allocate_closed_slot(){ +bool AsyncClient::_allocate_closed_slot(){ + if (_closed_slot != -1) { + return true; + } xSemaphoreTake(_slots_lock, portMAX_DELAY); uint32_t closed_slot_min_index = 0; for (int i = 0; i < _number_of_closed_slots; ++ i) { @@ -831,28 +889,27 @@ void AsyncClient::_allocate_closed_slot(){ _closed_slots[_closed_slot] = 0; } xSemaphoreGive(_slots_lock); + return (_closed_slot != -1); } void AsyncClient::_free_closed_slot(){ + xSemaphoreTake(_slots_lock, portMAX_DELAY); if (_closed_slot != -1) { _closed_slots[_closed_slot] = _closed_index; _closed_slot = -1; ++ _closed_index; } + xSemaphoreGive(_slots_lock); } /* * Private Callbacks * */ -int8_t AsyncClient::_connected(void* pcb, int8_t err){ +int8_t AsyncClient::_connected(tcp_pcb* pcb, int8_t err){ _pcb = reinterpret_cast(pcb); if(_pcb){ _rx_last_packet = millis(); - _pcb_busy = false; -// tcp_recv(_pcb, &_tcp_recv); -// tcp_sent(_pcb, &_tcp_sent); -// tcp_poll(_pcb, &_tcp_poll, 1); } if(_connect_cb) { _connect_cb(_connect_cb_arg, this); @@ -869,6 +926,7 @@ void AsyncClient::_error(int8_t err) { tcp_err(_pcb, NULL); tcp_poll(_pcb, NULL, 0); } + _free_closed_slot(); _pcb = NULL; } if(_error_cb) { @@ -882,7 +940,7 @@ void AsyncClient::_error(int8_t err) { //In LwIP Thread int8_t AsyncClient::_lwip_fin(tcp_pcb* pcb, int8_t err) { if(!_pcb || pcb != _pcb){ - log_e("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); + log_d("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); return ERR_OK; } tcp_arg(_pcb, NULL); @@ -910,23 +968,27 @@ int8_t AsyncClient::_fin(tcp_pcb* pcb, int8_t err) { } int8_t AsyncClient::_sent(tcp_pcb* pcb, uint16_t len) { - _rx_last_packet = millis(); - //log_i("%u", len); - _pcb_busy = false; + _rx_last_ack = _rx_last_packet = millis(); if(_sent_cb) { - _sent_cb(_sent_cb_arg, this, len, (millis() - _pcb_sent_at)); + _sent_cb(_sent_cb_arg, this, len, (_rx_last_packet - _tx_last_packet)); } return ERR_OK; } int8_t AsyncClient::_recv(tcp_pcb* pcb, pbuf* pb, int8_t err) { - while(pb != NULL) { + if(!_pcb || pcb != _pcb){ + log_d("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); + return ERR_OK; + } + size_t total = 0; + while((pb != NULL) && (ERR_OK == err)) { _rx_last_packet = millis(); //we should not ack before we assimilate the data _ack_pcb = true; pbuf *b = pb; pb = b->next; b->next = NULL; + total += b->len; if(_pb_cb){ _pb_cb(_pb_cb_arg, this, b); } else { @@ -935,38 +997,39 @@ int8_t AsyncClient::_recv(tcp_pcb* pcb, pbuf* pb, int8_t err) { } if(!_ack_pcb) { _rx_ack_len += b->len; - } else if(_pcb) { - _tcp_recved(_pcb, _closed_slot, b->len); } - pbuf_free(b); } + pbuf_free(b); } - return ERR_OK; + return _tcp_recved(pcb, _closed_slot, total); } int8_t AsyncClient::_poll(tcp_pcb* pcb){ if(!_pcb){ - log_w("pcb is NULL"); + log_d("pcb is NULL"); return ERR_OK; } if(pcb != _pcb){ - log_e("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); + log_d("0x%08x != 0x%08x", (uint32_t)pcb, (uint32_t)_pcb); return ERR_OK; } uint32_t now = millis(); // ACK Timeout - if(_pcb_busy && _ack_timeout && (now - _pcb_sent_at) >= _ack_timeout){ - _pcb_busy = false; - log_w("ack timeout %d", pcb->state); - if(_timeout_cb) - _timeout_cb(_timeout_cb_arg, this, (now - _pcb_sent_at)); - return ERR_OK; + if(_ack_timeout){ + const uint32_t one_day = 86400000; + bool last_tx_is_after_last_ack = (_rx_last_ack - _tx_last_packet + one_day) < one_day; + if(last_tx_is_after_last_ack && (now - _tx_last_packet) >= _ack_timeout) { + log_d("ack timeout %d", pcb->state); + if(_timeout_cb) + _timeout_cb(_timeout_cb_arg, this, (now - _tx_last_packet)); + return ERR_OK; + } } // RX Timeout - if(_rx_since_timeout && (now - _rx_last_packet) >= (_rx_since_timeout * 1000)){ - log_w("rx timeout %d", pcb->state); + if(_rx_timeout && (now - _rx_last_packet) >= (_rx_timeout * 1000)) { + log_d("rx timeout %d", pcb->state); _close(); return ERR_OK; } @@ -978,8 +1041,19 @@ int8_t AsyncClient::_poll(tcp_pcb* pcb){ } void AsyncClient::_dns_found(struct ip_addr *ipaddr){ - if(ipaddr && ipaddr->u_addr.ip4.addr){ - connect(IPAddress(ipaddr->u_addr.ip4.addr), _connect_port); +#if ESP_IDF_VERSION_MAJOR < 5 + if(ipaddr && IP_IS_V4(ipaddr)){ + connect(IPAddress(ip_addr_get_ip4_u32(ipaddr)), _connect_port); +#if LWIP_IPV6 + } else if(ipaddr && ipaddr->u_addr.ip6.addr){ + connect(IPv6Address(ipaddr->u_addr.ip6.addr), _connect_port); +#endif +#else + if(ipaddr) { + IPAddress ip; + ip.from_ip_addr_t(ipaddr); + connect(ip, _connect_port); +#endif } else { if(_error_cb) { _error_cb(_error_cb_arg, this, -55); @@ -1017,18 +1091,21 @@ size_t AsyncClient::write(const char* data) { size_t AsyncClient::write(const char* data, size_t size, uint8_t apiflags) { size_t will_send = add(data, size, apiflags); - if(!will_send || !send()) { + if(!will_send) { return 0; } + while (connected() && !send()) { + taskYIELD(); + } return will_send; } void AsyncClient::setRxTimeout(uint32_t timeout){ - _rx_since_timeout = timeout; + _rx_timeout = timeout; } uint32_t AsyncClient::getRxTimeout(){ - return _rx_since_timeout; + return _rx_timeout; } uint32_t AsyncClient::getAckTimeout(){ @@ -1057,6 +1134,18 @@ bool AsyncClient::getNoDelay(){ return tcp_nagle_disabled(_pcb); } +void AsyncClient::setKeepAlive(uint32_t ms, uint8_t cnt){ + if(ms!=0) { + _pcb->so_options |= SOF_KEEPALIVE; //Turn on TCP Keepalive for the given pcb + // Set the time between keepalive messages in milli-seconds + _pcb->keep_idle = ms; + _pcb->keep_intvl = ms; + _pcb->keep_cnt = cnt; //The number of unanswered probes required to force closure of the socket + } else { + _pcb->so_options &= ~SOF_KEEPALIVE; //Turn off TCP Keepalive for the given pcb + } +} + uint16_t AsyncClient::getMss(){ if(!_pcb) { return 0; @@ -1068,9 +1157,60 @@ uint32_t AsyncClient::getRemoteAddress() { if(!_pcb) { return 0; } +#if LWIP_IPV4 && LWIP_IPV6 return _pcb->remote_ip.u_addr.ip4.addr; +#else + return _pcb->remote_ip.addr; +#endif } +#if LWIP_IPV6 +ip6_addr_t AsyncClient::getRemoteAddress6() { + if(!_pcb) { + ip6_addr_t nulladdr; + ip6_addr_set_zero(&nulladdr); + return nulladdr; + } + return _pcb->remote_ip.u_addr.ip6; +} + +ip6_addr_t AsyncClient::getLocalAddress6() { + if(!_pcb) { + ip6_addr_t nulladdr; + ip6_addr_set_zero(&nulladdr); + return nulladdr; + } + return _pcb->local_ip.u_addr.ip6; +} +#if ESP_IDF_VERSION_MAJOR < 5 +IPv6Address AsyncClient::remoteIP6() { + return IPv6Address(getRemoteAddress6().addr); +} + +IPv6Address AsyncClient::localIP6() { + return IPv6Address(getLocalAddress6().addr); +} +#else +IPAddress AsyncClient::remoteIP6() { + if (!_pcb) { + return IPAddress(IPType::IPv6); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->remote_ip)); + return ip; +} + +IPAddress AsyncClient::localIP6() { + if (!_pcb) { + return IPAddress(IPType::IPv6); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->local_ip)); + return ip; +} +#endif +#endif + uint16_t AsyncClient::getRemotePort() { if(!_pcb) { return 0; @@ -1082,7 +1222,11 @@ uint32_t AsyncClient::getLocalAddress() { if(!_pcb) { return 0; } +#if LWIP_IPV4 && LWIP_IPV6 return _pcb->local_ip.u_addr.ip4.addr; +#else + return _pcb->local_ip.addr; +#endif } uint16_t AsyncClient::getLocalPort() { @@ -1093,7 +1237,16 @@ uint16_t AsyncClient::getLocalPort() { } IPAddress AsyncClient::remoteIP() { +#if ESP_IDF_VERSION_MAJOR < 5 return IPAddress(getRemoteAddress()); +#else + if (!_pcb) { + return IPAddress(); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->remote_ip)); + return ip; +#endif } uint16_t AsyncClient::remotePort() { @@ -1101,9 +1254,19 @@ uint16_t AsyncClient::remotePort() { } IPAddress AsyncClient::localIP() { +#if ESP_IDF_VERSION_MAJOR < 5 return IPAddress(getLocalAddress()); +#else + if (!_pcb) { + return IPAddress(); + } + IPAddress ip; + ip.from_ip_addr_t(&(_pcb->local_ip)); + return ip; +#endif } + uint16_t AsyncClient::localPort() { return getLocalPort(); } @@ -1226,7 +1389,7 @@ void AsyncClient::_s_error(void * arg, int8_t err) { reinterpret_cast(arg)->_error(err); } -int8_t AsyncClient::_s_connected(void * arg, void * pcb, int8_t err){ +int8_t AsyncClient::_s_connected(void * arg, struct tcp_pcb * pcb, int8_t err){ return reinterpret_cast(arg)->_connected(pcb, err); } @@ -1236,6 +1399,13 @@ int8_t AsyncClient::_s_connected(void * arg, void * pcb, int8_t err){ AsyncServer::AsyncServer(IPAddress addr, uint16_t port) : _port(port) +#if ESP_IDF_VERSION_MAJOR < 5 +, _bind4(true) +, _bind6(false) +#else +, _bind4(addr.type() != IPType::IPv6) +, _bind6(addr.type() == IPType::IPv6) +#endif , _addr(addr) , _noDelay(false) , _pcb(0) @@ -1243,9 +1413,27 @@ AsyncServer::AsyncServer(IPAddress addr, uint16_t port) , _connect_cb_arg(0) {} +#if ESP_IDF_VERSION_MAJOR < 5 +AsyncServer::AsyncServer(IPv6Address addr, uint16_t port) +: _port(port) +, _bind4(false) +, _bind6(true) +, _addr6(addr) +, _noDelay(false) +, _pcb(0) +, _connect_cb(0) +, _connect_cb_arg(0) +{} +#endif + AsyncServer::AsyncServer(uint16_t port) : _port(port) +, _bind4(true) +, _bind6(false) , _addr((uint32_t) IPADDR_ANY) +#if ESP_IDF_VERSION_MAJOR < 5 +, _addr6() +#endif , _noDelay(false) , _pcb(0) , _connect_cb(0) @@ -1271,15 +1459,24 @@ void AsyncServer::begin(){ return; } int8_t err; - _pcb = tcp_new_ip_type(IPADDR_TYPE_V4); + _pcb = tcp_new_ip_type(_bind4 && _bind6 ? IPADDR_TYPE_ANY : (_bind6 ? IPADDR_TYPE_V6 : IPADDR_TYPE_V4)); if (!_pcb){ log_e("_pcb == NULL"); return; } ip_addr_t local_addr; - local_addr.type = IPADDR_TYPE_V4; - local_addr.u_addr.ip4.addr = (uint32_t) _addr; +#if ESP_IDF_VERSION_MAJOR < 5 + if (_bind6) { // _bind6 && _bind4 both at the same time is not supported on Arduino 2 in this lib API + local_addr.type = IPADDR_TYPE_V6; + memcpy(local_addr.u_addr.ip6.addr, static_cast(_addr6), sizeof(uint32_t) * 4); + } else { + local_addr.type = IPADDR_TYPE_V4; + local_addr.u_addr.ip4.addr = _addr; + } +#else + _addr.to_ip_addr_t(&local_addr); +#endif err = _tcp_bind(_pcb, &local_addr, _port); if (err != ERR_OK) { @@ -1322,7 +1519,7 @@ int8_t AsyncServer::_accept(tcp_pcb* pcb, int8_t err){ if(tcp_close(pcb) != ERR_OK){ tcp_abort(pcb); } - log_e("FAIL"); + log_d("FAIL"); return ERR_OK; } diff --git a/lib/AsyncTCP/src/AsyncTCP.h b/lib/AsyncTCP/src/AsyncTCP.h index ac87ded..9079d44 100644 --- a/lib/AsyncTCP/src/AsyncTCP.h +++ b/lib/AsyncTCP/src/AsyncTCP.h @@ -22,13 +22,34 @@ #ifndef ASYNCTCP_H_ #define ASYNCTCP_H_ +#define ASYNCTCP_VERSION "3.1.4" +#define ASYNCTCP_VERSION_MAJOR 3 +#define ASYNCTCP_VERSION_MINOR 1 +#define ASYNCTCP_VERSION_REVISION 4 +#define ASYNCTCP_FORK_mathieucarbou + #include "IPAddress.h" -#include "sdkconfig.h" +#if ESP_IDF_VERSION_MAJOR < 5 +#include "IPv6Address.h" +#endif #include +#include "lwip/ip_addr.h" +#include "lwip/ip6_addr.h" + +#ifndef LIBRETINY +#include "sdkconfig.h" extern "C" { #include "freertos/semphr.h" #include "lwip/pbuf.h" } +#else +extern "C" { + #include + #include +} +#define CONFIG_ASYNC_TCP_RUNNING_CORE -1 //any available core +#define CONFIG_ASYNC_TCP_USE_WDT 0 +#endif //If core is not defined, then we are running in Arduino or PIO #ifndef CONFIG_ASYNC_TCP_RUNNING_CORE @@ -36,9 +57,24 @@ extern "C" { #define CONFIG_ASYNC_TCP_USE_WDT 1 //if enabled, adds between 33us and 200us per event #endif +#ifndef CONFIG_ASYNC_TCP_STACK_SIZE +#define CONFIG_ASYNC_TCP_STACK_SIZE 8192 * 2 +#endif + +#ifndef CONFIG_ASYNC_TCP_PRIORITY +#define CONFIG_ASYNC_TCP_PRIORITY 10 +#endif + +#ifndef CONFIG_ASYNC_TCP_QUEUE_SIZE +#define CONFIG_ASYNC_TCP_QUEUE_SIZE 64 +#endif + +#ifndef CONFIG_ASYNC_TCP_MAX_ACK_TIME +#define CONFIG_ASYNC_TCP_MAX_ACK_TIME 5000 +#endif + class AsyncClient; -#define ASYNC_MAX_ACK_TIME 5000 #define ASYNC_WRITE_FLAG_COPY 0x01 //will allocate new buffer to hold the data while sending (else will hold reference to the data given) #define ASYNC_WRITE_FLAG_MORE 0x02 //will not send PSH flag, meaning that there should be more data to be sent before the application should react. @@ -65,8 +101,11 @@ class AsyncClient { bool operator!=(const AsyncClient &other) { return !(*this == other); } - bool connect(IPAddress ip, uint16_t port); - bool connect(const char* host, uint16_t port); + bool connect(const IPAddress& ip, uint16_t port); +#if ESP_IDF_VERSION_MAJOR < 5 + bool connect(const IPv6Address& ip, uint16_t port); +#endif + bool connect(const char *host, uint16_t port); void close(bool now = false); void stop(); int8_t abort(); @@ -99,16 +138,29 @@ class AsyncClient { void setNoDelay(bool nodelay); bool getNoDelay(); + void setKeepAlive(uint32_t ms, uint8_t cnt); + uint32_t getRemoteAddress(); uint16_t getRemotePort(); uint32_t getLocalAddress(); uint16_t getLocalPort(); +#if LWIP_IPV6 + ip6_addr_t getRemoteAddress6(); + ip6_addr_t getLocalAddress6(); +#if ESP_IDF_VERSION_MAJOR < 5 + IPv6Address remoteIP6(); + IPv6Address localIP6(); +#else + IPAddress remoteIP6(); + IPAddress localIP6(); +#endif +#endif //compatibility IPAddress remoteIP(); - uint16_t remotePort(); + uint16_t remotePort(); IPAddress localIP(); - uint16_t localPort(); + uint16_t localPort(); void onConnect(AcConnectHandler cb, void* arg = 0); //on successful connect void onDisconnect(AcConnectHandler cb, void* arg = 0); //disconnected @@ -133,13 +185,15 @@ class AsyncClient { static int8_t _s_lwip_fin(void *arg, struct tcp_pcb *tpcb, int8_t err); static void _s_error(void *arg, int8_t err); static int8_t _s_sent(void *arg, struct tcp_pcb *tpcb, uint16_t len); - static int8_t _s_connected(void* arg, void* tpcb, int8_t err); + static int8_t _s_connected(void* arg, struct tcp_pcb *tpcb, int8_t err); static void _s_dns_found(const char *name, struct ip_addr *ipaddr, void *arg); int8_t _recv(tcp_pcb* pcb, pbuf* pb, int8_t err); tcp_pcb * pcb(){ return _pcb; } protected: + bool _connect(ip_addr_t addr, uint16_t port); + tcp_pcb* _pcb; int8_t _closed_slot; @@ -160,19 +214,19 @@ class AsyncClient { AcConnectHandler _poll_cb; void* _poll_cb_arg; - bool _pcb_busy; - uint32_t _pcb_sent_at; bool _ack_pcb; + uint32_t _tx_last_packet; uint32_t _rx_ack_len; uint32_t _rx_last_packet; - uint32_t _rx_since_timeout; + uint32_t _rx_timeout; + uint32_t _rx_last_ack; uint32_t _ack_timeout; uint16_t _connect_port; int8_t _close(); void _free_closed_slot(); - void _allocate_closed_slot(); - int8_t _connected(void* pcb, int8_t err); + bool _allocate_closed_slot(); + int8_t _connected(tcp_pcb* pcb, int8_t err); void _error(int8_t err); int8_t _poll(tcp_pcb* pcb); int8_t _sent(tcp_pcb* pcb, uint16_t len); @@ -188,6 +242,9 @@ class AsyncClient { class AsyncServer { public: AsyncServer(IPAddress addr, uint16_t port); +#if ESP_IDF_VERSION_MAJOR < 5 + AsyncServer(IPv6Address addr, uint16_t port); +#endif AsyncServer(uint16_t port); ~AsyncServer(); void onClient(AcConnectHandler cb, void* arg); @@ -203,7 +260,12 @@ class AsyncServer { protected: uint16_t _port; + bool _bind4 = false; + bool _bind6 = false; IPAddress _addr; +#if ESP_IDF_VERSION_MAJOR < 5 + IPv6Address _addr6; +#endif bool _noDelay; tcp_pcb* _pcb; AcConnectHandler _connect_cb; diff --git a/lib/AsyncTCP/src/IPv6Address.cpp b/lib/AsyncTCP/src/IPv6Address.cpp deleted file mode 100644 index 7d3c0de..0000000 --- a/lib/AsyncTCP/src/IPv6Address.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - IPv6Address.cpp - Base class that provides IPv6Address - Copyright (c) 2011 Adrian McEwen. 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 - */ - -#include -#include -#include - -IPv6Address::IPv6Address() -{ - memset(_address.bytes, 0, sizeof(_address.bytes)); -} - -IPv6Address::IPv6Address(const uint8_t *address) -{ - memcpy(_address.bytes, address, sizeof(_address.bytes)); -} - -IPv6Address::IPv6Address(const uint32_t *address) -{ - memcpy(_address.bytes, (const uint8_t *)address, sizeof(_address.bytes)); -} - -IPv6Address& IPv6Address::operator=(const uint8_t *address) -{ - memcpy(_address.bytes, address, sizeof(_address.bytes)); - return *this; -} - -bool IPv6Address::operator==(const uint8_t* addr) const -{ - return memcmp(addr, _address.bytes, sizeof(_address.bytes)) == 0; -} - -size_t IPv6Address::printTo(Print& p) const -{ - size_t n = 0; - for(int i = 0; i < 16; i+=2) { - if(i){ - n += p.print(':'); - } - n += p.printf("%02x", _address.bytes[i]); - n += p.printf("%02x", _address.bytes[i+1]); - - } - return n; -} - -String IPv6Address::toString() const -{ - char szRet[40]; - sprintf(szRet,"%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", - _address.bytes[0], _address.bytes[1], _address.bytes[2], _address.bytes[3], - _address.bytes[4], _address.bytes[5], _address.bytes[6], _address.bytes[7], - _address.bytes[8], _address.bytes[9], _address.bytes[10], _address.bytes[11], - _address.bytes[12], _address.bytes[13], _address.bytes[14], _address.bytes[15]); - return String(szRet); -} - -bool IPv6Address::fromString(const char *address) -{ - //format 0011:2233:4455:6677:8899:aabb:ccdd:eeff - if(strlen(address) != 39){ - return false; - } - char * pos = (char *)address; - size_t i = 0; - for(i = 0; i < 16; i+=2) { - if(!sscanf(pos, "%2hhx", &_address.bytes[i]) || !sscanf(pos+2, "%2hhx", &_address.bytes[i+1])){ - return false; - } - pos += 5; - } - return true; -} diff --git a/lib/AsyncTCP/src/IPv6Address.h b/lib/AsyncTCP/src/IPv6Address.h deleted file mode 100644 index e61d0e7..0000000 --- a/lib/AsyncTCP/src/IPv6Address.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - IPv6Address.h - Base class that provides IPv6Address - Copyright (c) 2011 Adrian McEwen. 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 - */ - -#ifndef IPv6Address_h -#define IPv6Address_h - -#include -#include -#include - -// A class to make it easier to handle and pass around IP addresses - -class IPv6Address: public Printable -{ -private: - union { - uint8_t bytes[16]; // IPv4 address - uint32_t dword[4]; - } _address; - - // Access the raw byte array containing the address. Because this returns a pointer - // to the internal structure rather than a copy of the address this function should only - // be used when you know that the usage of the returned uint8_t* will be transient and not - // stored. - uint8_t* raw_address() - { - return _address.bytes; - } - -public: - // Constructors - IPv6Address(); - IPv6Address(const uint8_t *address); - IPv6Address(const uint32_t *address); - virtual ~IPv6Address() {} - - bool fromString(const char *address); - bool fromString(const String &address) { return fromString(address.c_str()); } - - operator const uint8_t*() const - { - return _address.bytes; - } - operator const uint32_t*() const - { - return _address.dword; - } - bool operator==(const IPv6Address& addr) const - { - return (_address.dword[0] == addr._address.dword[0]) - && (_address.dword[1] == addr._address.dword[1]) - && (_address.dword[2] == addr._address.dword[2]) - && (_address.dword[3] == addr._address.dword[3]); - } - bool operator==(const uint8_t* addr) const; - - // Overloaded index operator to allow getting and setting individual octets of the address - uint8_t operator[](int index) const - { - return _address.bytes[index]; - } - uint8_t& operator[](int index) - { - return _address.bytes[index]; - } - - // Overloaded copy operators to allow initialisation of IPv6Address objects from other types - IPv6Address& operator=(const uint8_t *address); - - virtual size_t printTo(Print& p) const; - String toString() const; - - friend class UDP; - friend class Client; - friend class Server; -}; - -#endif diff --git a/lib/BleScanner/src/BleScanner.cpp b/lib/BleScanner/src/BleScanner.cpp index 4509bd7..d4a257b 100644 --- a/lib/BleScanner/src/BleScanner.cpp +++ b/lib/BleScanner/src/BleScanner.cpp @@ -24,12 +24,19 @@ void Scanner::initialize(const std::string& deviceName, const bool wantDuplicate if (!BLEDevice::getInitialized()) { if (wantDuplicates) { // reduce memory footprint, cache is not used anyway + #ifdef CONFIG_BTDM_BLE_SCAN_DUPL NimBLEDevice::setScanDuplicateCacheSize(10); + #endif } BLEDevice::init(deviceName); } bleScan = BLEDevice::getScan(); + + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) bleScan->setAdvertisedDeviceCallbacks(this, wantDuplicates); + #else + bleScan->setScanCallbacks(this, wantDuplicates); + #endif bleScan->setInterval(interval); bleScan->setWindow(window); bleScan->setActiveScan(false); @@ -47,7 +54,11 @@ void Scanner::update() { log_w("Ble scanner max results not 0. Be aware of memory issue due to unbridled growth of results vector"); } + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) bool result = bleScan->start(scanDuration, nullptr, false); + #else + bool result = bleScan->start(scanDuration * 1000, false); + #endif // if (!result) { // scanErrors++; // if (scanErrors % 100 == 0) { @@ -87,4 +98,4 @@ void Scanner::onResult(NimBLEAdvertisedDevice* advertisedDevice) { } } -} // namespace BleScanner +} // namespace BleScanner \ No newline at end of file diff --git a/lib/Crc16/Crc16.h b/lib/Crc16/Crc16.h deleted file mode 100644 index fdcf2ff..0000000 --- a/lib/Crc16/Crc16.h +++ /dev/null @@ -1,243 +0,0 @@ -//------------------------------------------------------------------------------------- -// CRC16 support class -// Based on various examples found on the web -// Copyright (C) 2014 Vincenzo Mennella (see license.txt) -// History -// 0.1.0 31/05/2014: First public code release -// 0.1.1 17/12/2014: Minor revision and commented code -// 0.1.2 06/06/2019: Fix reflect routine for 16 bit data -// Added ModBus and Mcrf4XX inline functions -// -// License -// "MIT Open Source Software License": -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in the -// Software without restriction, including without limitation the rights to use, copy, -// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -// and to permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -//------------------------------------------------------------------------------------- -#ifndef CRC16_H -#define CRC16_H -#define LIBRARY_VERSION_CRC16_H "0.1.2" - -#if defined(ARDUINO) && ARDUINO >= 100 - #include "Arduino.h" -#elif defined(ARDUINO) - #include "WProgram.h" -#else - #include -#endif - -class Crc16 { - private: - //Crc parameters - uint16_t _msbMask; - uint16_t _mask; - uint16_t _xorIn; - uint16_t _xorOut; - uint16_t _polynomial; - uint8_t _reflectIn; - uint8_t _reflectOut; - //Crc value - uint16_t _crc; - uint8_t reflect(uint8_t data); - uint16_t reflect(uint16_t data); - - public: - inline Crc16() - { - //Default to XModem parameters - _reflectIn = false; - _reflectOut = false; - _polynomial = 0x1021; - _xorIn = 0x0000; - _xorOut = 0x0000; - _msbMask = 0x8000; - _mask = 0xFFFF; - _crc = _xorIn; - } - inline Crc16(uint8_t reflectIn, uint8_t reflectOut, uint16_t polynomial, uint16_t xorIn, uint16_t xorOut, uint16_t msbMask, uint16_t mask) - { - _reflectIn = reflectIn; - _reflectOut = reflectOut; - _polynomial = polynomial; - _xorIn = xorIn; - _xorOut = xorOut; - _msbMask = msbMask; - _mask = mask; - _crc = _xorIn; - } - inline void clearCrc(); - inline void updateCrc(uint8_t data); - inline uint16_t getCrc(); - inline unsigned int fastCrc(uint8_t data[], uint8_t start, uint16_t length, uint8_t reflectIn, uint8_t reflectOut, uint16_t polynomial, uint16_t xorIn, uint16_t xorOut, uint16_t msbMask, uint16_t mask); - inline unsigned int XModemCrc(uint8_t data[], uint8_t start, uint16_t length) - { - // XModem parameters: poly=0x1021 initialize=0x0000 refin=false refout=false xorout=0x0000 - return fastCrc(data, start, length, false, false, 0x1021, 0x0000, 0x0000, 0x8000, 0xffff); - } - inline unsigned int Mcrf4XX(uint8_t data[], uint8_t start, uint16_t length) - { - return fastCrc(data, start, length, true, true, 0x1021, 0xffff, 0x0000, 0x8000, 0xffff); - } - inline unsigned int Modbus(uint8_t data[], uint8_t start, uint16_t length) - { - return fastCrc(data, start, length, true, true, 0x8005, 0xffff, 0x0000, 0x8000, 0xffff); - } -}; - -//--------------------------------------------------- -// Initialize crc calculation -//--------------------------------------------------- -void Crc16::clearCrc() -{ - _crc = _xorIn; -} -//--------------------------------------------------- -// Update crc with new data -//--------------------------------------------------- -void Crc16::updateCrc(uint8_t data) -{ - if (_reflectIn != 0) - data = (uint8_t) reflect(data); - - int j = 0x80; - - while (j > 0) - { - uint16_t bit = (uint16_t)(_crc & _msbMask); - - _crc <<= 1; - - if ((data & j) != 0) - { - bit = (uint16_t)(bit ^ _msbMask); - } - - if (bit != 0) - { - _crc ^= _polynomial; - } - - j >>= 1; - } -} - -//--------------------------------------------------- -// Get final crc value -//--------------------------------------------------- -uint16_t Crc16::getCrc() -{ - if (_reflectOut != 0) - _crc = (unsigned int)((reflect(_crc) ^ _xorOut) & _mask); - - return _crc; -} - -//--------------------------------------------------- -// Calculate generic crc code on data array -// Examples of crc 16: -// Kermit: width=16 poly=0x1021 initialize=0x0000 refin=true refout=true xorout=0x0000 check=0x2189 -// Modbus: width=16 poly=0x8005 initialize=0xffff refin=true refout=true xorout=0x0000 check=0x4b37 -// XModem: width=16 poly=0x1021 initialize=0x0000 refin=false refout=false xorout=0x0000 check=0x31c3 -// CCITT-False: width=16 poly=0x1021 initialize=0xffff refin=false refout=false xorout=0x0000 check=0x29b1 -//--------------------------------------------------- -unsigned int Crc16::fastCrc(uint8_t data[], uint8_t start, uint16_t length, uint8_t reflectIn, uint8_t reflectOut, uint16_t polynomial, uint16_t xorIn, uint16_t xorOut, uint16_t msbMask, uint16_t mask) -{ - uint16_t crc = xorIn; - - int j; - uint8_t c; - unsigned int bit; - - if (length == 0) return crc; - - for (int i = start; i < (start + length); i++) - { - c = data[i]; - - if (reflectIn != 0) - c = (uint8_t) reflect(c); - - j = 0x80; - - while (j > 0) - { - bit = (unsigned int)(crc & msbMask); - crc <<= 1; - - if ((c & j) != 0) - { - bit = (unsigned int)(bit ^ msbMask); - } - - if (bit != 0) - { - crc ^= polynomial; - } - - j >>= 1; - } - } - - if (reflectOut != 0) - crc = (unsigned int)((reflect((uint16_t) crc) ^ xorOut) & mask); - - return crc; -} - -//------------------------------------------------------- -// Reflects bit in a uint8_t -//------------------------------------------------------- -uint8_t Crc16::reflect(uint8_t data) -{ - const uint8_t bits = 8; - unsigned long reflection = 0x00000000; - // Reflect the data about the center bit. - for (uint8_t bit = 0; bit < bits; bit++) - { - // If the LSB bit is set, set the reflection of it. - if ((data & 0x01) != 0) - { - reflection |= (unsigned long)(1 << ((bits - 1) - bit)); - } - - data = (uint8_t)(data >> 1); - } - - return reflection; -} -//------------------------------------------------------- -// Reflects bit in a uint16_t -//------------------------------------------------------- -uint16_t Crc16::reflect(uint16_t data) -{ - const uint8_t bits = 16; - unsigned long reflection = 0x00000000; - // Reflect the data about the center bit. - for (uint8_t bit = 0; bit < bits; bit++) - { - // If the LSB bit is set, set the reflection of it. - if ((data & 0x01) != 0) - { - reflection |= (unsigned long)(1 << ((bits - 1) - bit)); - } - - data = (uint16_t)(data >> 1); - } - - return reflection; -} - -#endif diff --git a/lib/ESP Async WebServer/.piopm b/lib/ESP Async WebServer/.piopm new file mode 100644 index 0000000..b5b4aa1 --- /dev/null +++ b/lib/ESP Async WebServer/.piopm @@ -0,0 +1 @@ +{"type": "library", "name": "ESP Async WebServer", "version": "3.0.6", "spec": {"owner": "mathieucarbou", "id": 16603, "name": "ESP Async WebServer", "requirements": null, "uri": null}} \ No newline at end of file diff --git a/lib/AsyncTCP-esphome/LICENSE b/lib/ESP Async WebServer/LICENSE similarity index 98% rename from lib/AsyncTCP-esphome/LICENSE rename to lib/ESP Async WebServer/LICENSE index 65c5ca8..153d416 100644 --- a/lib/AsyncTCP-esphome/LICENSE +++ b/lib/ESP Async WebServer/LICENSE @@ -1,7 +1,7 @@ GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -162,4 +162,4 @@ General Public License ever published by the Free Software Foundation. whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the -Library. +Library. \ No newline at end of file diff --git a/lib/ESP Async WebServer/README.md b/lib/ESP Async WebServer/README.md new file mode 100644 index 0000000..b14d36c --- /dev/null +++ b/lib/ESP Async WebServer/README.md @@ -0,0 +1,117 @@ +# ESP Async WebServer + +[![License: LGPL 3.0](https://img.shields.io/badge/License-LGPL%203.0-yellow.svg)](https://opensource.org/license/lgpl-3-0/) +[![Continuous Integration](https://github.com/mathieucarbou/ESPAsyncWebServer/actions/workflows/ci.yml/badge.svg)](https://github.com/mathieucarbou/ESPAsyncWebServer/actions/workflows/ci.yml) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/ESP%20Async%20WebServer.svg)](https://registry.platformio.org/libraries/mathieucarbou/ESP%20Async%20WebServer) + +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. + +This fork is based on [yubox-node-org/ESPAsyncWebServer](https://github.com/yubox-node-org/ESPAsyncWebServer) and includes all the concurrency fixes. + +## Changes in this fork + +- [@ayushsharma82](https://github.com/ayushsharma82) and [@mathieucarbou](https://github.com/mathieucarbou): Add RP2040 support ([#31](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/31)) +- [@mathieucarbou](https://github.com/mathieucarbou): `SSE_MAX_QUEUED_MESSAGES` to control the maximum number of messages that can be queued for a SSE client +- [@mathieucarbou](https://github.com/mathieucarbou): `write()` function public in `AsyncEventSource.h` +- [@mathieucarbou](https://github.com/mathieucarbou): `WS_MAX_QUEUED_MESSAGES`: control the maximum number of messages that can be queued for a Websocket client +- [@mathieucarbou](https://github.com/mathieucarbou): Added `setAuthentication(const String& username, const String& password)` +- [@mathieucarbou](https://github.com/mathieucarbou): Added `setCloseClientOnQueueFull(bool)` which can be set on a client to either close the connection or discard messages but not close the connection when the queue is full +- [@mathieucarbou](https://github.com/mathieucarbou): Added `StreamConcat` example to show how to stream multiple files in one response +- [@mathieucarbou](https://github.com/mathieucarbou): Added all flavors of `binary()`, `text()`, `binaryAll()` and `textAll()` in `AsyncWebSocket` +- [@mathieucarbou](https://github.com/mathieucarbou): Arduino 3 / ESP-IDF 5.1 compatibility +- [@mathieucarbou](https://github.com/mathieucarbou): Arduino Json 7 compatibility and backward compatible with 6 and 6 (changes in `AsyncJson.h`). The API to use Json has not changed. These are only internal changes. +- [@mathieucarbou](https://github.com/mathieucarbou): CI +- [@mathieucarbou](https://github.com/mathieucarbou): Depends on `mathieucarbou/Async TCP @ ^3.1.4` +- [@mathieucarbou](https://github.com/mathieucarbou): Deployed in PlatformIO registry and Arduino IDE library manager +- [@mathieucarbou](https://github.com/mathieucarbou): Firmware size optimization: remove mbedtls dependency (accounts for 33KB in firmware) +- [@mathieucarbou](https://github.com/mathieucarbou): Made DEFAULT_MAX_SSE_CLIENTS customizable +- [@mathieucarbou](https://github.com/mathieucarbou): Made DEFAULT_MAX_WS_CLIENTS customizable +- [@mathieucarbou](https://github.com/mathieucarbou): Remove filename after inline in Content-Disposition header according to RFC2183 +- [@mathieucarbou](https://github.com/mathieucarbou): Removed SPIFFSEditor to reduce library size and maintainance. SPIFF si also deprecated. If you need it, please copy the files from the original repository in your project. This fork focus on maintaining the server part and the SPIFFEditor is an application which has nothing to do inside a server library. +- [@mathieucarbou](https://github.com/mathieucarbou): Resurrected `AsyncWebSocketMessageBuffer` and `makeBuffer()` in order to make the fork API-compatible with the original library from me-no-dev regarding WebSocket. +- [@mathieucarbou](https://github.com/mathieucarbou): Some code cleanup +- [@mathieucarbou](https://github.com/mathieucarbou): Use `-D DEFAULT_MAX_WS_CLIENTS` to change the number of allows WebSocket clients and use `cleanupClients()` to help cleanup resources about dead clients +- [@nilo85](https://github.com/nilo85): Add support for Auth & GET requests in AsyncCallbackJsonWebHandler ([#14](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/14)) +- [@p0p-x](https://github.com/p0p-x): ESP IDF Compatibility (added back CMakeLists.txt) ([#32](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/32)) +- [@tueddy](https://github.com/tueddy): Compile with Arduino 3 (ESP-IDF 5.1) ([#13](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/13)) +- [@vortigont](https://github.com/vortigont): Set real "Last-Modified" header based on file's LastWrite time ([#5](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/5)) +- [@vortigont](https://github.com/vortigont): Some websocket code cleanup ([#29](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/29)) +- [@vortigont](https://github.com/vortigont): Refactor code - replace DYI structs with STL objects ([#39](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/39)) + +## Dependencies: + +- **ESP32**: `mathieucarbou/Async TCP @ ^3.1.4` (Arduino IDE: [https://github.com/mathieucarbou/AsyncTCP#v3.1.4](https://github.com/mathieucarbou/AsyncTCP/releases/tag/v3.1.4)) +- **ESP8266**: `esphome/ESPAsyncTCP-esphome @ 2.0.0` (Arduino IDE: [https://github.com/mathieucarbou/esphome-ESPAsyncTCP#v2.0.0](https://github.com/mathieucarbou/esphome-ESPAsyncTCP/releases/tag/v2.0.0)) +- **RP2040**: `khoih-prog/AsyncTCP_RP2040W @ 1.2.0` (Arduino IDE: [https://github.com/khoih-prog/AsyncTCP_RP2040W#v1.2.0](https://github.com/khoih-prog/AsyncTCP_RP2040W/releases/tag/v1.2.0)) + +## Documentation + +Usage and API stays the same as the original library. +Please look at the original libraries for more examples and documentation. + +- [https://github.com/me-no-dev/ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) (original library) +- [https://github.com/yubox-node-org/ESPAsyncWebServer](https://github.com/yubox-node-org/ESPAsyncWebServer) (fork of the original library) + +## `AsyncWebSocketMessageBuffer` and `makeBuffer()` + +The fork from `yubox-node-org` introduces some breaking API changes compared to the original library, especially regarding the use of `std::shared_ptr>` for WebSocket. + +This fork is compatible with the original library from `me-no-dev` regarding WebSocket, and wraps the optimizations done by `yubox-node-org` in the `AsyncWebSocketMessageBuffer` class. +So you have the choice of which API to use. + +Here are examples for serializing a Json document in a websocket message buffer: + +```cpp +void send(JsonDocument& doc) { + const size_t len = measureJson(doc); + + // original API from me-no-dev + AsyncWebSocketMessageBuffer* buffer = _ws->makeBuffer(len); + assert(buffer); // up to you to keep or remove this + serializeJson(doc, buffer->get(), len); + _ws->textAll(buffer); +} +``` + +```cpp +void send(JsonDocument& doc) { + const size_t len = measureJson(doc); + + // this fork (originally from yubox-node-org), uses another API with shared pointer + auto buffer = std::make_shared>(len); + assert(buffer); // up to you to keep or remove this + serializeJson(doc, buffer->data(), len); + _ws->textAll(std::move(buffer)); +} +``` + +I recommend to use the official API `AsyncWebSocketMessageBuffer` to retain further compatibility. + +## Important recommendations + +Most of the crashes are caused by improper configuration of the library for the project. +Here are some recommendations to avoid them. + +1. Set the running core to be on the same core of your application (usually core 1) `-D CONFIG_ASYNC_TCP_RUNNING_CORE=1` +2. Set the stack size appropriately with `-D CONFIG_ASYNC_TCP_STACK_SIZE=16384`. + The default value of `16384` might be too much for your project. + You can look at the [MycilaTaskMonitor](https://oss.carbou.me/MycilaTaskMonitor) project to monitor the stack usage. +3. You can change **if you know what you are doing** the task priority with `-D CONFIG_ASYNC_TCP_PRIORITY=10`. + Default is `10`. +4. You can increase the queue size with `-D CONFIG_ASYNC_TCP_QUEUE_SIZE=128`. + Default is `64`. +5. You can decrease the maximum ack time `-D CONFIG_ASYNC_TCP_MAX_ACK_TIME=3000`. + Default is `5000`. + +I personally use the following configuration in my projects because my WS messages can be big (up to 4k). +If you have smaller messages, you can increase `WS_MAX_QUEUED_MESSAGES` to 128. + +```c++ + -D CONFIG_ASYNC_TCP_MAX_ACK_TIME=3000 + -D CONFIG_ASYNC_TCP_PRIORITY=10 + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 + -D WS_MAX_QUEUED_MESSAGES=64 +``` diff --git a/lib/ESP Async WebServer/examples/CaptivePortal/CaptivePortal.ino b/lib/ESP Async WebServer/examples/CaptivePortal/CaptivePortal.ino new file mode 100644 index 0000000..2d0de89 --- /dev/null +++ b/lib/ESP Async WebServer/examples/CaptivePortal/CaptivePortal.ino @@ -0,0 +1,57 @@ +#include +#ifdef ESP32 + #include + #include +#elif defined(ESP8266) + #include + #include +#elif defined(TARGET_RP2040) + #include + #include +#endif +#include "ESPAsyncWebServer.h" + +DNSServer dnsServer; +AsyncWebServer server(80); + +class CaptiveRequestHandler : public AsyncWebHandler { + public: + CaptiveRequestHandler() {} + virtual ~CaptiveRequestHandler() {} + + bool canHandle(__unused AsyncWebServerRequest* request) { + // request->addInterestingHeader("ANY"); + return true; + } + + void handleRequest(AsyncWebServerRequest* request) { + AsyncResponseStream* response = request->beginResponseStream("text/html"); + response->print("Captive Portal"); + response->print("

This is out captive portal front page.

"); + response->printf("

You were trying to reach: http://%s%s

", request->host().c_str(), request->url().c_str()); + response->printf("

Try opening this link instead

", WiFi.softAPIP().toString().c_str()); + response->print(""); + request->send(response); + } +}; + +void setup() { + Serial.begin(115200); + Serial.println(); + Serial.println("Configuring access point..."); + + if (!WiFi.softAP("esp-captive")) { + Serial.println("Soft AP creation failed."); + while (1) + ; + } + + dnsServer.start(53, "*", WiFi.softAPIP()); + server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER); // only when requested from AP + // more handlers... + server.begin(); +} + +void loop() { + dnsServer.processNextRequest(); +} diff --git a/lib/ESP Async WebServer/examples/Draft/Draft.ino b/lib/ESP Async WebServer/examples/Draft/Draft.ino new file mode 100644 index 0000000..f10a9e7 --- /dev/null +++ b/lib/ESP Async WebServer/examples/Draft/Draft.ino @@ -0,0 +1,37 @@ +#include "mbedtls/md5.h" +#include +#include + +void setup() { + Serial.begin(115200); + delay(2000); + + const char* data = "Hello World"; + + { + uint8_t md5[16]; + mbedtls_md5_context _ctx; + mbedtls_md5_init(&_ctx); + mbedtls_md5_starts(&_ctx); + mbedtls_md5_update(&_ctx, (const unsigned char*)data, strlen(data)); + mbedtls_md5_finish(&_ctx, md5); + char output[33]; + for (int i = 0; i < 16; i++) { + sprintf_P(output + (i * 2), PSTR("%02x"), md5[i]); + } + Serial.println(String(output)); + } + + { + MD5Builder md5; + md5.begin(); + md5.add(data, strlen(data); + md5.calculate(); + char output[33]; + md5.getChars(output); + Serial.println(String(output)); + } +} + +void loop() { +} diff --git a/lib/ESP Async WebServer/examples/Filters/Filters.ino b/lib/ESP Async WebServer/examples/Filters/Filters.ino new file mode 100644 index 0000000..f031a1f --- /dev/null +++ b/lib/ESP Async WebServer/examples/Filters/Filters.ino @@ -0,0 +1,111 @@ +// Reproduced issue https://github.com/mathieucarbou/ESPAsyncWebServer/issues/26 + +#include +#ifdef ESP32 + #include + #include +#elif defined(ESP8266) + #include + #include +#elif defined(TARGET_RP2040) + #include + #include +#endif +#include "ESPAsyncWebServer.h" + +DNSServer dnsServer; +AsyncWebServer server(80); + +class CaptiveRequestHandler : public AsyncWebHandler { + public: + CaptiveRequestHandler() {} + virtual ~CaptiveRequestHandler() {} + + bool canHandle(__unused AsyncWebServerRequest* request) { + // request->addInterestingHeader("ANY"); + return true; + } + + void handleRequest(AsyncWebServerRequest* request) { + AsyncResponseStream* response = request->beginResponseStream("text/html"); + response->print("Captive Portal"); + response->print("

This is out captive portal front page.

"); + response->printf("

You were trying to reach: http://%s%s

", request->host().c_str(), request->url().c_str()); + response->printf("

Try opening this link instead

", WiFi.softAPIP().toString().c_str()); + response->print(""); + request->send(response); + } +}; + +bool hit1 = false; +bool hit2 = false; + +void setup() { + Serial.begin(115200); + + server + .on("/", HTTP_GET, [](AsyncWebServerRequest* request) { + Serial.println("Captive portal request..."); + Serial.println("WiFi.localIP(): " + WiFi.localIP().toString()); + Serial.println("request->client()->localIP(): " + request->client()->localIP().toString()); +#if ESP_IDF_VERSION_MAJOR >= 5 + Serial.println("WiFi.type(): " + String((int)WiFi.localIP().type())); + Serial.println("request->client()->type(): " + String((int)request->client()->localIP().type())); +#endif + Serial.println(WiFi.localIP() == request->client()->localIP() ? "should be: ON_STA_FILTER" : "should be: ON_AP_FILTER"); + Serial.println(WiFi.localIP() == request->client()->localIP()); + Serial.println(WiFi.localIP().toString() == request->client()->localIP().toString()); + request->send(200, "text/plain", "This is the captive portal"); + hit1 = true; + }) + .setFilter(ON_AP_FILTER); + + server + .on("/", HTTP_GET, [](AsyncWebServerRequest* request) { + Serial.println("Website request..."); + Serial.println("WiFi.localIP(): " + WiFi.localIP().toString()); + Serial.println("request->client()->localIP(): " + request->client()->localIP().toString()); +#if ESP_IDF_VERSION_MAJOR >= 5 + Serial.println("WiFi.type(): " + String((int)WiFi.localIP().type())); + Serial.println("request->client()->type(): " + String((int)request->client()->localIP().type())); +#endif + Serial.println(WiFi.localIP() == request->client()->localIP() ? "should be: ON_STA_FILTER" : "should be: ON_AP_FILTER"); + Serial.println(WiFi.localIP() == request->client()->localIP()); + Serial.println(WiFi.localIP().toString() == request->client()->localIP().toString()); + request->send(200, "text/plain", "This is the website"); + hit2 = true; + }) + .setFilter(ON_STA_FILTER); + + // assert(WiFi.softAP("esp-captive-portal")); + // dnsServer.start(53, "*", WiFi.softAPIP()); + // server.begin(); + // Serial.println("Captive portal started!"); + + // while (!hit1) { + // dnsServer.processNextRequest(); + // yield(); + // } + // delay(1000); // Wait for the client to process the response + + // Serial.println("Captive portal opened, stopping it and connecting to WiFi..."); + // dnsServer.stop(); + // WiFi.softAPdisconnect(); + + WiFi.persistent(false); + WiFi.begin("IoT"); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + } + Serial.println("Connected to WiFi with IP address: " + WiFi.localIP().toString()); + server.begin(); + + // while (!hit2) { + // delay(10); + // } + // delay(1000); // Wait for the client to process the response + // ESP.restart(); +} + +void loop() { +} diff --git a/lib/ESP Async WebServer/examples/SimpleServer/SimpleServer.ino b/lib/ESP Async WebServer/examples/SimpleServer/SimpleServer.ino new file mode 100644 index 0000000..2472674 --- /dev/null +++ b/lib/ESP Async WebServer/examples/SimpleServer/SimpleServer.ino @@ -0,0 +1,77 @@ +// +// A simple server implementation showing how to: +// * serve static messages +// * read GET and POST parameters +// * handle missing pages / 404s +// + +#include +#ifdef ESP32 + #include + #include +#elif defined(ESP8266) + #include + #include +#elif defined(TARGET_RP2040) + #include + #include +#endif +#include + +AsyncWebServer server(80); + +const char* ssid = "YOUR_SSID"; +const char* password = "YOUR_PASSWORD"; + +const char* PARAM_MESSAGE = "message"; + +void notFound(AsyncWebServerRequest* request) { + request->send(404, "text/plain", "Not found"); +} + +void setup() { + + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.printf("WiFi Failed!\n"); + return; + } + + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + + server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { + request->send(200, "text/plain", "Hello, world"); + }); + + // Send a GET request to /get?message= + server.on("/get", HTTP_GET, [](AsyncWebServerRequest* request) { + String message; + if (request->hasParam(PARAM_MESSAGE)) { + message = request->getParam(PARAM_MESSAGE)->value(); + } else { + message = "No message sent"; + } + request->send(200, "text/plain", "Hello, GET: " + message); + }); + + // Send a POST request to /post with a form field message set to + server.on("/post", HTTP_POST, [](AsyncWebServerRequest* request) { + String message; + if (request->hasParam(PARAM_MESSAGE, true)) { + message = request->getParam(PARAM_MESSAGE, true)->value(); + } else { + message = "No message sent"; + } + request->send(200, "text/plain", "Hello, POST: " + message); + }); + + server.onNotFound(notFound); + + server.begin(); +} + +void loop() { +} \ No newline at end of file diff --git a/lib/ESP Async WebServer/examples/StreamFiles/StreamConcat.h b/lib/ESP Async WebServer/examples/StreamFiles/StreamConcat.h new file mode 100644 index 0000000..c1e1927 --- /dev/null +++ b/lib/ESP Async WebServer/examples/StreamFiles/StreamConcat.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +class StreamConcat : public Stream { + public: + StreamConcat(Stream* s1, Stream* s2) : _s1(s1), _s2(s2) {} + + size_t write(__unused const uint8_t* p, __unused size_t n) override { return 0; } + size_t write(__unused uint8_t c) override { return 0; } + void flush() override {} + + int available() override { return _s1->available() + _s2->available(); } + + int read() override { + int c = _s1->read(); + return c != -1 ? c : _s2->read(); + } + +#if defined(TARGET_RP2040) + size_t readBytes(char* buffer, size_t length) { +#else + size_t readBytes(char* buffer, size_t length) override { +#endif + size_t count = _s1->readBytes(buffer, length); + return count > 0 ? count : _s2->readBytes(buffer, length); + } + + int peek() override { + int c = _s1->peek(); + return c != -1 ? c : _s2->peek(); + } + + private: + Stream* _s1; + Stream* _s2; +}; diff --git a/lib/ESP Async WebServer/examples/StreamFiles/StreamFiles.ino b/lib/ESP Async WebServer/examples/StreamFiles/StreamFiles.ino new file mode 100644 index 0000000..2a2c1b6 --- /dev/null +++ b/lib/ESP Async WebServer/examples/StreamFiles/StreamFiles.ino @@ -0,0 +1,84 @@ +#include +#include +#ifdef ESP32 + #include + #include +#elif defined(ESP8266) + #include + #include +#elif defined(TARGET_RP2040) + #include + #include +#endif +#include "StreamConcat.h" +#include "StreamString.h" +#include +#include + +DNSServer dnsServer; +AsyncWebServer server(80); + +void setup() { + Serial.begin(115200); + + LittleFS.begin(); + + WiFi.mode(WIFI_AP); + WiFi.softAP("esp-captive"); + dnsServer.start(53, "*", WiFi.softAPIP()); + + File file1 = LittleFS.open("/header.html", "w"); + file1.print("ESP Captive Portal"); + file1.close(); + + File file2 = LittleFS.open("/body.html", "w"); + file2.print("

Welcome to ESP Captive Portal

"); + file2.close(); + + File file3 = LittleFS.open("/footer.html", "w"); + file3.print(""); + file3.close(); + + server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { + File header = LittleFS.open("/header.html", "r"); + File body = LittleFS.open("/body.html", "r"); + StreamConcat stream1(&header, &body); + + StreamString content; +#if defined(TARGET_RP2040) + content.printf("FreeHeap: %d", rp2040.getFreeHeap()); +#else + content.printf("FreeHeap: %" PRIu32, ESP.getFreeHeap()); +#endif + StreamConcat stream2 = StreamConcat(&stream1, &content); + + File footer = LittleFS.open("/footer.html", "r"); + StreamConcat stream3 = StreamConcat(&stream2, &footer); + + request->send(stream3, "text/html", stream3.available()); + header.close(); + body.close(); + footer.close(); + }); + + server.onNotFound([](AsyncWebServerRequest* request) { + request->send(404, "text/plain", "Not found"); + }); + + server.begin(); +} + +uint32_t last = 0; + +void loop() { + // dnsServer.processNextRequest(); + + if (millis() - last > 2000) { +#if defined(TARGET_RP2040) + Serial.printf("FreeHeap: %d", rp2040.getFreeHeap()); +#else + Serial.printf("FreeHeap: %" PRIu32, ESP.getFreeHeap()); +#endif + last = millis(); + } +} \ No newline at end of file diff --git a/lib/ESP Async WebServer/examples/StreamFiles/StreamString.h b/lib/ESP Async WebServer/examples/StreamFiles/StreamString.h new file mode 100644 index 0000000..a6e0655 --- /dev/null +++ b/lib/ESP Async WebServer/examples/StreamFiles/StreamString.h @@ -0,0 +1,40 @@ +#pragma once + +#include + +class StreamString : public Stream { + public: + size_t write(const uint8_t* p, size_t n) override { return _buffer.concat(reinterpret_cast(p), n) ? n : 0; } + size_t write(uint8_t c) override { return _buffer.concat(static_cast(c)) ? 1 : 0; } + void flush() override {} + + int available() override { return static_cast(_buffer.length()); } + + int read() override { + if (_buffer.length() == 0) + return -1; + char c = _buffer[0]; + _buffer.remove(0, 1); + return c; + } + +#if defined(TARGET_RP2040) + size_t readBytes(char* buffer, size_t length) { +#else + size_t readBytes(char* buffer, size_t length) override { +#endif + if (length > _buffer.length()) + length = _buffer.length(); + // Don't use _str.ToCharArray() because it inserts a terminator + memcpy(buffer, _buffer.c_str(), length); + _buffer.remove(0, static_cast(length)); + return length; + } + + int peek() override { return _buffer.length() > 0 ? _buffer[0] : -1; } + + const String& buffer() const { return _buffer; } + + private: + String _buffer; +}; diff --git a/lib/ESP Async WebServer/library.json b/lib/ESP Async WebServer/library.json new file mode 100644 index 0000000..4e089ba --- /dev/null +++ b/lib/ESP Async WebServer/library.json @@ -0,0 +1,64 @@ +{ + "name": "ESP Async WebServer", + "version": "3.0.6", + "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", + "repository": { + "type": "git", + "url": "https://github.com/mathieucarbou/ESPAsyncWebServer.git" + }, + "authors": [ + { + "name": "Hristo Gochkov" + }, + { + "name": "Mathieu Carbou", + "maintainer": true + } + ], + "license": "LGPL-3.0", + "frameworks": "arduino", + "platforms": [ + "espressif32", + "espressif8266", + "raspberrypi" + ], + "dependencies": [ + { + "owner": "mathieucarbou", + "name": "Async TCP", + "version": "^3.1.4", + "platforms": "espressif32" + }, + { + "owner": "esphome", + "name": "ESPAsyncTCP-esphome", + "version": "^2.0.0", + "platforms": "espressif8266" + }, + { + "name": "Hash", + "platforms": "espressif8266" + }, + { + "owner": "khoih-prog", + "name": "AsyncTCP_RP2040W", + "version": "^1.2.0", + "platforms": "raspberrypi" + } + ], + "export": { + "include": [ + "examples", + "src", + "library.json", + "library.properties", + "LICENSE", + "README.md" + ] + }, + "build": { + "libCompatMode": "strict" + } +} \ No newline at end of file diff --git a/lib/ESP Async WebServer/library.properties b/lib/ESP Async WebServer/library.properties new file mode 100644 index 0000000..e0265c3 --- /dev/null +++ b/lib/ESP Async WebServer/library.properties @@ -0,0 +1,10 @@ +name=ESP Async WebServer +version=3.0.6 +author=Me-No-Dev +maintainer=Mathieu Carbou +sentence=Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040 +paragraph=Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc +category=Other +url=https://github.com/mathieucarbou/ESPAsyncWebServer +architectures=* +license=LGPL-3.0 diff --git a/lib/ESP Async WebServer/src/AsyncEventSource.cpp b/lib/ESP Async WebServer/src/AsyncEventSource.cpp new file mode 100644 index 0000000..4cafdae --- /dev/null +++ b/lib/ESP Async WebServer/src/AsyncEventSource.cpp @@ -0,0 +1,402 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "Arduino.h" +#if defined(ESP32) + #include +#endif +#include "AsyncEventSource.h" + +static String generateEventMessage(const char* message, const char* event, uint32_t id, uint32_t reconnect) { + String ev; + + if (reconnect) { + ev += F("retry: "); + ev += reconnect; + ev += F("\r\n"); + } + + if (id) { + ev += F("id: "); + ev += String(id); + ev += F("\r\n"); + } + + if (event != NULL) { + ev += F("event: "); + ev += String(event); + ev += F("\r\n"); + } + + if (message != NULL) { + size_t messageLen = strlen(message); + char* lineStart = (char*)message; + char* lineEnd; + do { + char* nextN = strchr(lineStart, '\n'); + char* nextR = strchr(lineStart, '\r'); + if (nextN == NULL && nextR == NULL) { + size_t llen = ((char*)message + messageLen) - lineStart; + char* ldata = (char*)malloc(llen + 1); + if (ldata != NULL) { + memcpy(ldata, lineStart, llen); + ldata[llen] = 0; + ev += F("data: "); + ev += ldata; + ev += F("\r\n\r\n"); + free(ldata); + } + lineStart = (char*)message + messageLen; + } else { + char* nextLine = NULL; + if (nextN != NULL && nextR != NULL) { + if (nextR < nextN) { + lineEnd = nextR; + if (nextN == (nextR + 1)) + nextLine = nextN + 1; + else + nextLine = nextR + 1; + } else { + lineEnd = nextN; + if (nextR == (nextN + 1)) + nextLine = nextR + 1; + else + nextLine = nextN + 1; + } + } else if (nextN != NULL) { + lineEnd = nextN; + nextLine = nextN + 1; + } else { + lineEnd = nextR; + nextLine = nextR + 1; + } + + size_t llen = lineEnd - lineStart; + char* ldata = (char*)malloc(llen + 1); + if (ldata != NULL) { + memcpy(ldata, lineStart, llen); + ldata[llen] = 0; + ev += F("data: "); + ev += ldata; + ev += F("\r\n"); + free(ldata); + } + lineStart = nextLine; + if (lineStart == ((char*)message + messageLen)) + ev += F("\r\n"); + } + } while (lineStart < ((char*)message + messageLen)); + } + + return ev; +} + +// Message + +AsyncEventSourceMessage::AsyncEventSourceMessage(const char* data, size_t len) + : _data(nullptr), _len(len), _sent(0), _acked(0) { + _data = (uint8_t*)malloc(_len + 1); + if (_data == nullptr) { + _len = 0; + } else { + memcpy(_data, data, len); + _data[_len] = 0; + } +} + +AsyncEventSourceMessage::~AsyncEventSourceMessage() { + if (_data != NULL) + free(_data); +} + +size_t AsyncEventSourceMessage::ack(size_t len, uint32_t time) { + (void)time; + // If the whole message is now acked... + if (_acked + len > _len) { + // Return the number of extra bytes acked (they will be carried on to the next message) + const size_t extra = _acked + len - _len; + _acked = _len; + return extra; + } + // Return that no extra bytes left. + _acked += len; + return 0; +} + +// This could also return void as the return value is not used. +// Leaving as-is for compatibility... +size_t AsyncEventSourceMessage::send(AsyncClient* client) { + if (_sent >= _len) { + return 0; + } + const size_t len_to_send = _len - _sent; + auto position = reinterpret_cast(_data + _sent); + const size_t sent_now = client->write(position, len_to_send); + _sent += sent_now; + return sent_now; +} + +// Client + +AsyncEventSourceClient::AsyncEventSourceClient(AsyncWebServerRequest* request, AsyncEventSource* server) { + _client = request->client(); + _server = server; + _lastId = 0; + if (request->hasHeader(F("Last-Event-ID"))) + _lastId = atoi(request->getHeader(F("Last-Event-ID"))->value().c_str()); + + _client->setRxTimeout(0); + _client->onError(NULL, NULL); + _client->onAck([](void* r, AsyncClient* c, size_t len, uint32_t time) { (void)c; ((AsyncEventSourceClient*)(r))->_onAck(len, time); }, this); + _client->onPoll([](void* r, AsyncClient* c) { (void)c; ((AsyncEventSourceClient*)(r))->_onPoll(); }, this); + _client->onData(NULL, NULL); + _client->onTimeout([this](void* r, AsyncClient* c __attribute__((unused)), uint32_t time) { ((AsyncEventSourceClient*)(r))->_onTimeout(time); }, this); + _client->onDisconnect([this](void* r, AsyncClient* c) { ((AsyncEventSourceClient*)(r))->_onDisconnect(); delete c; }, this); + + _server->_addClient(this); + delete request; +} + +AsyncEventSourceClient::~AsyncEventSourceClient() { +#ifdef ESP32 + std::lock_guard lock(_lockmq); +#endif + _messageQueue.clear(); + close(); +} + +void AsyncEventSourceClient::_queueMessage(const char* message, size_t len) { +#ifdef ESP32 + // length() is not thread-safe, thus acquiring the lock before this call.. + std::lock_guard lock(_lockmq); +#endif + + if (_messageQueue.size() >= SSE_MAX_QUEUED_MESSAGES) { +#ifdef ESP8266 + ets_printf(String(F("ERROR: Too many messages queued\n")).c_str()); +#elif defined(ESP32) + log_e("Too many messages queued: deleting message"); +#endif + return; + } + + _messageQueue.emplace_back(message, len); + // runqueue trigger when new messages added + if (_client->canSend()) { + _runQueue(); + } +} + +void AsyncEventSourceClient::_onAck(size_t len, uint32_t time) { +#ifdef ESP32 + // Same here, acquiring the lock early + std::lock_guard lock(_lockmq); +#endif + while (len && _messageQueue.size()) { + len = _messageQueue.front().ack(len, time); + if (_messageQueue.front().finished()) + _messageQueue.pop_front(); + } + _runQueue(); +} + +void AsyncEventSourceClient::_onPoll() { +#ifdef ESP32 + // Same here, acquiring the lock early + std::lock_guard lock(_lockmq); +#endif + if (_messageQueue.size()) { + _runQueue(); + } +} + +void AsyncEventSourceClient::_onTimeout(uint32_t time __attribute__((unused))) { + _client->close(true); +} + +void AsyncEventSourceClient::_onDisconnect() { + _client = NULL; + _server->_handleDisconnect(this); +} + +void AsyncEventSourceClient::close() { + if (_client != NULL) + _client->close(); +} + +void AsyncEventSourceClient::write(const char* message, size_t len) { + if (!connected()) + return; + _queueMessage(message, len); +} + +void AsyncEventSourceClient::send(const char* message, const char* event, uint32_t id, uint32_t reconnect) { + if (!connected()) + return; + String ev = generateEventMessage(message, event, id, reconnect); + _queueMessage(ev.c_str(), ev.length()); +} + +size_t AsyncEventSourceClient::packetsWaiting() const { +#ifdef ESP32 + std::lock_guard lock(_lockmq); +#endif + return _messageQueue.size(); +} + +void AsyncEventSourceClient::_runQueue() { + // Calls to this private method now already protected by _lockmq acquisition + // so no extra call of _lockmq.lock() here.. + for (auto& i : _messageQueue) { + if (!i.sent()) + i.send(_client); + } +} + +// Handler +void AsyncEventSource::onConnect(ArEventHandlerFunction cb) { + _connectcb = cb; +} + +void AsyncEventSource::authorizeConnect(ArAuthorizeConnectHandler cb) { + _authorizeConnectHandler = cb; +} + +void AsyncEventSource::_addClient(AsyncEventSourceClient* client) { + if (!client) + return; +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + _clients.emplace_back(client); + if (_connectcb) + _connectcb(client); +} + +void AsyncEventSource::_handleDisconnect(AsyncEventSourceClient* client) { +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + for (auto i = _clients.begin(); i != _clients.end(); ++i) { + if (i->get() == client) + _clients.erase(i); + } +} + +void AsyncEventSource::close() { + // While the whole loop is not done, the linked list is locked and so the + // iterator should remain valid even when AsyncEventSource::_handleDisconnect() + // is called very early +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + for (const auto& c : _clients) { + if (c->connected()) + c->close(); + } +} + +// pmb fix +size_t AsyncEventSource::avgPacketsWaiting() const { + size_t aql = 0; + uint32_t nConnectedClients = 0; +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + if (!_clients.size()) + return 0; + + for (const auto& c : _clients) { + if (c->connected()) { + aql += c->packetsWaiting(); + ++nConnectedClients; + } + } + return ((aql) + (nConnectedClients / 2)) / (nConnectedClients); // round up +} + +void AsyncEventSource::send( + const char* message, const char* event, uint32_t id, uint32_t reconnect) { + String ev = generateEventMessage(message, event, id, reconnect); +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + for (const auto& c : _clients) { + if (c->connected()) { + c->write(ev.c_str(), ev.length()); + } + } +} + +size_t AsyncEventSource::count() const { +#ifdef ESP32 + std::lock_guard lock(_client_queue_lock); +#endif + size_t n_clients{0}; + for (const auto& i : _clients) + if (i->connected()) + ++n_clients; + + return n_clients; +} + +bool AsyncEventSource::canHandle(AsyncWebServerRequest* request) { + if (request->method() != HTTP_GET || !request->url().equals(_url)) { + return false; + } + request->addInterestingHeader(F("Last-Event-ID")); + request->addInterestingHeader("Cookie"); + return true; +} + +void AsyncEventSource::handleRequest(AsyncWebServerRequest* request) { + if ((_username.length() && _password.length()) && !request->authenticate(_username.c_str(), _password.c_str())) { + return request->requestAuthentication(); + } + if (_authorizeConnectHandler != NULL) { + if (!_authorizeConnectHandler(request)) { + return request->send(401); + } + } + request->send(new AsyncEventSourceResponse(this)); +} + +// Response + +AsyncEventSourceResponse::AsyncEventSourceResponse(AsyncEventSource* server) { + _server = server; + _code = 200; + _contentType = F("text/event-stream"); + _sendContentLength = false; + addHeader(F("Cache-Control"), F("no-cache")); + addHeader(F("Connection"), F("keep-alive")); +} + +void AsyncEventSourceResponse::_respond(AsyncWebServerRequest* request) { + String out = _assembleHead(request->version()); + request->client()->write(out.c_str(), _headLength); + _state = RESPONSE_WAIT_ACK; +} + +size_t AsyncEventSourceResponse::_ack(AsyncWebServerRequest* request, size_t len, uint32_t time __attribute__((unused))) { + if (len) { + new AsyncEventSourceClient(request, _server); + } + return 0; +} diff --git a/lib/ESP Async WebServer/src/AsyncEventSource.h b/lib/ESP Async WebServer/src/AsyncEventSource.h new file mode 100644 index 0000000..0289ebf --- /dev/null +++ b/lib/ESP Async WebServer/src/AsyncEventSource.h @@ -0,0 +1,158 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#ifndef ASYNCEVENTSOURCE_H_ +#define ASYNCEVENTSOURCE_H_ + +#include +#include +#ifdef ESP32 + #include + #include + #ifndef SSE_MAX_QUEUED_MESSAGES + #define SSE_MAX_QUEUED_MESSAGES 32 + #endif +#elif defined(ESP8266) + #include + #ifndef SSE_MAX_QUEUED_MESSAGES + #define SSE_MAX_QUEUED_MESSAGES 8 + #endif +#elif defined(TARGET_RP2040) + #include + #ifndef SSE_MAX_QUEUED_MESSAGES + #define SSE_MAX_QUEUED_MESSAGES 32 + #endif +#endif + +#include + +#ifdef ESP8266 + #include + #ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library + #include <../src/Hash.h> + #endif +#endif + +#ifndef DEFAULT_MAX_SSE_CLIENTS + #ifdef ESP32 + #define DEFAULT_MAX_SSE_CLIENTS 8 + #else + #define DEFAULT_MAX_SSE_CLIENTS 4 + #endif +#endif + +class AsyncEventSource; +class AsyncEventSourceResponse; +class AsyncEventSourceClient; +using ArEventHandlerFunction = std::function; +using ArAuthorizeConnectHandler = std::function; + +class AsyncEventSourceMessage { + private: + uint8_t* _data; + size_t _len; + size_t _sent; + // size_t _ack; + size_t _acked; + + public: + AsyncEventSourceMessage(const char* data, size_t len); + ~AsyncEventSourceMessage(); + size_t ack(size_t len, uint32_t time __attribute__((unused))); + size_t send(AsyncClient* client); + bool finished() { return _acked == _len; } + bool sent() { return _sent == _len; } +}; + +class AsyncEventSourceClient { + private: + AsyncClient* _client; + AsyncEventSource* _server; + uint32_t _lastId; + std::list _messageQueue; +#ifdef ESP32 + mutable std::mutex _lockmq; +#endif + void _queueMessage(const char* message, size_t len); + void _runQueue(); + + public: + AsyncEventSourceClient(AsyncWebServerRequest* request, AsyncEventSource* server); + ~AsyncEventSourceClient(); + + AsyncClient* client() { return _client; } + void close(); + void write(const char* message, size_t len); + void send(const char* message, const char* event = NULL, uint32_t id = 0, uint32_t reconnect = 0); + bool connected() const { return (_client != NULL) && _client->connected(); } + uint32_t lastId() const { return _lastId; } + size_t packetsWaiting() const; + + // system callbacks (do not call) + void _onAck(size_t len, uint32_t time); + void _onPoll(); + void _onTimeout(uint32_t time); + void _onDisconnect(); +}; + +class AsyncEventSource : public AsyncWebHandler { + private: + String _url; + std::list> _clients; +#ifdef ESP32 + // Same as for individual messages, protect mutations of _clients list + // since simultaneous access from different tasks is possible + mutable std::mutex _client_queue_lock; +#endif + ArEventHandlerFunction _connectcb{nullptr}; + ArAuthorizeConnectHandler _authorizeConnectHandler; + + public: + AsyncEventSource(const String& url) : _url(url){}; + ~AsyncEventSource() { close(); }; + + const char* url() const { return _url.c_str(); } + void close(); + void onConnect(ArEventHandlerFunction cb); + void authorizeConnect(ArAuthorizeConnectHandler cb); + void send(const char* message, const char* event = NULL, uint32_t id = 0, uint32_t reconnect = 0); + // number of clients connected + size_t count() const; + size_t avgPacketsWaiting() const; + + // system callbacks (do not call) + void _addClient(AsyncEventSourceClient* client); + void _handleDisconnect(AsyncEventSourceClient* client); + virtual bool canHandle(AsyncWebServerRequest* request) override final; + virtual void handleRequest(AsyncWebServerRequest* request) override final; +}; + +class AsyncEventSourceResponse : public AsyncWebServerResponse { + private: + String _content; + AsyncEventSource* _server; + + public: + AsyncEventSourceResponse(AsyncEventSource* server); + void _respond(AsyncWebServerRequest* request); + size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time); + bool _sourceValid() const { return true; } +}; + +#endif /* ASYNCEVENTSOURCE_H_ */ diff --git a/lib/ESP Async WebServer/src/AsyncJson.h b/lib/ESP Async WebServer/src/AsyncJson.h new file mode 100644 index 0000000..b85a938 --- /dev/null +++ b/lib/ESP Async WebServer/src/AsyncJson.h @@ -0,0 +1,281 @@ +// AsyncJson.h +/* + Async Response to use with ArduinoJson and AsyncWebServer + Written by Andrew Melvin (SticilFace) with help from me-no-dev and BBlanchon. + + Example of callback in use + + server.on("/json", HTTP_ANY, [](AsyncWebServerRequest * request) { + + AsyncJsonResponse * response = new AsyncJsonResponse(); + JsonObject& root = response->getRoot(); + root["key1"] = "key number one"; + JsonObject& nested = root.createNestedObject("nested"); + nested["key1"] = "key number one"; + + response->setLength(); + request->send(response); + }); + + -------------------- + + Async Request to use with ArduinoJson and AsyncWebServer + Written by Arsène von Wyss (avonwyss) + + Example + + AsyncCallbackJsonWebHandler* handler = new AsyncCallbackJsonWebHandler("/rest/endpoint"); + handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) { + JsonObject& jsonObj = json.as(); + // ... + }); + server.addHandler(handler); + +*/ +#ifndef ASYNC_JSON_H_ +#define ASYNC_JSON_H_ +#include +#include +#include + +#if ARDUINOJSON_VERSION_MAJOR == 6 + #ifndef DYNAMIC_JSON_DOCUMENT_SIZE + #define DYNAMIC_JSON_DOCUMENT_SIZE 1024 + #endif +#endif + +constexpr const char* JSON_MIMETYPE = "application/json"; + +/* + * Json Response + * */ + +class ChunkPrint : public Print { + private: + uint8_t* _destination; + size_t _to_skip; + size_t _to_write; + size_t _pos; + + public: + ChunkPrint(uint8_t* destination, size_t from, size_t len) + : _destination(destination), _to_skip(from), _to_write(len), _pos{0} {} + virtual ~ChunkPrint() {} + size_t write(uint8_t c) { + if (_to_skip > 0) { + _to_skip--; + return 1; + } else if (_to_write > 0) { + _to_write--; + _destination[_pos++] = c; + return 1; + } + return 0; + } + size_t write(const uint8_t* buffer, size_t size) { + return this->Print::write(buffer, size); + } +}; + +class AsyncJsonResponse : public AsyncAbstractResponse { + protected: +#if ARDUINOJSON_VERSION_MAJOR == 5 + DynamicJsonBuffer _jsonBuffer; +#elif ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument _jsonBuffer; +#else + JsonDocument _jsonBuffer; +#endif + + JsonVariant _root; + bool _isValid; + + public: +#if ARDUINOJSON_VERSION_MAJOR == 5 + AsyncJsonResponse(bool isArray = false) : _isValid{false} { + _code = 200; + _contentType = JSON_MIMETYPE; + if (isArray) + _root = _jsonBuffer.createArray(); + else + _root = _jsonBuffer.createObject(); + } +#elif ARDUINOJSON_VERSION_MAJOR == 6 + AsyncJsonResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE) : _jsonBuffer(maxJsonBufferSize), _isValid{false} { + _code = 200; + _contentType = JSON_MIMETYPE; + if (isArray) + _root = _jsonBuffer.createNestedArray(); + else + _root = _jsonBuffer.createNestedObject(); + } +#else + AsyncJsonResponse(bool isArray = false) : _isValid{false} { + _code = 200; + _contentType = JSON_MIMETYPE; + if (isArray) + _root = _jsonBuffer.add(); + else + _root = _jsonBuffer.add(); + } +#endif + + JsonVariant& getRoot() { return _root; } + bool _sourceValid() const { return _isValid; } + size_t setLength() { + +#if ARDUINOJSON_VERSION_MAJOR == 5 + _contentLength = _root.measureLength(); +#else + _contentLength = measureJson(_root); +#endif + + if (_contentLength) { + _isValid = true; + } + return _contentLength; + } + + size_t getSize() const { return _jsonBuffer.size(); } + +#if ARDUINOJSON_VERSION_MAJOR >= 6 + bool overflowed() const { return _jsonBuffer.overflowed(); } +#endif + + size_t _fillBuffer(uint8_t* data, size_t len) { + ChunkPrint dest(data, _sentLength, len); + +#if ARDUINOJSON_VERSION_MAJOR == 5 + _root.printTo(dest); +#else + serializeJson(_root, dest); +#endif + return len; + } +}; + +class PrettyAsyncJsonResponse : public AsyncJsonResponse { + public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + PrettyAsyncJsonResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE) : AsyncJsonResponse{isArray, maxJsonBufferSize} {} +#else + PrettyAsyncJsonResponse(bool isArray = false) : AsyncJsonResponse{isArray} {} +#endif + size_t setLength() { +#if ARDUINOJSON_VERSION_MAJOR == 5 + _contentLength = _root.measurePrettyLength(); +#else + _contentLength = measureJsonPretty(_root); +#endif + if (_contentLength) { + _isValid = true; + } + return _contentLength; + } + size_t _fillBuffer(uint8_t* data, size_t len) { + ChunkPrint dest(data, _sentLength, len); +#if ARDUINOJSON_VERSION_MAJOR == 5 + _root.prettyPrintTo(dest); +#else + serializeJsonPretty(_root, dest); +#endif + return len; + } +}; + +typedef std::function ArJsonRequestHandlerFunction; + +class AsyncCallbackJsonWebHandler : public AsyncWebHandler { + private: + protected: + const String _uri; + WebRequestMethodComposite _method; + ArJsonRequestHandlerFunction _onRequest; + size_t _contentLength; +#if ARDUINOJSON_VERSION_MAJOR == 6 + const size_t maxJsonBufferSize; +#endif + size_t _maxContentLength; + + public: +#if ARDUINOJSON_VERSION_MAJOR == 6 + AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE) + : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {} +#else + AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest) + : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {} +#endif + + void setMethod(WebRequestMethodComposite method) { _method = method; } + void setMaxContentLength(int maxContentLength) { _maxContentLength = maxContentLength; } + void onRequest(ArJsonRequestHandlerFunction fn) { _onRequest = fn; } + + virtual bool canHandle(AsyncWebServerRequest* request) override final { + if (!_onRequest) + return false; + + WebRequestMethodComposite request_method = request->method(); + if (!(_method & request_method)) + return false; + + if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/"))) + return false; + + if (request_method != HTTP_GET && !request->contentType().equalsIgnoreCase(JSON_MIMETYPE)) + return false; + + request->addInterestingHeader("ANY"); + return true; + } + + virtual void handleRequest(AsyncWebServerRequest* request) override final { + if ((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str())) + return request->requestAuthentication(); + if (_onRequest) { + if (request->method() == HTTP_GET) { + JsonVariant json; + _onRequest(request, json); + return; + } else if (request->_tempObject != NULL) { + +#if ARDUINOJSON_VERSION_MAJOR == 5 + DynamicJsonBuffer jsonBuffer; + JsonVariant json = jsonBuffer.parse((uint8_t*)(request->_tempObject)); + if (json.success()) { +#elif ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument jsonBuffer(this->maxJsonBufferSize); + DeserializationError error = deserializeJson(jsonBuffer, (uint8_t*)(request->_tempObject)); + if (!error) { + JsonVariant json = jsonBuffer.as(); +#else + JsonDocument jsonBuffer; + DeserializationError error = deserializeJson(jsonBuffer, (uint8_t*)(request->_tempObject)); + if (!error) { + JsonVariant json = jsonBuffer.as(); +#endif + + _onRequest(request, json); + return; + } + } + request->send(_contentLength > _maxContentLength ? 413 : 400); + } else { + request->send(500); + } + } + virtual void handleUpload(__unused AsyncWebServerRequest* request, __unused const String& filename, __unused size_t index, __unused uint8_t* data, __unused size_t len, __unused bool final) override final { + } + virtual void handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) override final { + if (_onRequest) { + _contentLength = total; + if (total > 0 && request->_tempObject == NULL && total < _maxContentLength) { + request->_tempObject = malloc(total); + } + if (request->_tempObject != NULL) { + memcpy((uint8_t*)(request->_tempObject) + index, data, len); + } + } + } + virtual bool isRequestHandlerTrivial() override final { return _onRequest ? false : true; } +}; +#endif diff --git a/lib/ESP Async WebServer/src/AsyncWebSocket.cpp b/lib/ESP Async WebServer/src/AsyncWebSocket.cpp new file mode 100644 index 0000000..e978afc --- /dev/null +++ b/lib/ESP Async WebServer/src/AsyncWebSocket.cpp @@ -0,0 +1,1197 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "AsyncWebSocket.h" +#include "Arduino.h" + +#include + +#include + +#if defined(ESP32) + #if ESP_IDF_VERSION_MAJOR < 5 + #include "./port/SHA1Builder.h" + #else + #include + #endif + #include +#elif defined(TARGET_RP2040) || defined(ESP8266) + #include +#endif + +#define MAX_PRINTF_LEN 64 + +size_t webSocketSendFrameWindow(AsyncClient* client) { + if (!client->canSend()) + return 0; + size_t space = client->space(); + if (space < 9) + return 0; + return space - 8; +} + +size_t webSocketSendFrame(AsyncClient* client, bool final, uint8_t opcode, bool mask, uint8_t* data, size_t len) { + if (!client->canSend()) { + // Serial.println("SF 1"); + return 0; + } + size_t space = client->space(); + if (space < 2) { + // Serial.println("SF 2"); + return 0; + } + uint8_t mbuf[4] = {0, 0, 0, 0}; + uint8_t headLen = 2; + if (len && mask) { + headLen += 4; + mbuf[0] = rand() % 0xFF; + mbuf[1] = rand() % 0xFF; + mbuf[2] = rand() % 0xFF; + mbuf[3] = rand() % 0xFF; + } + if (len > 125) + headLen += 2; + if (space < headLen) { + // Serial.println("SF 2"); + return 0; + } + space -= headLen; + + if (len > space) + len = space; + + uint8_t* buf = (uint8_t*)malloc(headLen); + if (buf == NULL) { + // os_printf("could not malloc %u bytes for frame header\n", headLen); + // Serial.println("SF 3"); + return 0; + } + + buf[0] = opcode & 0x0F; + if (final) + buf[0] |= 0x80; + if (len < 126) + buf[1] = len & 0x7F; + else { + buf[1] = 126; + buf[2] = (uint8_t)((len >> 8) & 0xFF); + buf[3] = (uint8_t)(len & 0xFF); + } + if (len && mask) { + buf[1] |= 0x80; + memcpy(buf + (headLen - 4), mbuf, 4); + } + if (client->add((const char*)buf, headLen) != headLen) { + // os_printf("error adding %lu header bytes\n", headLen); + free(buf); + // Serial.println("SF 4"); + return 0; + } + free(buf); + + if (len) { + if (len && mask) { + size_t i; + for (i = 0; i < len; i++) + data[i] = data[i] ^ mbuf[i % 4]; + } + if (client->add((const char*)data, len) != len) { + // os_printf("error adding %lu data bytes\n", len); + // Serial.println("SF 5"); + return 0; + } + } + if (!client->send()) { + // os_printf("error sending frame: %lu\n", headLen+len); + // Serial.println("SF 6"); + return 0; + } + // Serial.println("SF"); + return len; +} + +/* + * AsyncWebSocketMessageBuffer + */ + +AsyncWebSocketMessageBuffer::AsyncWebSocketMessageBuffer(const uint8_t* data, size_t size) + : _buffer(std::make_shared>(size)) { + if (_buffer->capacity() < size) { + _buffer->reserve(size); + } else { + std::memcpy(_buffer->data(), data, size); + } +} + +AsyncWebSocketMessageBuffer::AsyncWebSocketMessageBuffer(size_t size) + : _buffer(std::make_shared>(size)) { + if (_buffer->capacity() < size) { + _buffer->reserve(size); + } +} + +bool AsyncWebSocketMessageBuffer::reserve(size_t size) { + if (_buffer->capacity() >= size) + return true; + _buffer->reserve(size); + return _buffer->capacity() >= size; +} + +/* + * Control Frame + */ + +class AsyncWebSocketControl { + private: + uint8_t _opcode; + uint8_t* _data; + size_t _len; + bool _mask; + bool _finished; + + public: + AsyncWebSocketControl(uint8_t opcode, const uint8_t* data = NULL, size_t len = 0, bool mask = false) + : _opcode(opcode), _len(len), _mask(len && mask), _finished(false) { + if (data == NULL) + _len = 0; + if (_len) { + if (_len > 125) + _len = 125; + + _data = (uint8_t*)malloc(_len); + + if (_data == NULL) + _len = 0; + else + memcpy(_data, data, len); + } else + _data = NULL; + } + + virtual ~AsyncWebSocketControl() { + if (_data != NULL) + free(_data); + } + + virtual bool finished() const { return _finished; } + uint8_t opcode() { return _opcode; } + uint8_t len() { return _len + 2; } + size_t send(AsyncClient* client) { + _finished = true; + return webSocketSendFrame(client, true, _opcode & 0x0F, _mask, _data, _len); + } +}; + +/* + * AsyncWebSocketMessage Message + */ + +AsyncWebSocketMessage::AsyncWebSocketMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode, bool mask) : _WSbuffer{buffer}, + _opcode(opcode & 0x07), + _mask{mask}, + _status{_WSbuffer ? WS_MSG_SENDING : WS_MSG_ERROR} { +} + +void AsyncWebSocketMessage::ack(size_t len, uint32_t time) { + (void)time; + _acked += len; + if (_sent >= _WSbuffer->size() && _acked >= _ack) { + _status = WS_MSG_SENT; + } + // ets_printf("A: %u\n", len); +} + +size_t AsyncWebSocketMessage::send(AsyncClient* client) { + if (_status != WS_MSG_SENDING) + return 0; + if (_acked < _ack) { + return 0; + } + if (_sent == _WSbuffer->size()) { + if (_acked == _ack) + _status = WS_MSG_SENT; + return 0; + } + if (_sent > _WSbuffer->size()) { + _status = WS_MSG_ERROR; + // ets_printf("E: %u > %u\n", _sent, _WSbuffer->length()); + return 0; + } + + size_t toSend = _WSbuffer->size() - _sent; + size_t window = webSocketSendFrameWindow(client); + + if (window < toSend) { + toSend = window; + } + + _sent += toSend; + _ack += toSend + ((toSend < 126) ? 2 : 4) + (_mask * 4); + + // ets_printf("W: %u %u\n", _sent - toSend, toSend); + + bool final = (_sent == _WSbuffer->size()); + uint8_t* dPtr = (uint8_t*)(_WSbuffer->data() + (_sent - toSend)); + uint8_t opCode = (toSend && _sent == toSend) ? _opcode : (uint8_t)WS_CONTINUATION; + + size_t sent = webSocketSendFrame(client, final, opCode, _mask, dPtr, toSend); + _status = WS_MSG_SENDING; + if (toSend && sent != toSend) { + // ets_printf("E: %u != %u\n", toSend, sent); + _sent -= (toSend - sent); + _ack -= (toSend - sent); + } + // ets_printf("S: %u %u\n", _sent, sent); + return sent; +} + +/* + * Async WebSocket Client + */ +const char* AWSC_PING_PAYLOAD = "ESPAsyncWebServer-PING"; +const size_t AWSC_PING_PAYLOAD_LEN = 22; + +AsyncWebSocketClient::AsyncWebSocketClient(AsyncWebServerRequest* request, AsyncWebSocket* server) + : _tempObject(NULL) { + _client = request->client(); + _server = server; + _clientId = _server->_getNextId(); + _status = WS_CONNECTED; + _pstate = 0; + _lastMessageTime = millis(); + _keepAlivePeriod = 0; + _client->setRxTimeout(0); + _client->onError([](void* r, AsyncClient* c, int8_t error) { (void)c; ((AsyncWebSocketClient*)(r))->_onError(error); }, this); + _client->onAck([](void* r, AsyncClient* c, size_t len, uint32_t time) { (void)c; ((AsyncWebSocketClient*)(r))->_onAck(len, time); }, this); + _client->onDisconnect([](void* r, AsyncClient* c) { ((AsyncWebSocketClient*)(r))->_onDisconnect(); delete c; }, this); + _client->onTimeout([](void* r, AsyncClient* c, uint32_t time) { (void)c; ((AsyncWebSocketClient*)(r))->_onTimeout(time); }, this); + _client->onData([](void* r, AsyncClient* c, void* buf, size_t len) { (void)c; ((AsyncWebSocketClient*)(r))->_onData(buf, len); }, this); + _client->onPoll([](void* r, AsyncClient* c) { (void)c; ((AsyncWebSocketClient*)(r))->_onPoll(); }, this); + _server->_handleEvent(this, WS_EVT_CONNECT, request, NULL, 0); + delete request; + memset(&_pinfo, 0, sizeof(_pinfo)); +} + +AsyncWebSocketClient::~AsyncWebSocketClient() { + { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + _messageQueue.clear(); + _controlQueue.clear(); + } + _server->_handleEvent(this, WS_EVT_DISCONNECT, NULL, NULL, 0); +} + +void AsyncWebSocketClient::_clearQueue() { + while (!_messageQueue.empty() && _messageQueue.front().finished()) + _messageQueue.pop_front(); +} + +void AsyncWebSocketClient::_onAck(size_t len, uint32_t time) { + _lastMessageTime = millis(); + +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + + if (!_controlQueue.empty()) { + auto& head = _controlQueue.front(); + if (head.finished()) { + len -= head.len(); + if (_status == WS_DISCONNECTING && head.opcode() == WS_DISCONNECT) { + _controlQueue.pop_front(); + _status = WS_DISCONNECTED; + if (_client) + _client->close(true); + return; + } + _controlQueue.pop_front(); + } + } + + if (len && !_messageQueue.empty()) { + _messageQueue.front().ack(len, time); + } + + _clearQueue(); + + _runQueue(); +} + +void AsyncWebSocketClient::_onPoll() { + if (!_client) + return; + +#ifdef ESP32 + std::unique_lock lock(_lock); +#endif + if (_client->canSend() && (!_controlQueue.empty() || !_messageQueue.empty())) { + _runQueue(); + } else if (_keepAlivePeriod > 0 && (millis() - _lastMessageTime) >= _keepAlivePeriod && (_controlQueue.empty() && _messageQueue.empty())) { +#ifdef ESP32 + lock.unlock(); +#endif + ping((uint8_t*)AWSC_PING_PAYLOAD, AWSC_PING_PAYLOAD_LEN); + } +} + +void AsyncWebSocketClient::_runQueue() { + // all calls to this method MUST be protected by a mutex lock! + if (!_client) + return; + + _clearQueue(); + + if (!_controlQueue.empty() && (_messageQueue.empty() || _messageQueue.front().betweenFrames()) && webSocketSendFrameWindow(_client) > (size_t)(_controlQueue.front().len() - 1)) { + _controlQueue.front().send(_client); + } else if (!_messageQueue.empty() && _messageQueue.front().betweenFrames() && webSocketSendFrameWindow(_client)) { + _messageQueue.front().send(_client); + } +} + +bool AsyncWebSocketClient::queueIsFull() const { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + size_t size = _messageQueue.size(); + ; + return (size >= WS_MAX_QUEUED_MESSAGES) || (_status != WS_CONNECTED); +} + +size_t AsyncWebSocketClient::queueLen() const { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + + return _messageQueue.size() + _controlQueue.size(); +} + +bool AsyncWebSocketClient::canSend() const { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + return _messageQueue.size() < WS_MAX_QUEUED_MESSAGES; +} + +void AsyncWebSocketClient::_queueControl(uint8_t opcode, const uint8_t* data, size_t len, bool mask) { + if (!_client) + return; + + { +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + _controlQueue.emplace_back(opcode, data, len, mask); + } + + if (_client && _client->canSend()) + _runQueue(); +} + +void AsyncWebSocketClient::_queueMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode, bool mask) { + if (!_client || buffer->size() == 0 || _status != WS_CONNECTED) + return; + +#ifdef ESP32 + std::lock_guard lock(_lock); +#endif + if (_messageQueue.size() >= WS_MAX_QUEUED_MESSAGES) { + if (closeWhenFull) { +#ifdef ESP8266 + ets_printf("AsyncWebSocketClient::_queueMessage: Too many messages queued: closing connection\n"); +#elif defined(ESP32) + log_e("Too many messages queued: closing connection"); +#endif + _status = WS_DISCONNECTED; + if (_client) + _client->close(true); + } else { +#ifdef ESP8266 + ets_printf("AsyncWebSocketClient::_queueMessage: Too many messages queued: discarding new message\n"); +#elif defined(ESP32) + log_e("Too many messages queued: discarding new message"); +#endif + } + return; + } else { + _messageQueue.emplace_back(buffer, opcode, mask); + } + + if (_client && _client->canSend()) + _runQueue(); +} + +void AsyncWebSocketClient::close(uint16_t code, const char* message) { + if (_status != WS_CONNECTED) + return; + + if (code) { + uint8_t packetLen = 2; + if (message != NULL) { + size_t mlen = strlen(message); + if (mlen > 123) + mlen = 123; + packetLen += mlen; + } + char* buf = (char*)malloc(packetLen); + if (buf != NULL) { + buf[0] = (uint8_t)(code >> 8); + buf[1] = (uint8_t)(code & 0xFF); + if (message != NULL) { + memcpy(buf + 2, message, packetLen - 2); + } + _queueControl(WS_DISCONNECT, (uint8_t*)buf, packetLen); + free(buf); + return; + } + } + _queueControl(WS_DISCONNECT); +} + +void AsyncWebSocketClient::ping(const uint8_t* data, size_t len) { + if (_status == WS_CONNECTED) + _queueControl(WS_PING, data, len); +} + +void AsyncWebSocketClient::_onError(int8_t) { + // Serial.println("onErr"); +} + +void AsyncWebSocketClient::_onTimeout(uint32_t time) { + // Serial.println("onTime"); + (void)time; + _client->close(true); +} + +void AsyncWebSocketClient::_onDisconnect() { + // Serial.println("onDis"); + _client = NULL; +} + +void AsyncWebSocketClient::_onData(void* pbuf, size_t plen) { + // Serial.println("onData"); + _lastMessageTime = millis(); + uint8_t* data = (uint8_t*)pbuf; + while (plen > 0) { + if (!_pstate) { + const uint8_t* fdata = data; + _pinfo.index = 0; + _pinfo.final = (fdata[0] & 0x80) != 0; + _pinfo.opcode = fdata[0] & 0x0F; + _pinfo.masked = (fdata[1] & 0x80) != 0; + _pinfo.len = fdata[1] & 0x7F; + data += 2; + plen -= 2; + if (_pinfo.len == 126) { + _pinfo.len = fdata[3] | (uint16_t)(fdata[2]) << 8; + data += 2; + plen -= 2; + } else if (_pinfo.len == 127) { + _pinfo.len = fdata[9] | (uint16_t)(fdata[8]) << 8 | (uint32_t)(fdata[7]) << 16 | (uint32_t)(fdata[6]) << 24 | (uint64_t)(fdata[5]) << 32 | (uint64_t)(fdata[4]) << 40 | (uint64_t)(fdata[3]) << 48 | (uint64_t)(fdata[2]) << 56; + data += 8; + plen -= 8; + } + + if (_pinfo.masked) { + memcpy(_pinfo.mask, data, 4); + data += 4; + plen -= 4; + } + } + + const size_t datalen = std::min((size_t)(_pinfo.len - _pinfo.index), plen); + const auto datalast = data[datalen]; + + if (_pinfo.masked) { + for (size_t i = 0; i < datalen; i++) + data[i] ^= _pinfo.mask[(_pinfo.index + i) % 4]; + } + + if ((datalen + _pinfo.index) < _pinfo.len) { + _pstate = 1; + + if (_pinfo.index == 0) { + if (_pinfo.opcode) { + _pinfo.message_opcode = _pinfo.opcode; + _pinfo.num = 0; + } + } + if (datalen > 0) + _server->_handleEvent(this, WS_EVT_DATA, (void*)&_pinfo, (uint8_t*)data, datalen); + + _pinfo.index += datalen; + } else if ((datalen + _pinfo.index) == _pinfo.len) { + _pstate = 0; + if (_pinfo.opcode == WS_DISCONNECT) { + if (datalen) { + uint16_t reasonCode = (uint16_t)(data[0] << 8) + data[1]; + char* reasonString = (char*)(data + 2); + if (reasonCode > 1001) { + _server->_handleEvent(this, WS_EVT_ERROR, (void*)&reasonCode, (uint8_t*)reasonString, strlen(reasonString)); + } + } + if (_status == WS_DISCONNECTING) { + _status = WS_DISCONNECTED; + _client->close(true); + } else { + _status = WS_DISCONNECTING; + _client->ackLater(); + _queueControl(WS_DISCONNECT, data, datalen); + } + } else if (_pinfo.opcode == WS_PING) { + _queueControl(WS_PONG, data, datalen); + } else if (_pinfo.opcode == WS_PONG) { + if (datalen != AWSC_PING_PAYLOAD_LEN || memcmp(AWSC_PING_PAYLOAD, data, AWSC_PING_PAYLOAD_LEN) != 0) + _server->_handleEvent(this, WS_EVT_PONG, NULL, data, datalen); + } else if (_pinfo.opcode < 8) { // continuation or text/binary frame + _server->_handleEvent(this, WS_EVT_DATA, (void*)&_pinfo, data, datalen); + if (_pinfo.final) + _pinfo.num = 0; + else + _pinfo.num += 1; + } + } else { + // os_printf("frame error: len: %u, index: %llu, total: %llu\n", datalen, _pinfo.index, _pinfo.len); + // what should we do? + break; + } + + // restore byte as _handleEvent may have added a null terminator i.e., data[len] = 0; + if (datalen > 0) + data[datalen] = datalast; + + data += datalen; + plen -= datalen; + } +} + +size_t AsyncWebSocketClient::printf(const char* format, ...) { + va_list arg; + va_start(arg, format); + char* temp = new char[MAX_PRINTF_LEN]; + if (!temp) { + va_end(arg); + return 0; + } + char* buffer = temp; + size_t len = vsnprintf(temp, MAX_PRINTF_LEN, format, arg); + va_end(arg); + + if (len > (MAX_PRINTF_LEN - 1)) { + buffer = new char[len + 1]; + if (!buffer) { + delete[] temp; + return 0; + } + va_start(arg, format); + vsnprintf(buffer, len + 1, format, arg); + va_end(arg); + } + text(buffer, len); + if (buffer != temp) { + delete[] buffer; + } + delete[] temp; + return len; +} + +#ifndef ESP32 +size_t AsyncWebSocketClient::printf_P(PGM_P formatP, ...) { + va_list arg; + va_start(arg, formatP); + char* temp = new char[MAX_PRINTF_LEN]; + if (!temp) { + va_end(arg); + return 0; + } + char* buffer = temp; + size_t len = vsnprintf_P(temp, MAX_PRINTF_LEN, formatP, arg); + va_end(arg); + + if (len > (MAX_PRINTF_LEN - 1)) { + buffer = new char[len + 1]; + if (!buffer) { + delete[] temp; + return 0; + } + va_start(arg, formatP); + vsnprintf_P(buffer, len + 1, formatP, arg); + va_end(arg); + } + text(buffer, len); + if (buffer != temp) { + delete[] buffer; + } + delete[] temp; + return len; +} +#endif + +namespace { + AsyncWebSocketSharedBuffer makeSharedBuffer(const uint8_t* message, size_t len) { + auto buffer = std::make_shared>(len); + std::memcpy(buffer->data(), message, len); + return buffer; + } +} + +void AsyncWebSocketClient::text(AsyncWebSocketMessageBuffer* buffer) { + if (buffer) { + text(std::move(buffer->_buffer)); + delete buffer; + } +} + +void AsyncWebSocketClient::text(AsyncWebSocketSharedBuffer buffer) { + _queueMessage(buffer); +} + +void AsyncWebSocketClient::text(const uint8_t* message, size_t len) { + text(makeSharedBuffer(message, len)); +} + +void AsyncWebSocketClient::text(const char* message, size_t len) { + text((const uint8_t*)message, len); +} + +void AsyncWebSocketClient::text(const char* message) { + text(message, strlen(message)); +} + +void AsyncWebSocketClient::text(const String& message) { + text(message.c_str(), message.length()); +} + +#ifndef ESP32 +void AsyncWebSocketClient::text(const __FlashStringHelper* data) { + PGM_P p = reinterpret_cast(data); + + size_t n = 0; + while (1) { + if (pgm_read_byte(p + n) == 0) + break; + n += 1; + } + + char* message = (char*)malloc(n + 1); + if (message) { + memcpy_P(message, p, n); + message[n] = 0; + text(message, n); + free(message); + } +} +#endif // ESP32 + +void AsyncWebSocketClient::binary(AsyncWebSocketMessageBuffer* buffer) { + if (buffer) { + binary(std::move(buffer->_buffer)); + delete buffer; + } +} + +void AsyncWebSocketClient::binary(AsyncWebSocketSharedBuffer buffer) { + _queueMessage(buffer, WS_BINARY); +} + +void AsyncWebSocketClient::binary(const uint8_t* message, size_t len) { + binary(makeSharedBuffer(message, len)); +} + +void AsyncWebSocketClient::binary(const char* message, size_t len) { + binary((const uint8_t*)message, len); +} + +void AsyncWebSocketClient::binary(const char* message) { + binary(message, strlen(message)); +} + +void AsyncWebSocketClient::binary(const String& message) { + binary(message.c_str(), message.length()); +} + +#ifndef ESP32 +void AsyncWebSocketClient::binary(const __FlashStringHelper* data, size_t len) { + PGM_P p = reinterpret_cast(data); + char* message = (char*)malloc(len); + if (message) { + memcpy_P(message, p, len); + binary(message, len); + free(message); + } +} +#endif +IPAddress AsyncWebSocketClient::remoteIP() const { + if (!_client) + return IPAddress((uint32_t)0U); + + return _client->remoteIP(); +} + +uint16_t AsyncWebSocketClient::remotePort() const { + if (!_client) + return 0; + + return _client->remotePort(); +} + +/* + * Async Web Socket - Each separate socket location + */ + +void AsyncWebSocket::_handleEvent(AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) { + if (_eventHandler != NULL) { + _eventHandler(this, client, type, arg, data, len); + } +} + +AsyncWebSocketClient* AsyncWebSocket::_newClient(AsyncWebServerRequest* request) { + _clients.emplace_back(request, this); + return &_clients.back(); +} + +bool AsyncWebSocket::availableForWriteAll() { + return std::none_of(std::begin(_clients), std::end(_clients), [](const AsyncWebSocketClient& c) { return c.queueIsFull(); }); +} + +bool AsyncWebSocket::availableForWrite(uint32_t id) { + const auto iter = std::find_if(std::begin(_clients), std::end(_clients), [id](const AsyncWebSocketClient& c) { return c.id() == id; }); + if (iter == std::end(_clients)) + return true; + return !iter->queueIsFull(); +} + +size_t AsyncWebSocket::count() const { + return std::count_if(std::begin(_clients), std::end(_clients), [](const AsyncWebSocketClient& c) { return c.status() == WS_CONNECTED; }); +} + +AsyncWebSocketClient* AsyncWebSocket::client(uint32_t id) { + const auto iter = std::find_if(_clients.begin(), _clients.end(), [id](const AsyncWebSocketClient& c) { return c.id() == id && c.status() == WS_CONNECTED; }); + if (iter == std::end(_clients)) + return nullptr; + + return &(*iter); +} + +void AsyncWebSocket::close(uint32_t id, uint16_t code, const char* message) { + if (AsyncWebSocketClient* c = client(id)) + c->close(code, message); +} + +void AsyncWebSocket::closeAll(uint16_t code, const char* message) { + for (auto& c : _clients) + if (c.status() == WS_CONNECTED) + c.close(code, message); +} + +void AsyncWebSocket::cleanupClients(uint16_t maxClients) { + if (count() > maxClients) + _clients.front().close(); + + for (auto iter = std::begin(_clients); iter != std::end(_clients);) { + if (iter->shouldBeDeleted()) + iter = _clients.erase(iter); + else + iter++; + } +} + +void AsyncWebSocket::ping(uint32_t id, const uint8_t* data, size_t len) { + if (AsyncWebSocketClient* c = client(id)) + c->ping(data, len); +} + +void AsyncWebSocket::pingAll(const uint8_t* data, size_t len) { + for (auto& c : _clients) + if (c.status() == WS_CONNECTED) + c.ping(data, len); +} + +void AsyncWebSocket::text(uint32_t id, const uint8_t* message, size_t len) { + if (AsyncWebSocketClient* c = client(id)) + c->text(makeSharedBuffer(message, len)); +} +void AsyncWebSocket::text(uint32_t id, const char* message, size_t len) { + text(id, (const uint8_t*)message, len); +} +void AsyncWebSocket::text(uint32_t id, const char* message) { + text(id, message, strlen(message)); +} +void AsyncWebSocket::text(uint32_t id, const String& message) { + text(id, message.c_str(), message.length()); +} +#ifndef ESP32 +void AsyncWebSocket::text(uint32_t id, const __FlashStringHelper* data) { + PGM_P p = reinterpret_cast(data); + + size_t n = 0; + while (true) { + if (pgm_read_byte(p + n) == 0) + break; + n += 1; + } + + char* message = (char*)malloc(n + 1); + if (message) { + memcpy_P(message, p, n); + message[n] = 0; + text(id, message, n); + free(message); + } +} +#endif // ESP32 +void AsyncWebSocket::text(uint32_t id, AsyncWebSocketMessageBuffer* buffer) { + if (buffer) { + text(id, std::move(buffer->_buffer)); + delete buffer; + } +} +void AsyncWebSocket::text(uint32_t id, AsyncWebSocketSharedBuffer buffer) { + if (AsyncWebSocketClient* c = client(id)) + c->text(buffer); +} + +void AsyncWebSocket::textAll(const uint8_t* message, size_t len) { + textAll(makeSharedBuffer(message, len)); +} +void AsyncWebSocket::textAll(const char* message, size_t len) { + textAll((const uint8_t*)message, len); +} +void AsyncWebSocket::textAll(const char* message) { + textAll(message, strlen(message)); +} +void AsyncWebSocket::textAll(const String& message) { + textAll(message.c_str(), message.length()); +} +#ifndef ESP32 +void AsyncWebSocket::textAll(const __FlashStringHelper* data) { + PGM_P p = reinterpret_cast(data); + + size_t n = 0; + while (1) { + if (pgm_read_byte(p + n) == 0) + break; + n += 1; + } + + char* message = (char*)malloc(n + 1); + if (message) { + memcpy_P(message, p, n); + message[n] = 0; + textAll(message, n); + free(message); + } +} +#endif // ESP32 +void AsyncWebSocket::textAll(AsyncWebSocketMessageBuffer* buffer) { + if (buffer) { + textAll(std::move(buffer->_buffer)); + delete buffer; + } +} + +void AsyncWebSocket::textAll(AsyncWebSocketSharedBuffer buffer) { + for (auto& c : _clients) + if (c.status() == WS_CONNECTED) + c.text(buffer); +} + +void AsyncWebSocket::binary(uint32_t id, const uint8_t* message, size_t len) { + if (AsyncWebSocketClient* c = client(id)) + c->binary(makeSharedBuffer(message, len)); +} +void AsyncWebSocket::binary(uint32_t id, const char* message, size_t len) { + binary(id, (const uint8_t*)message, len); +} +void AsyncWebSocket::binary(uint32_t id, const char* message) { + binary(id, message, strlen(message)); +} +void AsyncWebSocket::binary(uint32_t id, const String& message) { + binary(id, message.c_str(), message.length()); +} +#ifndef ESP32 +void AsyncWebSocket::binary(uint32_t id, const __FlashStringHelper* data, size_t len) { + PGM_P p = reinterpret_cast(data); + char* message = (char*)malloc(len); + if (message) { + memcpy_P(message, p, len); + binary(id, message, len); + free(message); + } +} +#endif // ESP32 +void AsyncWebSocket::binary(uint32_t id, AsyncWebSocketMessageBuffer* buffer) { + if (buffer) { + binary(id, std::move(buffer->_buffer)); + delete buffer; + } +} +void AsyncWebSocket::binary(uint32_t id, AsyncWebSocketSharedBuffer buffer) { + if (AsyncWebSocketClient* c = client(id)) + c->binary(buffer); +} + +void AsyncWebSocket::binaryAll(const uint8_t* message, size_t len) { + binaryAll(makeSharedBuffer(message, len)); +} +void AsyncWebSocket::binaryAll(const char* message, size_t len) { + binaryAll((const uint8_t*)message, len); +} +void AsyncWebSocket::binaryAll(const char* message) { + binaryAll(message, strlen(message)); +} +void AsyncWebSocket::binaryAll(const String& message) { + binaryAll(message.c_str(), message.length()); +} +#ifndef ESP32 +void AsyncWebSocket::binaryAll(const __FlashStringHelper* data, size_t len) { + PGM_P p = reinterpret_cast(data); + char* message = (char*)malloc(len); + if (message) { + memcpy_P(message, p, len); + binaryAll(message, len); + free(message); + } +} +#endif // ESP32 +void AsyncWebSocket::binaryAll(AsyncWebSocketMessageBuffer* buffer) { + if (buffer) { + binaryAll(std::move(buffer->_buffer)); + delete buffer; + } +} +void AsyncWebSocket::binaryAll(AsyncWebSocketSharedBuffer buffer) { + for (auto& c : _clients) + if (c.status() == WS_CONNECTED) + c.binary(buffer); +} + +size_t AsyncWebSocket::printf(uint32_t id, const char* format, ...) { + AsyncWebSocketClient* c = client(id); + if (c) { + va_list arg; + va_start(arg, format); + size_t len = c->printf(format, arg); + va_end(arg); + return len; + } + return 0; +} + +size_t AsyncWebSocket::printfAll(const char* format, ...) { + va_list arg; + char* temp = new char[MAX_PRINTF_LEN]; + if (!temp) + return 0; + + va_start(arg, format); + size_t len = vsnprintf(temp, MAX_PRINTF_LEN, format, arg); + va_end(arg); + delete[] temp; + + AsyncWebSocketSharedBuffer buffer = std::make_shared>(len); + + va_start(arg, format); + vsnprintf((char*)buffer->data(), len + 1, format, arg); + va_end(arg); + + textAll(buffer); + return len; +} + +#ifndef ESP32 +size_t AsyncWebSocket::printf_P(uint32_t id, PGM_P formatP, ...) { + AsyncWebSocketClient* c = client(id); + if (c != NULL) { + va_list arg; + va_start(arg, formatP); + size_t len = c->printf_P(formatP, arg); + va_end(arg); + return len; + } + return 0; +} + +size_t AsyncWebSocket::printfAll_P(PGM_P formatP, ...) { + va_list arg; + char* temp = new char[MAX_PRINTF_LEN]; + if (!temp) + return 0; + + va_start(arg, formatP); + size_t len = vsnprintf_P(temp, MAX_PRINTF_LEN, formatP, arg); + va_end(arg); + delete[] temp; + + AsyncWebSocketSharedBuffer buffer = std::make_shared>(len + 1); + + va_start(arg, formatP); + vsnprintf_P((char*)buffer->data(), len + 1, formatP, arg); + va_end(arg); + + textAll(buffer); + return len; +} +#endif + +const char __WS_STR_CONNECTION[] PROGMEM = {"Connection"}; +const char __WS_STR_UPGRADE[] PROGMEM = {"Upgrade"}; +const char __WS_STR_ORIGIN[] PROGMEM = {"Origin"}; +const char __WS_STR_COOKIE[] PROGMEM = {"Cookie"}; +const char __WS_STR_VERSION[] PROGMEM = {"Sec-WebSocket-Version"}; +const char __WS_STR_KEY[] PROGMEM = {"Sec-WebSocket-Key"}; +const char __WS_STR_PROTOCOL[] PROGMEM = {"Sec-WebSocket-Protocol"}; +const char __WS_STR_ACCEPT[] PROGMEM = {"Sec-WebSocket-Accept"}; +const char __WS_STR_UUID[] PROGMEM = {"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"}; + +#define WS_STR_UUID_LEN 36 + +#define WS_STR_CONNECTION FPSTR(__WS_STR_CONNECTION) +#define WS_STR_UPGRADE FPSTR(__WS_STR_UPGRADE) +#define WS_STR_ORIGIN FPSTR(__WS_STR_ORIGIN) +#define WS_STR_COOKIE FPSTR(__WS_STR_COOKIE) +#define WS_STR_VERSION FPSTR(__WS_STR_VERSION) +#define WS_STR_KEY FPSTR(__WS_STR_KEY) +#define WS_STR_PROTOCOL FPSTR(__WS_STR_PROTOCOL) +#define WS_STR_ACCEPT FPSTR(__WS_STR_ACCEPT) +#define WS_STR_UUID FPSTR(__WS_STR_UUID) + +bool AsyncWebSocket::canHandle(AsyncWebServerRequest* request) { + if (!_enabled) + return false; + + if (request->method() != HTTP_GET || !request->url().equals(_url) || !request->isExpectedRequestedConnType(RCT_WS)) + return false; + + request->addInterestingHeader(WS_STR_CONNECTION); + request->addInterestingHeader(WS_STR_UPGRADE); + request->addInterestingHeader(WS_STR_ORIGIN); + request->addInterestingHeader(WS_STR_COOKIE); + request->addInterestingHeader(WS_STR_VERSION); + request->addInterestingHeader(WS_STR_KEY); + request->addInterestingHeader(WS_STR_PROTOCOL); + return true; +} + +void AsyncWebSocket::handleRequest(AsyncWebServerRequest* request) { + if (!request->hasHeader(WS_STR_VERSION) || !request->hasHeader(WS_STR_KEY)) { + request->send(400); + return; + } + if ((_username.length() && _password.length()) && !request->authenticate(_username.c_str(), _password.c_str())) { + return request->requestAuthentication(); + } + if (_handshakeHandler != nullptr) { + if (!_handshakeHandler(request)) { + request->send(401); + return; + } + } + const AsyncWebHeader* version = request->getHeader(WS_STR_VERSION); + if (version->value().toInt() != 13) { + AsyncWebServerResponse* response = request->beginResponse(400); + response->addHeader(WS_STR_VERSION, F("13")); + request->send(response); + return; + } + const AsyncWebHeader* key = request->getHeader(WS_STR_KEY); + AsyncWebServerResponse* response = new AsyncWebSocketResponse(key->value(), this); + if (request->hasHeader(WS_STR_PROTOCOL)) { + const AsyncWebHeader* protocol = request->getHeader(WS_STR_PROTOCOL); + // ToDo: check protocol + response->addHeader(WS_STR_PROTOCOL, protocol->value()); + } + request->send(response); +} + +AsyncWebSocketMessageBuffer* AsyncWebSocket::makeBuffer(size_t size) { + AsyncWebSocketMessageBuffer* buffer = new AsyncWebSocketMessageBuffer(size); + if (buffer->length() != size) { + delete buffer; + return nullptr; + } else { + return buffer; + } +} + +AsyncWebSocketMessageBuffer* AsyncWebSocket::makeBuffer(const uint8_t* data, size_t size) { + AsyncWebSocketMessageBuffer* buffer = new AsyncWebSocketMessageBuffer(data, size); + if (buffer->length() != size) { + delete buffer; + return nullptr; + } else { + return buffer; + } +} + +/* + * Response to Web Socket request - sends the authorization and detaches the TCP Client from the web server + * Authentication code from https://github.com/Links2004/arduinoWebSockets/blob/master/src/WebSockets.cpp#L480 + */ + +AsyncWebSocketResponse::AsyncWebSocketResponse(const String& key, AsyncWebSocket* server) { + _server = server; + _code = 101; + _sendContentLength = false; + + uint8_t hash[20]; + char buffer[33]; + +#if defined(ESP8266) || defined(TARGET_RP2040) + sha1(key + WS_STR_UUID, hash); +#else + String k; + k.reserve(key.length() + WS_STR_UUID_LEN); + k.concat(key); + k.concat(WS_STR_UUID); + SHA1Builder sha1; + sha1.begin(); + sha1.add((const uint8_t*)k.c_str(), k.length()); + sha1.calculate(); + sha1.getBytes(hash); +#endif + base64_encodestate _state; + base64_init_encodestate(&_state); + int len = base64_encode_block((const char*)hash, 20, buffer, &_state); + len = base64_encode_blockend((buffer + len), &_state); + addHeader(WS_STR_CONNECTION, WS_STR_UPGRADE); + addHeader(WS_STR_UPGRADE, F("websocket")); + addHeader(WS_STR_ACCEPT, buffer); +} + +void AsyncWebSocketResponse::_respond(AsyncWebServerRequest* request) { + if (_state == RESPONSE_FAILED) { + request->client()->close(true); + return; + } + String out(_assembleHead(request->version())); + request->client()->write(out.c_str(), _headLength); + _state = RESPONSE_WAIT_ACK; +} + +size_t AsyncWebSocketResponse::_ack(AsyncWebServerRequest* request, size_t len, uint32_t time) { + (void)time; + + if (len) + _server->_newClient(request); + + return 0; +} diff --git a/lib/ESP Async WebServer/src/AsyncWebSocket.h b/lib/ESP Async WebServer/src/AsyncWebSocket.h new file mode 100644 index 0000000..77bf7ee --- /dev/null +++ b/lib/ESP Async WebServer/src/AsyncWebSocket.h @@ -0,0 +1,390 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#ifndef ASYNCWEBSOCKET_H_ +#define ASYNCWEBSOCKET_H_ + +#include +#ifdef ESP32 + #include + #include + #ifndef WS_MAX_QUEUED_MESSAGES + #define WS_MAX_QUEUED_MESSAGES 32 + #endif +#elif defined(ESP8266) + #include + #ifndef WS_MAX_QUEUED_MESSAGES + #define WS_MAX_QUEUED_MESSAGES 8 + #endif +#elif defined(TARGET_RP2040) + #include + #ifndef WS_MAX_QUEUED_MESSAGES + #define WS_MAX_QUEUED_MESSAGES 32 + #endif +#endif + +#include + +#include +#include +#include + +#ifdef ESP8266 + #include + #ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library + #include <../src/Hash.h> + #endif +#endif + +#ifndef DEFAULT_MAX_WS_CLIENTS + #ifdef ESP32 + #define DEFAULT_MAX_WS_CLIENTS 8 + #else + #define DEFAULT_MAX_WS_CLIENTS 4 + #endif +#endif + +using AsyncWebSocketSharedBuffer = std::shared_ptr>; + +class AsyncWebSocket; +class AsyncWebSocketResponse; +class AsyncWebSocketClient; +class AsyncWebSocketControl; + +typedef struct { + /** Message type as defined by enum AwsFrameType. + * Note: Applications will only see WS_TEXT and WS_BINARY. + * All other types are handled by the library. */ + uint8_t message_opcode; + /** Frame number of a fragmented message. */ + uint32_t num; + /** Is this the last frame in a fragmented message ?*/ + uint8_t final; + /** Is this frame masked? */ + uint8_t masked; + /** Message type as defined by enum AwsFrameType. + * This value is the same as message_opcode for non-fragmented + * messages, but may also be WS_CONTINUATION in a fragmented message. */ + uint8_t opcode; + /** Length of the current frame. + * This equals the total length of the message if num == 0 && final == true */ + uint64_t len; + /** Mask key */ + uint8_t mask[4]; + /** Offset of the data inside the current frame. */ + uint64_t index; +} AwsFrameInfo; + +typedef enum { WS_DISCONNECTED, + WS_CONNECTED, + WS_DISCONNECTING } AwsClientStatus; +typedef enum { WS_CONTINUATION, + WS_TEXT, + WS_BINARY, + WS_DISCONNECT = 0x08, + WS_PING, + WS_PONG } AwsFrameType; +typedef enum { WS_MSG_SENDING, + WS_MSG_SENT, + WS_MSG_ERROR } AwsMessageStatus; +typedef enum { WS_EVT_CONNECT, + WS_EVT_DISCONNECT, + WS_EVT_PONG, + WS_EVT_ERROR, + WS_EVT_DATA } AwsEventType; + +class AsyncWebSocketMessageBuffer { + friend AsyncWebSocket; + friend AsyncWebSocketClient; + + private: + AsyncWebSocketSharedBuffer _buffer; + + public: + AsyncWebSocketMessageBuffer() {} + explicit AsyncWebSocketMessageBuffer(size_t size); + AsyncWebSocketMessageBuffer(const uint8_t* data, size_t size); + //~AsyncWebSocketMessageBuffer(); + bool reserve(size_t size); + uint8_t* get() { return _buffer->data(); } + size_t length() const { return _buffer->size(); } +}; + +class AsyncWebSocketMessage { + private: + AsyncWebSocketSharedBuffer _WSbuffer; + uint8_t _opcode{WS_TEXT}; + bool _mask{false}; + AwsMessageStatus _status{WS_MSG_ERROR}; + size_t _sent{}; + size_t _ack{}; + size_t _acked{}; + + public: + AsyncWebSocketMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false); + + bool finished() const { return _status != WS_MSG_SENDING; } + bool betweenFrames() const { return _acked == _ack; } + + void ack(size_t len, uint32_t time); + size_t send(AsyncClient* client); +}; + +class AsyncWebSocketClient { + private: + AsyncClient* _client; + AsyncWebSocket* _server; + uint32_t _clientId; + AwsClientStatus _status; +#ifdef ESP32 + mutable std::mutex _lock; +#endif + std::deque _controlQueue; + std::deque _messageQueue; + bool closeWhenFull = true; + + uint8_t _pstate; + AwsFrameInfo _pinfo; + + uint32_t _lastMessageTime; + uint32_t _keepAlivePeriod; + + void _queueControl(uint8_t opcode, const uint8_t* data = NULL, size_t len = 0, bool mask = false); + void _queueMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false); + void _runQueue(); + void _clearQueue(); + + public: + void* _tempObject; + + AsyncWebSocketClient(AsyncWebServerRequest* request, AsyncWebSocket* server); + ~AsyncWebSocketClient(); + + // client id increments for the given server + uint32_t id() const { return _clientId; } + AwsClientStatus status() const { return _status; } + AsyncClient* client() { return _client; } + const AsyncClient* client() const { return _client; } + AsyncWebSocket* server() { return _server; } + const AsyncWebSocket* server() const { return _server; } + AwsFrameInfo const& pinfo() const { return _pinfo; } + + // - If "true" (default), the connection will be closed if the message queue is full. + // This is the default behavior in yubox-node-org, which is not silently discarding messages but instead closes the connection. + // The big issue with this behavior is that is can cause the UI to automatically re-create a new WS connection, which can be filled again, + // and so on, causing a resource exhaustion. + // + // - If "false", the incoming message will be discarded if the queue is full. + // This is the default behavior in the original ESPAsyncWebServer library from me-no-dev. + // This behavior allows the best performance at the expense of unreliable message delivery in case the queue is full (some messages may be lost). + // + // - In any case, when the queue is full, a message is logged. + // - IT is recommended to use the methods queueIsFull(), availableForWriteAll(), availableForWrite(clientId) to check if the queue is full before sending a message. + // + // Usage: + // - can be set in the onEvent listener when connecting (event type is: WS_EVT_CONNECT) + // + // Use cases:, + // - if using websocket to send logging messages, maybe some loss is acceptable. + // - But if using websocket to send UI update messages, maybe the connection should be closed and the UI redrawn. + void setCloseClientOnQueueFull(bool close) { closeWhenFull = close; } + bool willCloseClientOnQueueFull() const { return closeWhenFull; } + + IPAddress remoteIP() const; + uint16_t remotePort() const; + + bool shouldBeDeleted() const { return !_client; } + + // control frames + void close(uint16_t code = 0, const char* message = NULL); + void ping(const uint8_t* data = NULL, size_t len = 0); + + // set auto-ping period in seconds. disabled if zero (default) + void keepAlivePeriod(uint16_t seconds) { + _keepAlivePeriod = seconds * 1000; + } + uint16_t keepAlivePeriod() { + return (uint16_t)(_keepAlivePeriod / 1000); + } + + // data packets + void message(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false) { _queueMessage(buffer, opcode, mask); } + bool queueIsFull() const; + size_t queueLen() const; + + size_t printf(const char* format, ...) __attribute__((format(printf, 2, 3))); +#ifndef ESP32 + size_t printf_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); +#endif + + void text(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); + void binary(const uint8_t* message, size_t len); + 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; + + // system callbacks (do not call) + void _onAck(size_t len, uint32_t time); + void _onError(int8_t); + void _onPoll(); + void _onTimeout(uint32_t time); + void _onDisconnect(); + void _onData(void* pbuf, size_t plen); +}; + +using AwsHandshakeHandler = std::function; +using AwsEventHandler = std::function; + +// WebServer Handler implementation that plays the role of a socket server +class AsyncWebSocket : public AsyncWebHandler { + private: + String _url; + std::list _clients; + uint32_t _cNextId; + AwsEventHandler _eventHandler{nullptr}; + AwsHandshakeHandler _handshakeHandler; + bool _enabled; +#ifdef ESP32 + mutable std::mutex _lock; +#endif + + public: + explicit AsyncWebSocket(const char* url) : _url(url), _cNextId(1), _enabled(true) {} + AsyncWebSocket(const String& url) : _url(url), _cNextId(1), _enabled(true) {} + ~AsyncWebSocket(){}; + const char* url() const { return _url.c_str(); } + void enable(bool e) { _enabled = e; } + bool enabled() const { return _enabled; } + bool availableForWriteAll(); + bool availableForWrite(uint32_t id); + + size_t count() const; + AsyncWebSocketClient* client(uint32_t id); + bool hasClient(uint32_t id) { return client(id) != nullptr; } + + void close(uint32_t id, uint16_t code = 0, const char* message = NULL); + void closeAll(uint16_t code = 0, const char* message = NULL); + void cleanupClients(uint16_t maxClients = DEFAULT_MAX_WS_CLIENTS); + + void ping(uint32_t id, const uint8_t* data = NULL, size_t len = 0); + void pingAll(const uint8_t* data = NULL, size_t len = 0); // done + + void text(uint32_t id, const uint8_t* message, size_t len); + void text(uint32_t id, const char* message, size_t len); + void text(uint32_t id, const char* message); + void text(uint32_t id, const String& message); +#ifndef ESP32 + void text(uint32_t id, const __FlashStringHelper* message); +#endif // ESP32 + void text(uint32_t id, AsyncWebSocketMessageBuffer* buffer); + void text(uint32_t id, AsyncWebSocketSharedBuffer buffer); + + 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); +#ifndef ESP32 + void textAll(const __FlashStringHelper* message); +#endif // ESP32 + void textAll(AsyncWebSocketMessageBuffer* buffer); + void textAll(AsyncWebSocketSharedBuffer buffer); + + void binary(uint32_t id, const uint8_t* message, size_t len); + 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); +#ifndef ESP32 + void binary(uint32_t id, const __FlashStringHelper* message, size_t len); +#endif // ESP32 + void binary(uint32_t id, AsyncWebSocketMessageBuffer* buffer); + void binary(uint32_t id, AsyncWebSocketSharedBuffer buffer); + + void binaryAll(const uint8_t* message, size_t len); + void binaryAll(const char* message, size_t len); + void binaryAll(const char* message); + void binaryAll(const String& message); +#ifndef ESP32 + void binaryAll(const __FlashStringHelper* message, size_t len); +#endif // ESP32 + void binaryAll(AsyncWebSocketMessageBuffer* buffer); + void binaryAll(AsyncWebSocketSharedBuffer buffer); + + size_t printf(uint32_t id, const char* format, ...) __attribute__((format(printf, 3, 4))); + size_t printfAll(const char* format, ...) __attribute__((format(printf, 2, 3))); + +#ifndef ESP32 + size_t printf_P(uint32_t id, PGM_P formatP, ...) __attribute__((format(printf, 3, 4))); + size_t printfAll_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); +#endif + + // event listener + void onEvent(AwsEventHandler handler) { + _eventHandler = handler; + } + + // Handshake Handler + void handleHandshake(AwsHandshakeHandler handler) { + _handshakeHandler = handler; + } + + // system callbacks (do not call) + uint32_t _getNextId() { return _cNextId++; } + AsyncWebSocketClient* _newClient(AsyncWebServerRequest* request); + void _handleEvent(AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len); + virtual bool canHandle(AsyncWebServerRequest* request) override final; + virtual void handleRequest(AsyncWebServerRequest* request) override final; + + // messagebuffer functions/objects. + AsyncWebSocketMessageBuffer* makeBuffer(size_t size = 0); + AsyncWebSocketMessageBuffer* makeBuffer(const uint8_t* data, size_t size); + + const std::list& getClients() const { return _clients; } +}; + +// WebServer response to authenticate the socket and detach the tcp client from the web server request +class AsyncWebSocketResponse : public AsyncWebServerResponse { + private: + String _content; + AsyncWebSocket* _server; + + public: + AsyncWebSocketResponse(const String& key, AsyncWebSocket* server); + void _respond(AsyncWebServerRequest* request); + size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time); + bool _sourceValid() const { return true; } +}; + +#endif /* ASYNCWEBSOCKET_H_ */ diff --git a/lib/ESP Async WebServer/src/ESPAsyncWebServer.h b/lib/ESP Async WebServer/src/ESPAsyncWebServer.h new file mode 100644 index 0000000..77c5de7 --- /dev/null +++ b/lib/ESP Async WebServer/src/ESPAsyncWebServer.h @@ -0,0 +1,652 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#ifndef _ESPAsyncWebServer_H_ +#define _ESPAsyncWebServer_H_ + +#include "Arduino.h" + +#include "FS.h" +#include +#include +#include + +#ifdef ESP32 + #include + #include +#elif defined(ESP8266) + #include + #include +#elif defined(TARGET_RP2040) + #include + #include + #include + #include +#else + #error Platform not supported +#endif + +#define ASYNCWEBSERVER_VERSION "3.0.6" +#define ASYNCWEBSERVER_VERSION_MAJOR 3 +#define ASYNCWEBSERVER_VERSION_MINOR 0 +#define ASYNCWEBSERVER_VERSION_REVISION 6 +#define ASYNCWEBSERVER_FORK_mathieucarbou + +#ifdef ASYNCWEBSERVER_REGEX + #define ASYNCWEBSERVER_REGEX_ATTRIBUTE +#else + #define ASYNCWEBSERVER_REGEX_ATTRIBUTE __attribute__((warning("ASYNCWEBSERVER_REGEX not defined"))) +#endif + +class AsyncWebServer; +class AsyncWebServerRequest; +class AsyncWebServerResponse; +class AsyncWebHeader; +class AsyncWebParameter; +class AsyncWebRewrite; +class AsyncWebHandler; +class AsyncStaticWebHandler; +class AsyncCallbackWebHandler; +class AsyncResponseStream; + +#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; + #endif +#endif + +#ifndef HAVE_FS_FILE_OPEN_MODE +namespace fs { + class FileOpenMode { + public: + static const char* read; + static const char* write; + static const char* append; + }; +}; +#else + #include "FileOpenMode.h" +#endif + +// if this value is returned when asked for data, packet will not be sent and you will be asked for data again +#define RESPONSE_TRY_AGAIN 0xFFFFFFFF + +typedef uint8_t WebRequestMethodComposite; +typedef std::function ArDisconnectHandler; + +/* + * PARAMETER :: Chainable object to hold GET/POST and FILE parameters + * */ + +class AsyncWebParameter { + private: + String _name; + String _value; + size_t _size; + bool _isForm; + bool _isFile; + + public: + AsyncWebParameter(const String& name, const String& value, bool form = false, bool file = false, size_t size = 0) : _name(name), _value(value), _size(size), _isForm(form), _isFile(file) {} + const String& name() const { return _name; } + const String& value() const { return _value; } + size_t size() const { return _size; } + bool isPost() const { return _isForm; } + bool isFile() const { return _isFile; } +}; + +/* + * HEADER :: Chainable object to hold the headers + * */ + +class AsyncWebHeader { + private: + String _name; + String _value; + + public: + AsyncWebHeader() = default; + AsyncWebHeader(const AsyncWebHeader&) = default; + + AsyncWebHeader(const String& name, const String& value) : _name(name), _value(value) {} + AsyncWebHeader(const String& data) { + if (!data) + return; + int index = data.indexOf(':'); + if (index < 0) + return; + _name = data.substring(0, index); + _value = data.substring(index + 2); + } + + AsyncWebHeader& operator=(const AsyncWebHeader&) = default; + + const String& name() const { return _name; } + const String& value() const { return _value; } + String toString() const { return _name + F(": ") + _value + F("\r\n"); } +}; + +/* + * REQUEST :: Each incoming Client is wrapped inside a Request and both live together until disconnect + * */ + +typedef enum { RCT_NOT_USED = -1, + RCT_DEFAULT = 0, + RCT_HTTP, + RCT_WS, + RCT_EVENT, + RCT_MAX } RequestedConnectionType; + +typedef std::function AwsResponseFiller; +typedef std::function AwsTemplateProcessor; + +class AsyncWebServerRequest { + using File = fs::File; + using FS = fs::FS; + friend class AsyncWebServer; + friend class AsyncCallbackWebHandler; + + private: + AsyncClient* _client; + AsyncWebServer* _server; + AsyncWebHandler* _handler; + AsyncWebServerResponse* _response; + std::vector _interestingHeaders; + ArDisconnectHandler _onDisconnectfn; + + String _temp; + uint8_t _parseState; + + uint8_t _version; + WebRequestMethodComposite _method; + String _url; + String _host; + String _contentType; + String _boundary; + String _authorization; + RequestedConnectionType _reqconntype; + void _removeNotInterestingHeaders(); + bool _isDigest; + bool _isMultipart; + bool _isPlainPost; + bool _expectingContinue; + size_t _contentLength; + size_t _parsedLength; + + std::list _headers; + std::list _params; + std::vector _pathParams; + + uint8_t _multiParseState; + uint8_t _boundaryPosition; + size_t _itemStartIndex; + size_t _itemSize; + String _itemName; + String _itemFilename; + String _itemType; + String _itemValue; + uint8_t* _itemBuffer; + size_t _itemBufferIndex; + bool _itemIsFile; + + void _onPoll(); + void _onAck(size_t len, uint32_t time); + void _onError(int8_t error); + void _onTimeout(uint32_t time); + void _onDisconnect(); + void _onData(void* buf, size_t len); + + void _addPathParam(const char* param); + + bool _parseReqHead(); + bool _parseReqHeader(); + void _parseLine(); + void _parsePlainPostChar(uint8_t data); + void _parseMultipartPostByte(uint8_t data, bool last); + void _addGetParams(const String& params); + + void _handleUploadStart(); + void _handleUploadByte(uint8_t data, bool last); + void _handleUploadEnd(); + + public: + File _tempFile; + void* _tempObject; + + AsyncWebServerRequest(AsyncWebServer*, AsyncClient*); + ~AsyncWebServerRequest(); + + AsyncClient* client() { return _client; } + uint8_t version() const { return _version; } + WebRequestMethodComposite method() const { return _method; } + const String& url() const { return _url; } + const String& host() const { return _host; } + const String& contentType() const { return _contentType; } + size_t contentLength() const { return _contentLength; } + bool multipart() const { return _isMultipart; } + +#ifndef ESP8266 + const char* methodToString() const; + const char* requestedConnTypeToString() const; +#else + const __FlashStringHelper* methodToString() const; + const __FlashStringHelper* requestedConnTypeToString() const; +#endif + + RequestedConnectionType requestedConnType() const { return _reqconntype; } + bool isExpectedRequestedConnType(RequestedConnectionType erct1, RequestedConnectionType erct2 = RCT_NOT_USED, RequestedConnectionType erct3 = RCT_NOT_USED); + void onDisconnect(ArDisconnectHandler fn); + + // hash is the string representation of: + // base64(user:pass) for basic or + // user:realm:md5(user:realm:pass) for digest + bool authenticate(const char* hash); + bool authenticate(const char* username, const char* password, const char* realm = NULL, bool passwordIsHash = false); + void requestAuthentication(const char* realm = NULL, bool isDigest = true); + + void setHandler(AsyncWebHandler* handler) { _handler = handler; } + + /** + * @brief add header to collect from a response + * + * @param name + */ + void addInterestingHeader(const char* name); + void addInterestingHeader(const String& name) { return addInterestingHeader(name.c_str()); }; + + /** + * @brief issue 302 redirect response + * + * @param url + */ + void redirect(const char* url); + 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); + + [[deprecated("Replaced by send(...)")]] + void send_P(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { + send(code, contentType, content, len, callback); + } + [[deprecated("Replaced by send(...)")]] + void send_P(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) { + 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); + + + [[deprecated("Replaced by beginResponse(...)")]] + AsyncWebServerResponse* beginResponse_P(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { + return beginResponse(code, contentType, content, len, callback); + } + [[deprecated("Replaced by beginResponse(...)")]] + AsyncWebServerResponse* beginResponse_P(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) { + return beginResponse(code, contentType, content, callback); + } + + size_t headers() const; // get header count + + // check if header exists + bool hasHeader(const char* name) const; + bool hasHeader(const String& name) const { return hasHeader(name.c_str()); }; +#ifdef ESP8266 + bool hasHeader(const __FlashStringHelper* data) const; // check if header exists +#endif + + const AsyncWebHeader* getHeader(const char* name) const; + const AsyncWebHeader* getHeader(const String& name) const { return getHeader(name.c_str()); }; +#ifdef ESP8266 + const AsyncWebHeader* getHeader(const __FlashStringHelper* data) const; +#endif + 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 __FlashStringHelper* data, bool post = false, bool file = false) const; + + /** + * @brief Get the Request parameter by name + * + * @param name + * @param post + * @param file + * @return const AsyncWebParameter* + */ + const AsyncWebParameter* getParam(const char* name, bool post = false, bool file = false) const; + + const AsyncWebParameter* getParam(const String& name, bool post = false, bool file = false) const { return getParam(name.c_str(), post, file); }; +#ifdef ESP8266 + const AsyncWebParameter* getParam(const __FlashStringHelper* data, bool post, bool file) const; +#endif + + /** + * @brief Get request parameter by number + * i.e., n-th parameter + * @param num + * @return const AsyncWebParameter* + */ + const AsyncWebParameter* getParam(size_t num) const; + + size_t args() const { return params(); } // get arguments count + + // get request argument value by name + const String& arg(const char* name) const; + // get request argument value by name + const String& arg(const String& name) const { return arg(name.c_str()); }; +#ifdef ESP8266 + const String& arg(const __FlashStringHelper* data) const; // get request argument value by F(name) +#endif + const String& arg(size_t i) const; // get request argument value by number + const String& argName(size_t i) const; // get request argument name by number + bool hasArg(const char* name) const; // check if argument exists + bool hasArg(const String& name) const { return hasArg(name.c_str()); }; +#ifdef ESP8266 + bool hasArg(const __FlashStringHelper* data) const; // check if F(argument) exists +#endif + + const String& ASYNCWEBSERVER_REGEX_ATTRIBUTE pathArg(size_t i) const; + + // get request header value by name + const String& header(const char* name) const; + const String& header(const String& name) const { return header(name.c_str()); }; + +#ifdef ESP8266 + const String& header(const __FlashStringHelper* data) const; // get request header value by F(name) +#endif + + const String& header(size_t i) const; // get request header value by number + const String& headerName(size_t i) const; // get request header name by number + + String urlDecode(const String& text) const; +}; + +/* + * FILTER :: Callback to filter AsyncWebRewrite and AsyncWebHandler (done by the Server) + * */ + +using ArRequestFilterFunction = std::function; + +bool ON_STA_FILTER(AsyncWebServerRequest* request); + +bool ON_AP_FILTER(AsyncWebServerRequest* request); + +/* + * REWRITE :: One instance can be handle any Request (done by the Server) + * */ + +class AsyncWebRewrite { + protected: + String _from; + String _toUrl; + String _params; + ArRequestFilterFunction _filter{nullptr}; + + public: + AsyncWebRewrite(const char* from, const char* to) : _from(from), _toUrl(to) { + int index = _toUrl.indexOf('?'); + if (index > 0) { + _params = _toUrl.substring(index + 1); + _toUrl = _toUrl.substring(0, index); + } + } + virtual ~AsyncWebRewrite() {} + AsyncWebRewrite& setFilter(ArRequestFilterFunction fn) { + _filter = fn; + return *this; + } + bool filter(AsyncWebServerRequest* request) const { return _filter == NULL || _filter(request); } + const String& from(void) const { return _from; } + const String& toUrl(void) const { return _toUrl; } + const String& params(void) const { return _params; } + virtual bool match(AsyncWebServerRequest* request) { return from() == request->url() && filter(request); } +}; + +/* + * HANDLER :: One instance can be attached to any Request (done by the Server) + * */ + +class AsyncWebHandler { + protected: + ArRequestFilterFunction _filter{nullptr}; + String _username; + String _password; + + public: + AsyncWebHandler() {} + AsyncWebHandler& setFilter(ArRequestFilterFunction fn) { + _filter = fn; + return *this; + } + AsyncWebHandler& setAuthentication(const char* username, const char* password) { + _username = username; + _password = password; + return *this; + }; + AsyncWebHandler& setAuthentication(const String& username, const String& password) { + _username = username; + _password = password; + return *this; + }; + bool filter(AsyncWebServerRequest* request) { return _filter == NULL || _filter(request); } + virtual ~AsyncWebHandler() {} + virtual bool canHandle(AsyncWebServerRequest* request __attribute__((unused))) { + return false; + } + virtual void handleRequest(AsyncWebServerRequest* request __attribute__((unused))) {} + virtual void handleUpload(AsyncWebServerRequest* request __attribute__((unused)), const String& filename __attribute__((unused)), size_t index __attribute__((unused)), uint8_t* data __attribute__((unused)), size_t len __attribute__((unused)), bool final __attribute__((unused))) {} + virtual void handleBody(AsyncWebServerRequest* request __attribute__((unused)), uint8_t* data __attribute__((unused)), size_t len __attribute__((unused)), size_t index __attribute__((unused)), size_t total __attribute__((unused))) {} + virtual bool isRequestHandlerTrivial() { return true; } +}; + +/* + * RESPONSE :: One instance is created for each Request (attached by the Handler) + * */ + +typedef enum { + RESPONSE_SETUP, + RESPONSE_HEADERS, + RESPONSE_CONTENT, + RESPONSE_WAIT_ACK, + RESPONSE_END, + RESPONSE_FAILED +} WebResponseState; + +class AsyncWebServerResponse { + protected: + int _code; + std::list _headers; + String _contentType; + size_t _contentLength; + bool _sendContentLength; + bool _chunked; + size_t _headLength; + size_t _sentLength; + size_t _ackedLength; + size_t _writtenLength; + WebResponseState _state; + const char* _responseCodeToString(int code); + + public: + static const __FlashStringHelper* responseCodeToString(int code); + + public: + 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); + virtual String _assembleHead(uint8_t version); + virtual bool _started() const; + virtual bool _finished() const; + virtual bool _failed() const; + virtual bool _sourceValid() const; + virtual void _respond(AsyncWebServerRequest* request); + virtual size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time); +}; + +/* + * SERVER :: One instance + * */ + +typedef std::function ArRequestHandlerFunction; +typedef std::function ArUploadHandlerFunction; +typedef std::function ArBodyHandlerFunction; + +class AsyncWebServer { + protected: + AsyncServer _server; + std::list> _rewrites; + std::list> _handlers; + AsyncCallbackWebHandler* _catchAllHandler; + + public: + AsyncWebServer(uint16_t port); + ~AsyncWebServer(); + + void begin(); + void end(); + +#if ASYNC_TCP_SSL_ENABLED + void onSslFileRequest(AcSSlFileHandler cb, void* arg); + void beginSecure(const char* cert, const char* private_key_file, const char* password); +#endif + + AsyncWebRewrite& addRewrite(AsyncWebRewrite* rewrite); + + /** + * @brief (compat) Add url rewrite rule by pointer + * a deep copy of the pounter object will be created, + * it is up to user to manage further lifetime of the object in argument + * + * @param rewrite pointer to rewrite object to copy setting from + * @return AsyncWebRewrite& reference to a newly created rewrite rule + */ + AsyncWebRewrite& addRewrite(std::shared_ptr rewrite); + + /** + * @brief add url rewrite rule + * + * @param from + * @param to + * @return AsyncWebRewrite& + */ + AsyncWebRewrite& rewrite(const char* from, const char* to); + + /** + * @brief (compat) remove rewrite rule via referenced object + * this will NOT deallocate pointed object itself, internal rule with same from/to urls will be removed if any + * it's a compat method, better use `removeRewrite(const char* from, const char* to)` + * @param rewrite + * @return true + * @return false + */ + bool removeRewrite(AsyncWebRewrite* rewrite); + + /** + * @brief remove rewrite rule + * + * @param from + * @param to + * @return true + * @return false + */ + bool removeRewrite(const char* from, const char* to); + + AsyncWebHandler& addHandler(AsyncWebHandler* handler); + bool removeHandler(AsyncWebHandler* handler); + + AsyncCallbackWebHandler& on(const char* uri, ArRequestHandlerFunction onRequest); + AsyncCallbackWebHandler& on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest); + AsyncCallbackWebHandler& on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload); + AsyncCallbackWebHandler& on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody); + + AsyncStaticWebHandler& serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control = NULL); + + void onNotFound(ArRequestHandlerFunction fn); // called when handler is not assigned + void onFileUpload(ArUploadHandlerFunction fn); // handle file uploads + void onRequestBody(ArBodyHandlerFunction fn); // handle posts with plain body content (JSON often transmitted this way as a request) + + void reset(); // remove all writers and handlers, with onNotFound/onFileUpload/onRequestBody + + void _handleDisconnect(AsyncWebServerRequest* request); + void _attachHandler(AsyncWebServerRequest* request); + void _rewriteRequest(AsyncWebServerRequest* request); +}; + +class DefaultHeaders { + using headers_t = std::list; + headers_t _headers; + + public: + DefaultHeaders() = default; + + using ConstIterator = headers_t::const_iterator; + + void addHeader(const String& name, const String& value) { + _headers.emplace_back(name, value); + } + + ConstIterator begin() const { return _headers.begin(); } + ConstIterator end() const { return _headers.end(); } + + DefaultHeaders(DefaultHeaders const&) = delete; + DefaultHeaders& operator=(DefaultHeaders const&) = delete; + + static DefaultHeaders& Instance() { + static DefaultHeaders instance; + return instance; + } +}; + +#include "AsyncEventSource.h" +#include "AsyncWebSocket.h" +#include "WebHandlerImpl.h" +#include "WebResponseImpl.h" + +#endif /* _AsyncWebServer_H_ */ diff --git a/lib/ESP Async WebServer/src/ESP_Async_WebServer.h b/lib/ESP Async WebServer/src/ESP_Async_WebServer.h new file mode 100644 index 0000000..ca6a112 --- /dev/null +++ b/lib/ESP Async WebServer/src/ESP_Async_WebServer.h @@ -0,0 +1,2 @@ +// to please Arduino Lint +#include "ESPAsyncWebServer.h" diff --git a/lib/ESP Async WebServer/src/WebAuthentication.cpp b/lib/ESP Async WebServer/src/WebAuthentication.cpp new file mode 100644 index 0000000..abd74b8 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebAuthentication.cpp @@ -0,0 +1,245 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "WebAuthentication.h" +#include +#if defined(ESP32) || defined(TARGET_RP2040) + #include +#else + #include "md5.h" +#endif + +// Basic Auth hash = base64("username:password") + +bool checkBasicAuthentication(const char* hash, const char* username, const char* password) { + if (username == NULL || password == NULL || hash == NULL) + return false; + + size_t toencodeLen = strlen(username) + strlen(password) + 1; + size_t encodedLen = base64_encode_expected_len(toencodeLen); + if (strlen(hash) != encodedLen) +// Fix from https://github.com/me-no-dev/ESPAsyncWebServer/issues/667 +#ifdef ARDUINO_ARCH_ESP32 + if (strlen(hash) != encodedLen) +#else + if (strlen(hash) != encodedLen - 1) +#endif + return false; + + char* toencode = new char[toencodeLen + 1]; + if (toencode == NULL) { + return false; + } + char* encoded = new char[base64_encode_expected_len(toencodeLen) + 1]; + if (encoded == NULL) { + delete[] toencode; + return false; + } + sprintf_P(toencode, PSTR("%s:%s"), username, password); + if (base64_encode_chars(toencode, toencodeLen, encoded) > 0 && memcmp(hash, encoded, encodedLen) == 0) { + delete[] toencode; + delete[] encoded; + return true; + } + delete[] toencode; + delete[] encoded; + return false; +} + +static bool getMD5(uint8_t* data, uint16_t len, char* output) { // 33 bytes or more +#if defined(ESP32) || defined(TARGET_RP2040) + MD5Builder md5; + md5.begin(); + md5.add(data, len); + md5.calculate(); + md5.getChars(output); +#else + md5_context_t _ctx; + + uint8_t* _buf = (uint8_t*)malloc(16); + if (_buf == NULL) + return false; + memset(_buf, 0x00, 16); + + MD5Init(&_ctx); + MD5Update(&_ctx, data, len); + MD5Final(_buf, &_ctx); + + for (uint8_t i = 0; i < 16; i++) { + sprintf_P(output + (i * 2), PSTR("%02x"), _buf[i]); + } + + free(_buf); +#endif + return true; +} + +static String genRandomMD5() { +#ifdef ESP8266 + uint32_t r = RANDOM_REG32; +#else + uint32_t r = rand(); +#endif + char* out = (char*)malloc(33); + if (out == NULL || !getMD5((uint8_t*)(&r), 4, out)) + return emptyString; + String res = String(out); + free(out); + return res; +} + +static String stringMD5(const String& in) { + char* out = (char*)malloc(33); + if (out == NULL || !getMD5((uint8_t*)(in.c_str()), in.length(), out)) + return emptyString; + String res = String(out); + free(out); + return res; +} + +String generateDigestHash(const char* username, const char* password, const char* realm) { + if (username == NULL || password == NULL || realm == NULL) { + return emptyString; + } + char* out = (char*)malloc(33); + String res = String(username); + res += ':'; + res.concat(realm); + res += ':'; + String in = res; + in.concat(password); + if (out == NULL || !getMD5((uint8_t*)(in.c_str()), in.length(), out)) + return emptyString; + res.concat(out); + free(out); + return res; +} + +String requestDigestAuthentication(const char* realm) { + String header = F("realm=\""); + if (realm == NULL) + header.concat(F("asyncesp")); + else + header.concat(realm); + header.concat(F("\", qop=\"auth\", nonce=\"")); + header.concat(genRandomMD5()); + header.concat(F("\", opaque=\"")); + header.concat(genRandomMD5()); + header += '"'; + return header; +} + +#ifndef ESP8266 +bool checkDigestAuthentication(const char* header, const char* method, const char* username, const char* password, const char* realm, bool passwordIsHash, const char* nonce, const char* opaque, const char* uri) +#else +bool checkDigestAuthentication(const char* header, const __FlashStringHelper* method, const char* username, const char* password, const char* realm, bool passwordIsHash, const char* nonce, const char* opaque, const char* uri) +#endif +{ + if (username == NULL || password == NULL || header == NULL || method == NULL) { + // os_printf("AUTH FAIL: missing requred fields\n"); + return false; + } + + String myHeader(header); + int nextBreak = myHeader.indexOf(','); + if (nextBreak < 0) { + // os_printf("AUTH FAIL: no variables\n"); + return false; + } + + String myUsername; + String myRealm; + String myNonce; + String myUri; + String myResponse; + String myQop; + String myNc; + String myCnonce; + + myHeader += F(", "); + do { + String avLine(myHeader.substring(0, nextBreak)); + avLine.trim(); + myHeader = myHeader.substring(nextBreak + 1); + nextBreak = myHeader.indexOf(','); + + int eqSign = avLine.indexOf('='); + if (eqSign < 0) { + // os_printf("AUTH FAIL: no = sign\n"); + return false; + } + String varName(avLine.substring(0, eqSign)); + avLine = avLine.substring(eqSign + 1); + if (avLine.startsWith(String('"'))) { + avLine = avLine.substring(1, avLine.length() - 1); + } + + if (varName.equals(F("username"))) { + if (!avLine.equals(username)) { + // os_printf("AUTH FAIL: username\n"); + return false; + } + myUsername = avLine; + } else if (varName.equals(F("realm"))) { + if (realm != NULL && !avLine.equals(realm)) { + // os_printf("AUTH FAIL: realm\n"); + return false; + } + myRealm = avLine; + } else if (varName.equals(F("nonce"))) { + if (nonce != NULL && !avLine.equals(nonce)) { + // os_printf("AUTH FAIL: nonce\n"); + return false; + } + myNonce = avLine; + } else if (varName.equals(F("opaque"))) { + if (opaque != NULL && !avLine.equals(opaque)) { + // os_printf("AUTH FAIL: opaque\n"); + return false; + } + } else if (varName.equals(F("uri"))) { + if (uri != NULL && !avLine.equals(uri)) { + // os_printf("AUTH FAIL: uri\n"); + return false; + } + myUri = avLine; + } else if (varName.equals(F("response"))) { + myResponse = avLine; + } else if (varName.equals(F("qop"))) { + myQop = avLine; + } else if (varName.equals(F("nc"))) { + myNc = avLine; + } else if (varName.equals(F("cnonce"))) { + myCnonce = avLine; + } + } while (nextBreak > 0); + + String ha1 = (passwordIsHash) ? String(password) : stringMD5(myUsername + ':' + myRealm + ':' + password); + String ha2 = String(method) + ':' + myUri; + String response = ha1 + ':' + myNonce + ':' + myNc + ':' + myCnonce + ':' + myQop + ':' + stringMD5(ha2); + + if (myResponse.equals(stringMD5(response))) { + // os_printf("AUTH SUCCESS\n"); + return true; + } + + // os_printf("AUTH FAIL: password\n"); + return false; +} diff --git a/lib/ESP Async WebServer/src/WebAuthentication.h b/lib/ESP Async WebServer/src/WebAuthentication.h new file mode 100644 index 0000000..d519777 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebAuthentication.h @@ -0,0 +1,39 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WEB_AUTHENTICATION_H_ +#define WEB_AUTHENTICATION_H_ + +#include "Arduino.h" + +bool checkBasicAuthentication(const char* header, const char* username, const char* password); +String requestDigestAuthentication(const char* realm); + +bool checkDigestAuthentication(const char* header, const char* method, const char* username, const char* password, const char* realm, bool passwordIsHash, const char* nonce, const char* opaque, const char* uri); + +#ifdef ESP8266 +bool checkDigestAuthentication(const char* header, const __FlashStringHelper* method, const char* username, const char* password, const char* realm, bool passwordIsHash, const char* nonce, const char* opaque, const char* uri); +#endif + +// for storing hashed versions on the device that can be authenticated against +String generateDigestHash(const char* username, const char* password, const char* realm); + +#endif diff --git a/lib/ESP Async WebServer/src/WebHandlerImpl.h b/lib/ESP Async WebServer/src/WebHandlerImpl.h new file mode 100644 index 0000000..22757d7 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebHandlerImpl.h @@ -0,0 +1,155 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#ifndef ASYNCWEBSERVERHANDLERIMPL_H_ +#define ASYNCWEBSERVERHANDLERIMPL_H_ + +#include +#ifdef ASYNCWEBSERVER_REGEX + #include +#endif + +#include "stddef.h" +#include + +class AsyncStaticWebHandler : public AsyncWebHandler { + using File = fs::File; + using FS = fs::FS; + + private: + bool _getFile(AsyncWebServerRequest* request); + bool _fileExists(AsyncWebServerRequest* request, const String& path); + uint8_t _countBits(const uint8_t value) const; + + protected: + FS _fs; + String _uri; + String _path; + String _default_file; + String _cache_control; + String _last_modified; + AwsTemplateProcessor _callback; + bool _isDir; + bool _gzipFirst; + uint8_t _gzipStats; + + public: + AsyncStaticWebHandler(const char* uri, FS& fs, const char* path, const char* cache_control); + virtual bool canHandle(AsyncWebServerRequest* request) override final; + virtual void handleRequest(AsyncWebServerRequest* request) override final; + AsyncStaticWebHandler& setIsDir(bool isDir); + AsyncStaticWebHandler& setDefaultFile(const char* filename); + AsyncStaticWebHandler& setCacheControl(const char* cache_control); + AsyncStaticWebHandler& setLastModified(const char* last_modified); + AsyncStaticWebHandler& setLastModified(struct tm* last_modified); +#ifdef ESP8266 + AsyncStaticWebHandler& setLastModified(time_t last_modified); + AsyncStaticWebHandler& setLastModified(); // sets to current time. Make sure sntp is runing and time is updated +#endif + AsyncStaticWebHandler& setTemplateProcessor(AwsTemplateProcessor newCallback) { + _callback = newCallback; + return *this; + } +}; + +class AsyncCallbackWebHandler : public AsyncWebHandler { + private: + protected: + String _uri; + WebRequestMethodComposite _method; + ArRequestHandlerFunction _onRequest; + ArUploadHandlerFunction _onUpload; + ArBodyHandlerFunction _onBody; + bool _isRegex; + + public: + AsyncCallbackWebHandler() : _uri(), _method(HTTP_ANY), _onRequest(NULL), _onUpload(NULL), _onBody(NULL), _isRegex(false) {} + void setUri(const String& uri) { + _uri = uri; + _isRegex = uri.startsWith("^") && uri.endsWith("$"); + } + void setMethod(WebRequestMethodComposite method) { _method = method; } + void onRequest(ArRequestHandlerFunction fn) { _onRequest = fn; } + void onUpload(ArUploadHandlerFunction fn) { _onUpload = fn; } + void onBody(ArBodyHandlerFunction fn) { _onBody = fn; } + + virtual bool canHandle(AsyncWebServerRequest* request) override final { + + if (!_onRequest) + return false; + + if (!(_method & request->method())) + return false; + +#ifdef ASYNCWEBSERVER_REGEX + if (_isRegex) { + std::regex pattern(_uri.c_str()); + std::smatch matches; + std::string s(request->url().c_str()); + if (std::regex_search(s, matches, pattern)) { + for (size_t i = 1; i < matches.size(); ++i) { // start from 1 + request->_addPathParam(matches[i].str().c_str()); + } + } else { + return false; + } + } else +#endif + if (_uri.length() && _uri.startsWith("/*.")) { + String uriTemplate = String(_uri); + uriTemplate = uriTemplate.substring(uriTemplate.lastIndexOf(".")); + if (!request->url().endsWith(uriTemplate)) + return false; + } else if (_uri.length() && _uri.endsWith("*")) { + String uriTemplate = String(_uri); + uriTemplate = uriTemplate.substring(0, uriTemplate.length() - 1); + if (!request->url().startsWith(uriTemplate)) + return false; + } else if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/"))) + return false; + + request->addInterestingHeader("ANY"); + return true; + } + + virtual void handleRequest(AsyncWebServerRequest* request) override final { + if ((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str())) + return request->requestAuthentication(); + if (_onRequest) + _onRequest(request); + else + request->send(500); + } + virtual void handleUpload(AsyncWebServerRequest* request, const String& filename, size_t index, uint8_t* data, size_t len, bool final) override final { + if ((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str())) + return request->requestAuthentication(); + if (_onUpload) + _onUpload(request, filename, index, data, len, final); + } + virtual void handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) override final { + if ((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str())) + return request->requestAuthentication(); + if (_onBody) + _onBody(request, data, len, index, total); + } + virtual bool isRequestHandlerTrivial() override final { return _onRequest ? false : true; } +}; + +#endif /* ASYNCWEBSERVERHANDLERIMPL_H_ */ diff --git a/lib/ESP Async WebServer/src/WebHandlers.cpp b/lib/ESP Async WebServer/src/WebHandlers.cpp new file mode 100644 index 0000000..d740d86 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebHandlers.cpp @@ -0,0 +1,247 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "ESPAsyncWebServer.h" +#include "WebHandlerImpl.h" + +AsyncStaticWebHandler::AsyncStaticWebHandler(const char* uri, FS& fs, const char* path, const char* cache_control) + : _fs(fs), _uri(uri), _path(path), _default_file(F("index.htm")), _cache_control(cache_control), _last_modified(), _callback(nullptr) { + // Ensure leading '/' + if (_uri.length() == 0 || _uri[0] != '/') + _uri = String('/') + _uri; + if (_path.length() == 0 || _path[0] != '/') + _path = String('/') + _path; + + // If path ends with '/' we assume a hint that this is a directory to improve performance. + // However - if it does not end with '/' we, can't assume a file, path can still be a directory. + _isDir = _path[_path.length() - 1] == '/'; + + // Remove the trailing '/' so we can handle default file + // Notice that root will be "" not "/" + if (_uri[_uri.length() - 1] == '/') + _uri = _uri.substring(0, _uri.length() - 1); + if (_path[_path.length() - 1] == '/') + _path = _path.substring(0, _path.length() - 1); + + // Reset stats + _gzipFirst = false; + _gzipStats = 0xF8; +} + +AsyncStaticWebHandler& AsyncStaticWebHandler::setIsDir(bool isDir) { + _isDir = isDir; + return *this; +} + +AsyncStaticWebHandler& AsyncStaticWebHandler::setDefaultFile(const char* filename) { + _default_file = String(filename); + return *this; +} + +AsyncStaticWebHandler& AsyncStaticWebHandler::setCacheControl(const char* cache_control) { + _cache_control = String(cache_control); + return *this; +} + +AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(const char* last_modified) { + _last_modified = last_modified; + return *this; +} + +AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(struct tm* last_modified) { + auto formatP = PSTR("%a, %d %b %Y %H:%M:%S %Z"); + char format[strlen_P(formatP) + 1]; + strcpy_P(format, formatP); + + char result[30]; + strftime(result, sizeof(result), format, last_modified); + return setLastModified((const char*)result); +} + +#ifdef ESP8266 +AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(time_t last_modified) { + return setLastModified((struct tm*)gmtime(&last_modified)); +} + +AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified() { + time_t last_modified; + if (time(&last_modified) == 0) // time is not yet set + return *this; + return setLastModified(last_modified); +} +#endif +bool AsyncStaticWebHandler::canHandle(AsyncWebServerRequest* request) { + if (request->method() != HTTP_GET || !request->url().startsWith(_uri) || !request->isExpectedRequestedConnType(RCT_DEFAULT, RCT_HTTP)) { + return false; + } + if (_getFile(request)) { + // We interested in "If-Modified-Since" header to check if file was modified + if (_last_modified.length()) + request->addInterestingHeader(F("If-Modified-Since")); + + if (_cache_control.length()) + request->addInterestingHeader(F("If-None-Match")); + + return true; + } + + return false; +} + +bool AsyncStaticWebHandler::_getFile(AsyncWebServerRequest* request) { + // Remove the found uri + String path = request->url().substring(_uri.length()); + + // We can skip the file check and look for default if request is to the root of a directory or that request path ends with '/' + bool canSkipFileCheck = (_isDir && path.length() == 0) || (path.length() && path[path.length() - 1] == '/'); + + path = _path + path; + + // Do we have a file or .gz file + if (!canSkipFileCheck && _fileExists(request, path)) + return true; + + // Can't handle if not default file + if (_default_file.length() == 0) + return false; + + // Try to add default file, ensure there is a trailing '/' ot the path. + if (path.length() == 0 || path[path.length() - 1] != '/') + path += String('/'); + path += _default_file; + + return _fileExists(request, path); +} + +#ifdef ESP32 + #define FILE_IS_REAL(f) (f == true && !f.isDirectory()) +#else + #define FILE_IS_REAL(f) (f == true) +#endif + +bool AsyncStaticWebHandler::_fileExists(AsyncWebServerRequest* request, const String& path) { + bool fileFound = false; + bool gzipFound = false; + + String gzip = path + F(".gz"); + + if (_gzipFirst) { + if (_fs.exists(gzip)) { + request->_tempFile = _fs.open(gzip, fs::FileOpenMode::read); + gzipFound = FILE_IS_REAL(request->_tempFile); + } + if (!gzipFound) { + if (_fs.exists(path)) { + request->_tempFile = _fs.open(path, fs::FileOpenMode::read); + fileFound = FILE_IS_REAL(request->_tempFile); + } + } + } else { + if (_fs.exists(path)) { + request->_tempFile = _fs.open(path, fs::FileOpenMode::read); + fileFound = FILE_IS_REAL(request->_tempFile); + } + if (!fileFound) { + if (_fs.exists(gzip)) { + request->_tempFile = _fs.open(gzip, fs::FileOpenMode::read); + gzipFound = FILE_IS_REAL(request->_tempFile); + } + } + } + + bool found = fileFound || gzipFound; + + if (found) { + // Extract the file name from the path and keep it in _tempObject + size_t pathLen = path.length(); + char* _tempPath = (char*)malloc(pathLen + 1); + snprintf_P(_tempPath, pathLen + 1, PSTR("%s"), path.c_str()); + request->_tempObject = (void*)_tempPath; + + // Calculate gzip statistic + _gzipStats = (_gzipStats << 1) + (gzipFound ? 1 : 0); + if (_gzipStats == 0x00) + _gzipFirst = false; // All files are not gzip + else if (_gzipStats == 0xFF) + _gzipFirst = true; // All files are gzip + else + _gzipFirst = _countBits(_gzipStats) > 4; // IF we have more gzip files - try gzip first + } + + return found; +} + +uint8_t AsyncStaticWebHandler::_countBits(const uint8_t value) const { + uint8_t w = value; + uint8_t n; + for (n = 0; w != 0; n++) + w &= w - 1; + return n; +} + +void AsyncStaticWebHandler::handleRequest(AsyncWebServerRequest* request) { + // Get the filename from request->_tempObject and free it + String filename = String((char*)request->_tempObject); + free(request->_tempObject); + request->_tempObject = NULL; + if ((_username.length() && _password.length()) && !request->authenticate(_username.c_str(), _password.c_str())) + return request->requestAuthentication(); + + if (request->_tempFile == true) { + time_t lw = request->_tempFile.getLastWrite(); // get last file mod time (if supported by FS) + // set etag to lastmod timestamp if available, otherwise to size + String etag; + if (lw) { + setLastModified(gmtime(&lw)); +#if defined(TARGET_RP2040) + // time_t == long long int + const size_t len = 1 + 8 * sizeof(time_t); + char buf[len]; + char* ret = lltoa(lw, buf, len, 10); + etag = ret ? String(ret) : String(request->_tempFile.size()); +#else + etag = String(lw); +#endif + } else { + etag = String(request->_tempFile.size()); + } + if (_last_modified.length() && _last_modified == request->header(F("If-Modified-Since"))) { + request->_tempFile.close(); + request->send(304); // Not modified + } else if (_cache_control.length() && request->hasHeader(F("If-None-Match")) && request->header(F("If-None-Match")).equals(etag)) { + request->_tempFile.close(); + AsyncWebServerResponse* response = new AsyncBasicResponse(304); // Not modified + response->addHeader(F("Cache-Control"), _cache_control); + response->addHeader(F("ETag"), etag); + request->send(response); + } else { + AsyncWebServerResponse* response = new AsyncFileResponse(request->_tempFile, filename, String(), false, _callback); + if (_last_modified.length()) + response->addHeader(F("Last-Modified"), _last_modified); + if (_cache_control.length()) { + response->addHeader(F("Cache-Control"), _cache_control); + response->addHeader(F("ETag"), etag); + } + request->send(response); + } + } else { + request->send(404); + } +} diff --git a/lib/ESP Async WebServer/src/WebRequest.cpp b/lib/ESP Async WebServer/src/WebRequest.cpp new file mode 100644 index 0000000..2331b13 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebRequest.cpp @@ -0,0 +1,1028 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "ESPAsyncWebServer.h" +#include "WebAuthentication.h" +#include "WebResponseImpl.h" + +#ifndef ESP8266 + #define os_strlen strlen +#endif + +#define __is_param_char(c) ((c) && ((c) != '{') && ((c) != '[') && ((c) != '&') && ((c) != '=')) + +enum { PARSE_REQ_START, + PARSE_REQ_HEADERS, + PARSE_REQ_BODY, + PARSE_REQ_END, + PARSE_REQ_FAIL }; + +AsyncWebServerRequest::AsyncWebServerRequest(AsyncWebServer* s, AsyncClient* c) + : _client(c), _server(s), _handler(NULL), _response(NULL), _temp(), _parseState(0), _version(0), _method(HTTP_ANY), _url(), _host(), _contentType(), _boundary(), _authorization(), _reqconntype(RCT_HTTP), _isDigest(false), _isMultipart(false), _isPlainPost(false), _expectingContinue(false), _contentLength(0), _parsedLength(0), _multiParseState(0), _boundaryPosition(0), _itemStartIndex(0), _itemSize(0), _itemName(), _itemFilename(), _itemType(), _itemValue(), _itemBuffer(0), _itemBufferIndex(0), _itemIsFile(false), _tempObject(NULL) { + c->onError([](void* r, AsyncClient* c, int8_t error) { (void)c; AsyncWebServerRequest *req = (AsyncWebServerRequest*)r; req->_onError(error); }, this); + c->onAck([](void* r, AsyncClient* c, size_t len, uint32_t time) { (void)c; AsyncWebServerRequest *req = (AsyncWebServerRequest*)r; req->_onAck(len, time); }, this); + c->onDisconnect([](void* r, AsyncClient* c) { AsyncWebServerRequest *req = (AsyncWebServerRequest*)r; req->_onDisconnect(); delete c; }, this); + c->onTimeout([](void* r, AsyncClient* c, uint32_t time) { (void)c; AsyncWebServerRequest *req = (AsyncWebServerRequest*)r; req->_onTimeout(time); }, this); + c->onData([](void* r, AsyncClient* c, void* buf, size_t len) { (void)c; AsyncWebServerRequest *req = (AsyncWebServerRequest*)r; req->_onData(buf, len); }, this); + c->onPoll([](void* r, AsyncClient* c) { (void)c; AsyncWebServerRequest *req = ( AsyncWebServerRequest*)r; req->_onPoll(); }, this); +} + +AsyncWebServerRequest::~AsyncWebServerRequest() { + _headers.clear(); + + _pathParams.clear(); + + _interestingHeaders.clear(); + + if (_response != NULL) { + delete _response; + } + + if (_tempObject != NULL) { + free(_tempObject); + } + + if (_tempFile) { + _tempFile.close(); + } + + if (_itemBuffer) { + free(_itemBuffer); + } +} + +void AsyncWebServerRequest::_onData(void* buf, size_t len) { + size_t i = 0; + while (true) { + + if (_parseState < PARSE_REQ_BODY) { + // Find new line in buf + char* str = (char*)buf; + for (i = 0; i < len; i++) { + if (str[i] == '\n') { + break; + } + } + if (i == len) { // No new line, just add the buffer in _temp + char ch = str[len - 1]; + str[len - 1] = 0; + _temp.reserve(_temp.length() + len); + _temp.concat(str); + _temp.concat(ch); + } else { // Found new line - extract it and parse + str[i] = 0; // Terminate the string at the end of the line. + _temp.concat(str); + _temp.trim(); + _parseLine(); + if (++i < len) { + // Still have more buffer to process + buf = str + i; + len -= i; + continue; + } + } + } else if (_parseState == PARSE_REQ_BODY) { + // A handler should be already attached at this point in _parseLine function. + // If handler does nothing (_onRequest is NULL), we don't need to really parse the body. + const bool needParse = _handler && !_handler->isRequestHandlerTrivial(); + if (_isMultipart) { + if (needParse) { + size_t i; + for (i = 0; i < len; i++) { + _parseMultipartPostByte(((uint8_t*)buf)[i], i == len - 1); + _parsedLength++; + } + } else + _parsedLength += len; + } else { + if (_parsedLength == 0) { + if (_contentType.startsWith(F("application/x-www-form-urlencoded"))) { + _isPlainPost = true; + } else if (_contentType == F("text/plain") && __is_param_char(((char*)buf)[0])) { + size_t i = 0; + while (i < len && __is_param_char(((char*)buf)[i++])) + ; + if (i < len && ((char*)buf)[i - 1] == '=') { + _isPlainPost = true; + } + } + } + if (!_isPlainPost) { + // check if authenticated before calling the body + if (_handler) + _handler->handleBody(this, (uint8_t*)buf, len, _parsedLength, _contentLength); + _parsedLength += len; + } else if (needParse) { + size_t i; + for (i = 0; i < len; i++) { + _parsedLength++; + _parsePlainPostChar(((uint8_t*)buf)[i]); + } + } else { + _parsedLength += len; + } + } + if (_parsedLength == _contentLength) { + _parseState = PARSE_REQ_END; + // check if authenticated before calling handleRequest and request auth instead + if (_handler) + _handler->handleRequest(this); + else + send(501); + } + } + break; + } +} + +void AsyncWebServerRequest::_removeNotInterestingHeaders() { + if (std::any_of(std::begin(_interestingHeaders), std::end(_interestingHeaders), [](const String& str) { return str.equalsIgnoreCase(F("ANY")); })) + return; // nothing to do + + for (auto iter = std::begin(_headers); iter != std::end(_headers);) { + const auto name = iter->name(); + + if (std::none_of(std::begin(_interestingHeaders), std::end(_interestingHeaders), [&name](const String& str) { return str.equalsIgnoreCase(name); })) + iter = _headers.erase(iter); + else + iter++; + } +} + +void AsyncWebServerRequest::_onPoll() { + // os_printf("p\n"); + if (_response != NULL && _client != NULL && _client->canSend()) { + if (!_response->_finished()) { + _response->_ack(this, 0, 0); + } else { + AsyncWebServerResponse* r = _response; + _response = NULL; + delete r; + + _client->close(); + } + } +} + +void AsyncWebServerRequest::_onAck(size_t len, uint32_t time) { + // os_printf("a:%u:%u\n", len, time); + if (_response != NULL) { + if (!_response->_finished()) { + _response->_ack(this, len, time); + } else if (_response->_finished()) { + AsyncWebServerResponse* r = _response; + _response = NULL; + delete r; + + _client->close(); + } + } +} + +void AsyncWebServerRequest::_onError(int8_t error) { + (void)error; +} + +void AsyncWebServerRequest::_onTimeout(uint32_t time) { + (void)time; + // os_printf("TIMEOUT: %u, state: %s\n", time, _client->stateToString()); + _client->close(); +} + +void AsyncWebServerRequest::onDisconnect(ArDisconnectHandler fn) { + _onDisconnectfn = fn; +} + +void AsyncWebServerRequest::_onDisconnect() { + // os_printf("d\n"); + if (_onDisconnectfn) { + _onDisconnectfn(); + } + _server->_handleDisconnect(this); +} + +void AsyncWebServerRequest::_addPathParam(const char* p) { + _pathParams.emplace_back(p); +} + +void AsyncWebServerRequest::_addGetParams(const String& params) { + size_t start = 0; + while (start < params.length()) { + int end = params.indexOf('&', start); + if (end < 0) + end = params.length(); + int equal = params.indexOf('=', start); + if (equal < 0 || equal > end) + equal = end; + String name(params.substring(start, equal)); + String value(equal + 1 < end ? params.substring(equal + 1, end) : String()); + _params.emplace_back(urlDecode(name), urlDecode(value)); + start = end + 1; + } +} + +bool AsyncWebServerRequest::_parseReqHead() { + // Split the head into method, url and version + int index = _temp.indexOf(' '); + String m = _temp.substring(0, index); + index = _temp.indexOf(' ', index + 1); + String u = _temp.substring(m.length() + 1, index); + _temp = _temp.substring(index + 1); + + if (m == F("GET")) { + _method = HTTP_GET; + } else if (m == F("POST")) { + _method = HTTP_POST; + } else if (m == F("DELETE")) { + _method = HTTP_DELETE; + } else if (m == F("PUT")) { + _method = HTTP_PUT; + } else if (m == F("PATCH")) { + _method = HTTP_PATCH; + } else if (m == F("HEAD")) { + _method = HTTP_HEAD; + } else if (m == F("OPTIONS")) { + _method = HTTP_OPTIONS; + } + + String g; + index = u.indexOf('?'); + if (index > 0) { + g = u.substring(index + 1); + u = u.substring(0, index); + } + _url = urlDecode(u); + _addGetParams(g); + + if (!_temp.startsWith(F("HTTP/1.0"))) + _version = 1; + + _temp = String(); + return true; +} + +bool strContains(const String& src, const String& find, bool mindcase = true) { + int pos = 0, i = 0; + const int slen = src.length(); + const int flen = find.length(); + + if (slen < flen) + return false; + while (pos <= (slen - flen)) { + for (i = 0; i < flen; i++) { + if (mindcase) { + if (src[pos + i] != find[i]) + i = flen + 1; // no match + } else if (tolower(src[pos + i]) != tolower(find[i])) { + i = flen + 1; // no match + } + } + if (i == flen) + return true; + pos++; + } + return false; +} + +bool AsyncWebServerRequest::_parseReqHeader() { + int index = _temp.indexOf(':'); + if (index) { + String name = _temp.substring(0, index); + String value = _temp.substring(index + 2); + if (name.equalsIgnoreCase("Host")) { + _host = value; + } else if (name.equalsIgnoreCase(F("Content-Type"))) { + _contentType = value.substring(0, value.indexOf(';')); + if (value.startsWith(F("multipart/"))) { + _boundary = value.substring(value.indexOf('=') + 1); + _boundary.replace(String('"'), String()); + _isMultipart = true; + } + } else if (name.equalsIgnoreCase(F("Content-Length"))) { + _contentLength = atoi(value.c_str()); + } else if (name.equalsIgnoreCase(F("Expect")) && value == F("100-continue")) { + _expectingContinue = true; + } else if (name.equalsIgnoreCase(F("Authorization"))) { + if (value.length() > 5 && value.substring(0, 5).equalsIgnoreCase(F("Basic"))) { + _authorization = value.substring(6); + } else if (value.length() > 6 && value.substring(0, 6).equalsIgnoreCase(F("Digest"))) { + _isDigest = true; + _authorization = value.substring(7); + } + } else { + if (name.equalsIgnoreCase(F("Upgrade")) && value.equalsIgnoreCase(F("websocket"))) { + // WebSocket request can be uniquely identified by header: [Upgrade: websocket] + _reqconntype = RCT_WS; + } else { + if (name.equalsIgnoreCase(F("Accept")) && strContains(value, F("text/event-stream"), false)) { + // WebEvent request can be uniquely identified by header: [Accept: text/event-stream] + _reqconntype = RCT_EVENT; + } + } + } + _headers.emplace_back(name, value); + } + _temp = String(); + return true; +} + +void AsyncWebServerRequest::_parsePlainPostChar(uint8_t data) { + if (data && (char)data != '&') + _temp += (char)data; + if (!data || (char)data == '&' || _parsedLength == _contentLength) { + String name = F("body"); + String value = _temp; + if (!_temp.startsWith(String('{')) && !_temp.startsWith(String('[')) && _temp.indexOf('=') > 0) { + name = _temp.substring(0, _temp.indexOf('=')); + value = _temp.substring(_temp.indexOf('=') + 1); + } + _params.emplace_back(urlDecode(name), urlDecode(value), true); + _temp = String(); + } +} + +void AsyncWebServerRequest::_handleUploadByte(uint8_t data, bool last) { + _itemBuffer[_itemBufferIndex++] = data; + + if (last || _itemBufferIndex == 1460) { + // check if authenticated before calling the upload + if (_handler) + _handler->handleUpload(this, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, false); + _itemBufferIndex = 0; + } +} + +enum { + EXPECT_BOUNDARY, + PARSE_HEADERS, + WAIT_FOR_RETURN1, + EXPECT_FEED1, + EXPECT_DASH1, + EXPECT_DASH2, + BOUNDARY_OR_DATA, + DASH3_OR_RETURN2, + EXPECT_FEED2, + PARSING_FINISHED, + PARSE_ERROR +}; + +void AsyncWebServerRequest::_parseMultipartPostByte(uint8_t data, bool last) { +#define itemWriteByte(b) \ + do { \ + _itemSize++; \ + if (_itemIsFile) \ + _handleUploadByte(b, last); \ + else \ + _itemValue += (char)(b); \ + } while (0) + + if (!_parsedLength) { + _multiParseState = EXPECT_BOUNDARY; + _temp = String(); + _itemName = String(); + _itemFilename = String(); + _itemType = String(); + } + + if (_multiParseState == WAIT_FOR_RETURN1) { + if (data != '\r') { + itemWriteByte(data); + } else { + _multiParseState = EXPECT_FEED1; + } + } else if (_multiParseState == EXPECT_BOUNDARY) { + if (_parsedLength < 2 && data != '-') { + _multiParseState = PARSE_ERROR; + return; + } else if (_parsedLength - 2 < _boundary.length() && _boundary.c_str()[_parsedLength - 2] != data) { + _multiParseState = PARSE_ERROR; + return; + } else if (_parsedLength - 2 == _boundary.length() && data != '\r') { + _multiParseState = PARSE_ERROR; + return; + } else if (_parsedLength - 3 == _boundary.length()) { + if (data != '\n') { + _multiParseState = PARSE_ERROR; + return; + } + _multiParseState = PARSE_HEADERS; + _itemIsFile = false; + } + } else if (_multiParseState == PARSE_HEADERS) { + if ((char)data != '\r' && (char)data != '\n') + _temp += (char)data; + if ((char)data == '\n') { + if (_temp.length()) { + if (_temp.length() > 12 && _temp.substring(0, 12).equalsIgnoreCase(F("Content-Type"))) { + _itemType = _temp.substring(14); + _itemIsFile = true; + } else if (_temp.length() > 19 && _temp.substring(0, 19).equalsIgnoreCase(F("Content-Disposition"))) { + _temp = _temp.substring(_temp.indexOf(';') + 2); + while (_temp.indexOf(';') > 0) { + String name = _temp.substring(0, _temp.indexOf('=')); + String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.indexOf(';') - 1); + if (name == F("name")) { + _itemName = nameVal; + } else if (name == F("filename")) { + _itemFilename = nameVal; + _itemIsFile = true; + } + _temp = _temp.substring(_temp.indexOf(';') + 2); + } + String name = _temp.substring(0, _temp.indexOf('=')); + String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.length() - 1); + if (name == F("name")) { + _itemName = nameVal; + } else if (name == F("filename")) { + _itemFilename = nameVal; + _itemIsFile = true; + } + } + _temp = String(); + } else { + _multiParseState = WAIT_FOR_RETURN1; + // value starts from here + _itemSize = 0; + _itemStartIndex = _parsedLength; + _itemValue = String(); + if (_itemIsFile) { + if (_itemBuffer) + free(_itemBuffer); + _itemBuffer = (uint8_t*)malloc(1460); + if (_itemBuffer == NULL) { + _multiParseState = PARSE_ERROR; + return; + } + _itemBufferIndex = 0; + } + } + } + } else if (_multiParseState == EXPECT_FEED1) { + if (data != '\n') { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + _parseMultipartPostByte(data, last); + } else { + _multiParseState = EXPECT_DASH1; + } + } else if (_multiParseState == EXPECT_DASH1) { + if (data != '-') { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + _parseMultipartPostByte(data, last); + } else { + _multiParseState = EXPECT_DASH2; + } + } else if (_multiParseState == EXPECT_DASH2) { + if (data != '-') { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + _parseMultipartPostByte(data, last); + } else { + _multiParseState = BOUNDARY_OR_DATA; + _boundaryPosition = 0; + } + } else if (_multiParseState == BOUNDARY_OR_DATA) { + if (_boundaryPosition < _boundary.length() && _boundary.c_str()[_boundaryPosition] != data) { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + itemWriteByte('-'); + uint8_t i; + for (i = 0; i < _boundaryPosition; i++) + itemWriteByte(_boundary.c_str()[i]); + _parseMultipartPostByte(data, last); + } else if (_boundaryPosition == _boundary.length() - 1) { + _multiParseState = DASH3_OR_RETURN2; + if (!_itemIsFile) { + _params.emplace_back(_itemName, _itemValue, true); + } else { + if (_itemSize) { + // check if authenticated before calling the upload + if (_handler) + _handler->handleUpload(this, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, true); + _itemBufferIndex = 0; + _params.emplace_back(_itemName, _itemFilename, true, true, _itemSize); + } + free(_itemBuffer); + _itemBuffer = NULL; + } + + } else { + _boundaryPosition++; + } + } else if (_multiParseState == DASH3_OR_RETURN2) { + if (data == '-' && (_contentLength - _parsedLength - 4) != 0) { + // os_printf("ERROR: The parser got to the end of the POST but is expecting %u bytes more!\nDrop an issue so we can have more info on the matter!\n", _contentLength - _parsedLength - 4); + _contentLength = _parsedLength + 4; // lets close the request gracefully + } + if (data == '\r') { + _multiParseState = EXPECT_FEED2; + } else if (data == '-' && _contentLength == (_parsedLength + 4)) { + _multiParseState = PARSING_FINISHED; + } else { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + itemWriteByte('-'); + uint8_t i; + for (i = 0; i < _boundary.length(); i++) + itemWriteByte(_boundary.c_str()[i]); + _parseMultipartPostByte(data, last); + } + } else if (_multiParseState == EXPECT_FEED2) { + if (data == '\n') { + _multiParseState = PARSE_HEADERS; + _itemIsFile = false; + } else { + _multiParseState = WAIT_FOR_RETURN1; + itemWriteByte('\r'); + itemWriteByte('\n'); + itemWriteByte('-'); + itemWriteByte('-'); + uint8_t i; + for (i = 0; i < _boundary.length(); i++) + itemWriteByte(_boundary.c_str()[i]); + itemWriteByte('\r'); + _parseMultipartPostByte(data, last); + } + } +} + +void AsyncWebServerRequest::_parseLine() { + if (_parseState == PARSE_REQ_START) { + if (!_temp.length()) { + _parseState = PARSE_REQ_FAIL; + _client->close(); + } else { + _parseReqHead(); + _parseState = PARSE_REQ_HEADERS; + } + return; + } + + if (_parseState == PARSE_REQ_HEADERS) { + if (!_temp.length()) { + // end of headers + _server->_rewriteRequest(this); + _server->_attachHandler(this); + _removeNotInterestingHeaders(); + if (_expectingContinue) { + String response = F("HTTP/1.1 100 Continue\r\n\r\n"); + _client->write(response.c_str(), response.length()); + } + // check handler for authentication + if (_contentLength) { + _parseState = PARSE_REQ_BODY; + } else { + _parseState = PARSE_REQ_END; + if (_handler) + _handler->handleRequest(this); + else + send(501); + } + } else + _parseReqHeader(); + } +} + +size_t AsyncWebServerRequest::headers() const { + return _headers.size(); +} + +bool AsyncWebServerRequest::hasHeader(const char* name) const { + for (const auto& h : _headers) { + if (h.name().equalsIgnoreCase(name)) { + return true; + } + } + return false; +} + +#ifdef ESP8266 +bool AsyncWebServerRequest::hasHeader(const __FlashStringHelper* data) const { + return hasHeader(String(data)); +} +#endif + +const AsyncWebHeader* AsyncWebServerRequest::getHeader(const char* name) const { + auto iter = std::find_if(std::begin(_headers), std::end(_headers), [&name](const AsyncWebHeader& header) { return header.name().equalsIgnoreCase(name); }); + + return (iter == std::end(_headers)) ? nullptr : &(*iter); +} + +#ifdef ESP8266 +const AsyncWebHeader* AsyncWebServerRequest::getHeader(const __FlashStringHelper* data) const { + PGM_P p = reinterpret_cast(data); + size_t n = strlen_P(p); + char* name = (char*)malloc(n + 1); + if (name) { + strcpy_P(name, p); + const AsyncWebHeader* result = getHeader(String(name)); + free(name); + return result; + } else { + return nullptr; + } +} +#endif + +const AsyncWebHeader* AsyncWebServerRequest::getHeader(size_t num) const { + if (num >= _headers.size()) + return nullptr; + return &(*std::next(_headers.cbegin(), num)); +} + +size_t AsyncWebServerRequest::params() const { + return _params.size(); +} + +bool AsyncWebServerRequest::hasParam(const String& name, bool post, bool file) const { + for (const auto& p : _params) { + if (p.name() == name && p.isPost() == post && p.isFile() == file) { + return true; + } + } + return false; +} + +bool AsyncWebServerRequest::hasParam(const __FlashStringHelper* data, bool post, bool file) const { + return hasParam(String(data).c_str(), post, file); +} + +const AsyncWebParameter* AsyncWebServerRequest::getParam(const char* name, bool post, bool file) const { + for (const auto& p : _params) { + if (p.name() == name && p.isPost() == post && p.isFile() == file) { + return &p; + } + } + return nullptr; +} + +#ifdef ESP8266 +const AsyncWebParameter* AsyncWebServerRequest::getParam(const __FlashStringHelper* data, bool post, bool file) const { + return getParam(String(data), post, file); +} +#endif + +const AsyncWebParameter* AsyncWebServerRequest::getParam(size_t num) const { + if (num >= _params.size()) + return nullptr; + return &(*std::next(_params.cbegin(), num)); +} + +void AsyncWebServerRequest::addInterestingHeader(const char* name) { + if (std::none_of(std::begin(_interestingHeaders), std::end(_interestingHeaders), [&name](const String& str) { return str.equalsIgnoreCase(name); })) + _interestingHeaders.emplace_back(name); +} + +AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& contentType, const String& content) { + return new AsyncBasicResponse(code, contentType, content); +} + +AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& 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) { + if (fs.exists(path) || (!download && fs.exists(path + F(".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) { + 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) { + return new AsyncStreamResponse(stream, contentType, len, callback); +} + +AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(const String& 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) { + if (_version) + return new AsyncChunkedResponse(contentType, callback, templateCallback); + return new AsyncCallbackResponse(contentType, 0, callback, templateCallback); +} + +AsyncResponseStream* AsyncWebServerRequest::beginResponseStream(const String& contentType, size_t bufferSize) { + return new AsyncResponseStream(contentType, bufferSize); +} + +void AsyncWebServerRequest::send(AsyncWebServerResponse* response) { + _response = response; + if (_response == NULL) { + _client->close(true); + _onDisconnect(); + return; + } + if (!_response->_sourceValid()) { + delete response; + _response = NULL; + send(500); + } else { + _client->setRxTimeout(0); + _response->_respond(this); + } +} + +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 + F(".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(F("Location"), url); + send(response); +} + +bool AsyncWebServerRequest::authenticate(const char* username, const char* password, const char* realm, bool passwordIsHash) { + if (_authorization.length()) { + if (_isDigest) + return checkDigestAuthentication(_authorization.c_str(), methodToString(), username, password, realm, passwordIsHash, NULL, NULL, NULL); + else if (!passwordIsHash) + return checkBasicAuthentication(_authorization.c_str(), username, password); + else + return _authorization.equals(password); + } + return false; +} + +bool AsyncWebServerRequest::authenticate(const char* hash) { + if (!_authorization.length() || hash == NULL) + return false; + + if (_isDigest) { + String hStr = String(hash); + int separator = hStr.indexOf(':'); + if (separator <= 0) + return false; + String username = hStr.substring(0, separator); + hStr = hStr.substring(separator + 1); + separator = hStr.indexOf(':'); + if (separator <= 0) + return false; + String realm = hStr.substring(0, separator); + hStr = hStr.substring(separator + 1); + return checkDigestAuthentication(_authorization.c_str(), methodToString(), username.c_str(), hStr.c_str(), realm.c_str(), true, NULL, NULL, NULL); + } + + return (_authorization.equals(hash)); +} + +void AsyncWebServerRequest::requestAuthentication(const char* realm, bool isDigest) { + AsyncWebServerResponse* r = beginResponse(401); + if (!isDigest && realm == NULL) { + r->addHeader(F("WWW-Authenticate"), F("Basic realm=\"Login Required\"")); + } else if (!isDigest) { + String header = F("Basic realm=\""); + header.concat(realm); + header += '"'; + r->addHeader(F("WWW-Authenticate"), header); + } else { + String header = F("Digest "); + header.concat(requestDigestAuthentication(realm)); + r->addHeader(F("WWW-Authenticate"), header); + } + send(r); +} + +bool AsyncWebServerRequest::hasArg(const char* name) const { + for (const auto& arg : _params) { + if (arg.name() == name) { + return true; + } + } + return false; +} + +#ifdef ESP8266 +bool AsyncWebServerRequest::hasArg(const __FlashStringHelper* data) const { + return hasArg(String(data).c_str()); +} +#endif + +const String& AsyncWebServerRequest::arg(const char* name) const { + for (const auto& arg : _params) { + if (arg.name() == name) { + return arg.value(); + } + } + return emptyString; +} + +#ifdef ESP8266 +const String& AsyncWebServerRequest::arg(const __FlashStringHelper* data) const { + return arg(String(data).c_str()); +} +#endif + +const String& AsyncWebServerRequest::arg(size_t i) const { + return getParam(i)->value(); +} + +const String& AsyncWebServerRequest::argName(size_t i) const { + return getParam(i)->name(); +} + +const String& AsyncWebServerRequest::pathArg(size_t i) const { + return i < _pathParams.size() ? _pathParams[i] : emptyString; +} + +const String& AsyncWebServerRequest::header(const char* name) const { + const AsyncWebHeader* h = getHeader(name); + return h ? h->value() : emptyString; +} + +#ifdef ESP8266 +const String& AsyncWebServerRequest::header(const __FlashStringHelper* data) const { + return header(String(data).c_str()); +}; +#endif + +const String& AsyncWebServerRequest::header(size_t i) const { + const AsyncWebHeader* h = getHeader(i); + return h ? h->value() : emptyString; +} + +const String& AsyncWebServerRequest::headerName(size_t i) const { + const AsyncWebHeader* h = getHeader(i); + return h ? h->name() : emptyString; +} + +String AsyncWebServerRequest::urlDecode(const String& text) const { + char temp[] = "0x00"; + unsigned int len = text.length(); + unsigned int i = 0; + String decoded; + decoded.reserve(len); // Allocate the string internal buffer - never longer from source text + while (i < len) { + char decodedChar; + char encodedChar = text.charAt(i++); + if ((encodedChar == '%') && (i + 1 < len)) { + temp[2] = text.charAt(i++); + temp[3] = text.charAt(i++); + decodedChar = strtol(temp, NULL, 16); + } else if (encodedChar == '+') { + decodedChar = ' '; + } else { + decodedChar = encodedChar; // normal ascii char + } + decoded.concat(decodedChar); + } + return decoded; +} + +#ifndef ESP8266 +const char* AsyncWebServerRequest::methodToString() const { + if (_method == HTTP_ANY) + return "ANY"; + if (_method & HTTP_GET) + return "GET"; + if (_method & HTTP_POST) + return "POST"; + if (_method & HTTP_DELETE) + return "DELETE"; + if (_method & HTTP_PUT) + return "PUT"; + if (_method & HTTP_PATCH) + return "PATCH"; + if (_method & HTTP_HEAD) + return "HEAD"; + if (_method & HTTP_OPTIONS) + return "OPTIONS"; + return "UNKNOWN"; +} + +const char* AsyncWebServerRequest::requestedConnTypeToString() const { + switch (_reqconntype) { + case RCT_NOT_USED: + return "RCT_NOT_USED"; + case RCT_DEFAULT: + return "RCT_DEFAULT"; + case RCT_HTTP: + return "RCT_HTTP"; + case RCT_WS: + return "RCT_WS"; + case RCT_EVENT: + return "RCT_EVENT"; + default: + return "ERROR"; + } +} +#endif + +#ifdef ESP8266 +const __FlashStringHelper* AsyncWebServerRequest::methodToString() const { + if (_method == HTTP_ANY) + return F("ANY"); + else if (_method & HTTP_GET) + return F("GET"); + else if (_method & HTTP_POST) + return F("POST"); + else if (_method & HTTP_DELETE) + return F("DELETE"); + else if (_method & HTTP_PUT) + return F("PUT"); + else if (_method & HTTP_PATCH) + return F("PATCH"); + else if (_method & HTTP_HEAD) + return F("HEAD"); + else if (_method & HTTP_OPTIONS) + return F("OPTIONS"); + return F("UNKNOWN"); +} + +const __FlashStringHelper* AsyncWebServerRequest::requestedConnTypeToString() const { + switch (_reqconntype) { + case RCT_NOT_USED: + return F("RCT_NOT_USED"); + case RCT_DEFAULT: + return F("RCT_DEFAULT"); + case RCT_HTTP: + return F("RCT_HTTP"); + case RCT_WS: + return F("RCT_WS"); + case RCT_EVENT: + return F("RCT_EVENT"); + default: + return F("ERROR"); + } +} +#endif + +bool AsyncWebServerRequest::isExpectedRequestedConnType(RequestedConnectionType erct1, RequestedConnectionType erct2, RequestedConnectionType erct3) { + bool res = false; + if ((erct1 != RCT_NOT_USED) && (erct1 == _reqconntype)) + res = true; + if ((erct2 != RCT_NOT_USED) && (erct2 == _reqconntype)) + res = true; + if ((erct3 != RCT_NOT_USED) && (erct3 == _reqconntype)) + res = true; + return res; +} diff --git a/lib/ESP Async WebServer/src/WebResponseImpl.h b/lib/ESP Async WebServer/src/WebResponseImpl.h new file mode 100644 index 0000000..26ec223 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebResponseImpl.h @@ -0,0 +1,148 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#ifndef ASYNCWEBSERVERRESPONSEIMPL_H_ +#define ASYNCWEBSERVERRESPONSEIMPL_H_ + +#ifdef Arduino_h + // arduino is not compatible with std::vector + #undef min + #undef max +#endif +#include +#include + +// It is possible to restore these defines, but one can use _min and _max instead. Or std::min, std::max. + +class AsyncBasicResponse : public AsyncWebServerResponse { + private: + String _content; + + public: + AsyncBasicResponse(int code, const String& contentType = String(), const String& content = String()); + void _respond(AsyncWebServerRequest* request); + size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time); + bool _sourceValid() const { return true; } +}; + +class AsyncAbstractResponse : public AsyncWebServerResponse { + private: + String _head; + // Data is inserted into cache at begin(). + // This is inefficient with vector, but if we use some other container, + // we won't be able to access it as contiguous array of bytes when reading from it, + // so by gaining performance in one place, we'll lose it in another. + std::vector _cache; + size_t _readDataFromCacheOrContent(uint8_t* data, const size_t len); + size_t _fillBufferAndProcessTemplates(uint8_t* buf, size_t maxLen); + + protected: + AwsTemplateProcessor _callback; + + public: + AsyncAbstractResponse(AwsTemplateProcessor callback = nullptr); + void _respond(AsyncWebServerRequest* request); + size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time); + bool _sourceValid() const { return false; } + virtual size_t _fillBuffer(uint8_t* buf __attribute__((unused)), size_t maxLen __attribute__((unused))) { return 0; } +}; + +#ifndef TEMPLATE_PLACEHOLDER + #define TEMPLATE_PLACEHOLDER '%' +#endif + +#define TEMPLATE_PARAM_NAME_LENGTH 32 +class AsyncFileResponse : public AsyncAbstractResponse { + using File = fs::File; + using FS = fs::FS; + + private: + File _content; + String _path; + void _setContentType(const String& path); + + public: + AsyncFileResponse(FS& fs, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr); + AsyncFileResponse(File content, const String& path, const String& contentType = String(), bool download = false, AwsTemplateProcessor callback = nullptr); + ~AsyncFileResponse(); + bool _sourceValid() const { return !!(_content); } + virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; +}; + +class AsyncStreamResponse : public AsyncAbstractResponse { + private: + Stream* _content; + + public: + AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr); + bool _sourceValid() const { return !!(_content); } + virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; +}; + +class AsyncCallbackResponse : public AsyncAbstractResponse { + private: + AwsResponseFiller _content; + size_t _filledLength; + + public: + AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); + bool _sourceValid() const { return !!(_content); } + virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; +}; + +class AsyncChunkedResponse : public AsyncAbstractResponse { + private: + AwsResponseFiller _content; + size_t _filledLength; + + public: + AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); + bool _sourceValid() const { return !!(_content); } + virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; +}; + +class AsyncProgmemResponse : public AsyncAbstractResponse { + private: + const uint8_t* _content; + size_t _readLength; + + public: + AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr); + bool _sourceValid() const { return true; } + virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; +}; + +class cbuf; + +class AsyncResponseStream : public AsyncAbstractResponse, public Print { + private: + std::unique_ptr _content; + + public: + AsyncResponseStream(const String& contentType, size_t bufferSize); + ~AsyncResponseStream(); + bool _sourceValid() const { return (_state < RESPONSE_END); } + virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; + size_t write(const uint8_t* data, size_t len); + size_t write(uint8_t data); + using Print::write; +}; + +#endif /* ASYNCWEBSERVERRESPONSEIMPL_H_ */ diff --git a/lib/ESP Async WebServer/src/WebResponses.cpp b/lib/ESP Async WebServer/src/WebResponses.cpp new file mode 100644 index 0000000..1fd41fa --- /dev/null +++ b/lib/ESP Async WebServer/src/WebResponses.cpp @@ -0,0 +1,751 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "ESPAsyncWebServer.h" +#include "WebResponseImpl.h" +#include "cbuf.h" + +// Since ESP8266 does not link memchr by default, here's its implementation. +void* memchr(void* ptr, int ch, size_t count) { + unsigned char* p = static_cast(ptr); + while (count--) + if (*p++ == static_cast(ch)) + return --p; + return nullptr; +} + +/* + * Abstract Response + * */ +const char* AsyncWebServerResponse::_responseCodeToString(int code) { + return reinterpret_cast(responseCodeToString(code)); +} + +const __FlashStringHelper* AsyncWebServerResponse::responseCodeToString(int code) { + switch (code) { + case 100: + return F("Continue"); + case 101: + return F("Switching Protocols"); + case 200: + return F("OK"); + case 201: + return F("Created"); + case 202: + return F("Accepted"); + case 203: + return F("Non-Authoritative Information"); + case 204: + return F("No Content"); + case 205: + return F("Reset Content"); + case 206: + return F("Partial Content"); + case 300: + return F("Multiple Choices"); + case 301: + return F("Moved Permanently"); + case 302: + return F("Found"); + case 303: + return F("See Other"); + case 304: + return F("Not Modified"); + case 305: + return F("Use Proxy"); + case 307: + return F("Temporary Redirect"); + case 400: + return F("Bad Request"); + case 401: + return F("Unauthorized"); + case 402: + return F("Payment Required"); + case 403: + return F("Forbidden"); + case 404: + return F("Not Found"); + case 405: + return F("Method Not Allowed"); + case 406: + return F("Not Acceptable"); + case 407: + return F("Proxy Authentication Required"); + case 408: + return F("Request Time-out"); + case 409: + return F("Conflict"); + case 410: + return F("Gone"); + case 411: + return F("Length Required"); + case 412: + return F("Precondition Failed"); + case 413: + return F("Request Entity Too Large"); + case 414: + return F("Request-URI Too Large"); + case 415: + return F("Unsupported Media Type"); + case 416: + return F("Requested range not satisfiable"); + case 417: + return F("Expectation Failed"); + case 500: + return F("Internal Server Error"); + case 501: + return F("Not Implemented"); + case 502: + return F("Bad Gateway"); + case 503: + return F("Service Unavailable"); + case 504: + return F("Gateway Time-out"); + case 505: + return F("HTTP Version not supported"); + default: + return F(""); + } +} + +AsyncWebServerResponse::AsyncWebServerResponse() + : _code(0), _contentType(), _contentLength(0), _sendContentLength(true), _chunked(false), _headLength(0), _sentLength(0), _ackedLength(0), _writtenLength(0), _state(RESPONSE_SETUP) { + for (const auto& header : DefaultHeaders::Instance()) { + _headers.emplace_back(header); + } +} + +AsyncWebServerResponse::~AsyncWebServerResponse() = default; + +void AsyncWebServerResponse::setCode(int code) { + if (_state == RESPONSE_SETUP) + _code = code; +} + +void AsyncWebServerResponse::setContentLength(size_t len) { + if (_state == RESPONSE_SETUP) + _contentLength = len; +} + +void AsyncWebServerResponse::setContentType(const String& type) { + if (_state == RESPONSE_SETUP) + _contentType = type; +} + +void AsyncWebServerResponse::addHeader(const String& name, const String& value) { + _headers.emplace_back(name, value); +} + +String AsyncWebServerResponse::_assembleHead(uint8_t version) { + if (version) { + addHeader(F("Accept-Ranges"), F("none")); + if (_chunked) + addHeader(F("Transfer-Encoding"), F("chunked")); + } + String out = String(); + int bufSize = 300; + char buf[bufSize]; + + snprintf_P(buf, bufSize, PSTR("HTTP/1.%d %d %s\r\n"), version, _code, _responseCodeToString(_code)); + out.concat(buf); + + if (_sendContentLength) { + snprintf_P(buf, bufSize, PSTR("Content-Length: %d\r\n"), _contentLength); + out.concat(buf); + } + if (_contentType.length()) { + snprintf_P(buf, bufSize, PSTR("Content-Type: %s\r\n"), _contentType.c_str()); + out.concat(buf); + } + + for (const auto& header : _headers) { + snprintf_P(buf, bufSize, PSTR("%s: %s\r\n"), header.name().c_str(), header.value().c_str()); + out.concat(buf); + } + _headers.clear(); + + out.concat(F("\r\n")); + _headLength = out.length(); + return out; +} + +bool AsyncWebServerResponse::_started() const { return _state > RESPONSE_SETUP; } +bool AsyncWebServerResponse::_finished() const { return _state > RESPONSE_WAIT_ACK; } +bool AsyncWebServerResponse::_failed() const { return _state == RESPONSE_FAILED; } +bool AsyncWebServerResponse::_sourceValid() const { return false; } +void AsyncWebServerResponse::_respond(AsyncWebServerRequest* request) { + _state = RESPONSE_END; + request->client()->close(); +} +size_t AsyncWebServerResponse::_ack(AsyncWebServerRequest* request, size_t len, uint32_t time) { + (void)request; + (void)len; + (void)time; + return 0; +} + +/* + * String/Code Response + * */ +AsyncBasicResponse::AsyncBasicResponse(int code, const String& contentType, const String& content) { + _code = code; + _content = content; + _contentType = contentType; + if (_content.length()) { + _contentLength = _content.length(); + if (!_contentType.length()) + _contentType = F("text/plain"); + } + addHeader(F("Connection"), F("close")); +} + +void AsyncBasicResponse::_respond(AsyncWebServerRequest* request) { + _state = RESPONSE_HEADERS; + String out = _assembleHead(request->version()); + size_t outLen = out.length(); + size_t space = request->client()->space(); + if (!_contentLength && space >= outLen) { + _writtenLength += request->client()->write(out.c_str(), outLen); + _state = RESPONSE_WAIT_ACK; + } else if (_contentLength && space >= outLen + _contentLength) { + out += _content; + outLen += _contentLength; + _writtenLength += request->client()->write(out.c_str(), outLen); + _state = RESPONSE_WAIT_ACK; + } else if (space && space < outLen) { + String partial = out.substring(0, space); + _content = out.substring(space) + _content; + _contentLength += outLen - space; + _writtenLength += request->client()->write(partial.c_str(), partial.length()); + _state = RESPONSE_CONTENT; + } else if (space > outLen && space < (outLen + _contentLength)) { + size_t shift = space - outLen; + outLen += shift; + _sentLength += shift; + out += _content.substring(0, shift); + _content = _content.substring(shift); + _writtenLength += request->client()->write(out.c_str(), outLen); + _state = RESPONSE_CONTENT; + } else { + _content = out + _content; + _contentLength += outLen; + _state = RESPONSE_CONTENT; + } +} + +size_t AsyncBasicResponse::_ack(AsyncWebServerRequest* request, size_t len, uint32_t time) { + (void)time; + _ackedLength += len; + if (_state == RESPONSE_CONTENT) { + size_t available = _contentLength - _sentLength; + size_t space = request->client()->space(); + // we can fit in this packet + if (space > available) { + _writtenLength += request->client()->write(_content.c_str(), available); + _content = String(); + _state = RESPONSE_WAIT_ACK; + return available; + } + // send some data, the rest on ack + String out = _content.substring(0, space); + _content = _content.substring(space); + _sentLength += space; + _writtenLength += request->client()->write(out.c_str(), space); + return space; + } else if (_state == RESPONSE_WAIT_ACK) { + if (_ackedLength >= _writtenLength) { + _state = RESPONSE_END; + } + } + return 0; +} + +/* + * Abstract Response + * */ + +AsyncAbstractResponse::AsyncAbstractResponse(AwsTemplateProcessor callback) : _callback(callback) { + // In case of template processing, we're unable to determine real response size + if (callback) { + _contentLength = 0; + _sendContentLength = false; + _chunked = true; + } +} + +void AsyncAbstractResponse::_respond(AsyncWebServerRequest* request) { + addHeader(F("Connection"), F("close")); + _head = _assembleHead(request->version()); + _state = RESPONSE_HEADERS; + _ack(request, 0, 0); +} + +size_t AsyncAbstractResponse::_ack(AsyncWebServerRequest* request, size_t len, uint32_t time) { + (void)time; + if (!_sourceValid()) { + _state = RESPONSE_FAILED; + request->client()->close(); + return 0; + } + _ackedLength += len; + size_t space = request->client()->space(); + + size_t headLen = _head.length(); + if (_state == RESPONSE_HEADERS) { + if (space >= headLen) { + _state = RESPONSE_CONTENT; + space -= headLen; + } else { + String out = _head.substring(0, space); + _head = _head.substring(space); + _writtenLength += request->client()->write(out.c_str(), out.length()); + return out.length(); + } + } + + if (_state == RESPONSE_CONTENT) { + size_t outLen; + if (_chunked) { + if (space <= 8) { + return 0; + } + outLen = space; + } else if (!_sendContentLength) { + outLen = space; + } else { + outLen = ((_contentLength - _sentLength) > space) ? space : (_contentLength - _sentLength); + } + + uint8_t* buf = (uint8_t*)malloc(outLen + headLen); + if (!buf) { + // os_printf("_ack malloc %d failed\n", outLen+headLen); + return 0; + } + + if (headLen) { + memcpy(buf, _head.c_str(), _head.length()); + } + + size_t readLen = 0; + + if (_chunked) { + // HTTP 1.1 allows leading zeros in chunk length. Or spaces may be added. + // See RFC2616 sections 2, 3.6.1. + readLen = _fillBufferAndProcessTemplates(buf + headLen + 6, outLen - 8); + if (readLen == RESPONSE_TRY_AGAIN) { + free(buf); + return 0; + } + outLen = sprintf_P((char*)buf + headLen, PSTR("%x"), readLen) + headLen; + while (outLen < headLen + 4) + buf[outLen++] = ' '; + buf[outLen++] = '\r'; + buf[outLen++] = '\n'; + outLen += readLen; + buf[outLen++] = '\r'; + buf[outLen++] = '\n'; + } else { + readLen = _fillBufferAndProcessTemplates(buf + headLen, outLen); + if (readLen == RESPONSE_TRY_AGAIN) { + free(buf); + return 0; + } + outLen = readLen + headLen; + } + + if (headLen) { + _head = String(); + } + + if (outLen) { + _writtenLength += request->client()->write((const char*)buf, outLen); + } + + if (_chunked) { + _sentLength += readLen; + } else { + _sentLength += outLen - headLen; + } + + free(buf); + + if ((_chunked && readLen == 0) || (!_sendContentLength && outLen == 0) || (!_chunked && _sentLength == _contentLength)) { + _state = RESPONSE_WAIT_ACK; + } + return outLen; + + } else if (_state == RESPONSE_WAIT_ACK) { + if (!_sendContentLength || _ackedLength >= _writtenLength) { + _state = RESPONSE_END; + if (!_chunked && !_sendContentLength) + request->client()->close(true); + } + } + return 0; +} + +size_t AsyncAbstractResponse::_readDataFromCacheOrContent(uint8_t* data, const size_t len) { + // If we have something in cache, copy it to buffer + const size_t readFromCache = std::min(len, _cache.size()); + if (readFromCache) { + memcpy(data, _cache.data(), readFromCache); + _cache.erase(_cache.begin(), _cache.begin() + readFromCache); + } + // If we need to read more... + const size_t needFromFile = len - readFromCache; + const size_t readFromContent = _fillBuffer(data + readFromCache, needFromFile); + return readFromCache + readFromContent; +} + +size_t AsyncAbstractResponse::_fillBufferAndProcessTemplates(uint8_t* data, size_t len) { + if (!_callback) + return _fillBuffer(data, len); + + const size_t originalLen = len; + len = _readDataFromCacheOrContent(data, len); + // Now we've read 'len' bytes, either from cache or from file + // Search for template placeholders + uint8_t* pTemplateStart = data; + while ((pTemplateStart < &data[len]) && (pTemplateStart = (uint8_t*)memchr(pTemplateStart, TEMPLATE_PLACEHOLDER, &data[len - 1] - pTemplateStart + 1))) { // data[0] ... data[len - 1] + uint8_t* pTemplateEnd = (pTemplateStart < &data[len - 1]) ? (uint8_t*)memchr(pTemplateStart + 1, TEMPLATE_PLACEHOLDER, &data[len - 1] - pTemplateStart) : nullptr; + // temporary buffer to hold parameter name + uint8_t buf[TEMPLATE_PARAM_NAME_LENGTH + 1]; + String paramName; + // If closing placeholder is found: + if (pTemplateEnd) { + // prepare argument to callback + const size_t paramNameLength = std::min((size_t)sizeof(buf) - 1, (size_t)(pTemplateEnd - pTemplateStart - 1)); + if (paramNameLength) { + memcpy(buf, pTemplateStart + 1, paramNameLength); + buf[paramNameLength] = 0; + paramName = String(reinterpret_cast(buf)); + } else { // double percent sign encountered, this is single percent sign escaped. + // remove the 2nd percent sign + memmove(pTemplateEnd, pTemplateEnd + 1, &data[len] - pTemplateEnd - 1); + len += _readDataFromCacheOrContent(&data[len - 1], 1) - 1; + ++pTemplateStart; + } + } else if (&data[len - 1] - pTemplateStart + 1 < TEMPLATE_PARAM_NAME_LENGTH + 2) { // closing placeholder not found, check if it's in the remaining file data + memcpy(buf, pTemplateStart + 1, &data[len - 1] - pTemplateStart); + const size_t readFromCacheOrContent = _readDataFromCacheOrContent(buf + (&data[len - 1] - pTemplateStart), TEMPLATE_PARAM_NAME_LENGTH + 2 - (&data[len - 1] - pTemplateStart + 1)); + if (readFromCacheOrContent) { + pTemplateEnd = (uint8_t*)memchr(buf + (&data[len - 1] - pTemplateStart), TEMPLATE_PLACEHOLDER, readFromCacheOrContent); + if (pTemplateEnd) { + // prepare argument to callback + *pTemplateEnd = 0; + paramName = String(reinterpret_cast(buf)); + // Copy remaining read-ahead data into cache + _cache.insert(_cache.begin(), pTemplateEnd + 1, buf + (&data[len - 1] - pTemplateStart) + readFromCacheOrContent); + pTemplateEnd = &data[len - 1]; + } else // closing placeholder not found in file data, store found percent symbol as is and advance to the next position + { + // but first, store read file data in cache + _cache.insert(_cache.begin(), buf + (&data[len - 1] - pTemplateStart), buf + (&data[len - 1] - pTemplateStart) + readFromCacheOrContent); + ++pTemplateStart; + } + } else // closing placeholder not found in content data, store found percent symbol as is and advance to the next position + ++pTemplateStart; + } else // closing placeholder not found in content data, store found percent symbol as is and advance to the next position + ++pTemplateStart; + if (paramName.length()) { + // call callback and replace with result. + // Everything in range [pTemplateStart, pTemplateEnd] can be safely replaced with parameter value. + // Data after pTemplateEnd may need to be moved. + // The first byte of data after placeholder is located at pTemplateEnd + 1. + // It should be located at pTemplateStart + numBytesCopied (to begin right after inserted parameter value). + const String paramValue(_callback(paramName)); + const char* pvstr = paramValue.c_str(); + const unsigned int pvlen = paramValue.length(); + const size_t numBytesCopied = std::min(pvlen, static_cast(&data[originalLen - 1] - pTemplateStart + 1)); + // make room for param value + // 1. move extra data to cache if parameter value is longer than placeholder AND if there is no room to store + if ((pTemplateEnd + 1 < pTemplateStart + numBytesCopied) && (originalLen - (pTemplateStart + numBytesCopied - pTemplateEnd - 1) < len)) { + _cache.insert(_cache.begin(), &data[originalLen - (pTemplateStart + numBytesCopied - pTemplateEnd - 1)], &data[len]); + // 2. parameter value is longer than placeholder text, push the data after placeholder which not saved into cache further to the end + memmove(pTemplateStart + numBytesCopied, pTemplateEnd + 1, &data[originalLen] - pTemplateStart - numBytesCopied); + len = originalLen; // fix issue with truncated data, not sure if it has any side effects + } else if (pTemplateEnd + 1 != pTemplateStart + numBytesCopied) + // 2. Either parameter value is shorter than placeholder text OR there is enough free space in buffer to fit. + // Move the entire data after the placeholder + memmove(pTemplateStart + numBytesCopied, pTemplateEnd + 1, &data[len] - pTemplateEnd - 1); + // 3. replace placeholder with actual value + memcpy(pTemplateStart, pvstr, numBytesCopied); + // If result is longer than buffer, copy the remainder into cache (this could happen only if placeholder text itself did not fit entirely in buffer) + if (numBytesCopied < pvlen) { + _cache.insert(_cache.begin(), pvstr + numBytesCopied, pvstr + pvlen); + } else if (pTemplateStart + numBytesCopied < pTemplateEnd + 1) { // result is copied fully; if result is shorter than placeholder text... + // there is some free room, fill it from cache + const size_t roomFreed = pTemplateEnd + 1 - pTemplateStart - numBytesCopied; + const size_t totalFreeRoom = originalLen - len + roomFreed; + len += _readDataFromCacheOrContent(&data[len - roomFreed], totalFreeRoom) - roomFreed; + } else { // result is copied fully; it is longer than placeholder text + const size_t roomTaken = pTemplateStart + numBytesCopied - pTemplateEnd - 1; + len = std::min(len + roomTaken, originalLen); + } + } + } // while(pTemplateStart) + return len; +} + +/* + * File Response + * */ + +AsyncFileResponse::~AsyncFileResponse() { + if (_content) + _content.close(); +} + +void AsyncFileResponse::_setContentType(const String& path) { +#if HAVE_EXTERN_GET_CONTENT_TYPE_FUNCTION + extern const __FlashStringHelper* getContentType(const String& path); + _contentType = getContentType(path); +#else + if (path.endsWith(F(".html"))) + _contentType = F("text/html"); + else if (path.endsWith(F(".htm"))) + _contentType = F("text/html"); + else if (path.endsWith(F(".css"))) + _contentType = F("text/css"); + else if (path.endsWith(F(".json"))) + _contentType = F("application/json"); + else if (path.endsWith(F(".js"))) + _contentType = F("application/javascript"); + else if (path.endsWith(F(".png"))) + _contentType = F("image/png"); + else if (path.endsWith(F(".gif"))) + _contentType = F("image/gif"); + else if (path.endsWith(F(".jpg"))) + _contentType = F("image/jpeg"); + else if (path.endsWith(F(".ico"))) + _contentType = F("image/x-icon"); + else if (path.endsWith(F(".svg"))) + _contentType = F("image/svg+xml"); + else if (path.endsWith(F(".eot"))) + _contentType = F("font/eot"); + else if (path.endsWith(F(".woff"))) + _contentType = F("font/woff"); + else if (path.endsWith(F(".woff2"))) + _contentType = F("font/woff2"); + else if (path.endsWith(F(".ttf"))) + _contentType = F("font/ttf"); + else if (path.endsWith(F(".xml"))) + _contentType = F("text/xml"); + else if (path.endsWith(F(".pdf"))) + _contentType = F("application/pdf"); + else if (path.endsWith(F(".zip"))) + _contentType = F("application/zip"); + else if (path.endsWith(F(".gz"))) + _contentType = F("application/x-gzip"); + else + _contentType = F("text/plain"); +#endif +} + +AsyncFileResponse::AsyncFileResponse(FS& fs, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { + _code = 200; + _path = path; + + if (!download && !fs.exists(_path) && fs.exists(_path + F(".gz"))) { + _path = _path + F(".gz"); + addHeader(F("Content-Encoding"), F("gzip")); + _callback = nullptr; // Unable to process zipped templates + _sendContentLength = true; + _chunked = false; + } + + _content = fs.open(_path, fs::FileOpenMode::read); + _contentLength = _content.size(); + + if (contentType.length() == 0) + _setContentType(path); + else + _contentType = contentType; + + int filenameStart = path.lastIndexOf('/') + 1; + char buf[26 + path.length() - filenameStart]; + char* filename = (char*)path.c_str() + filenameStart; + + if (download) { + // set filename and force download + snprintf_P(buf, sizeof(buf), PSTR("attachment; filename=\"%s\""), filename); + } else { + // set filename and force rendering + snprintf_P(buf, sizeof(buf), PSTR("inline")); + } + addHeader(F("Content-Disposition"), buf); +} + +AsyncFileResponse::AsyncFileResponse(File content, const String& path, const String& contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { + _code = 200; + _path = path; + + if (!download && String(content.name()).endsWith(F(".gz")) && !path.endsWith(F(".gz"))) { + addHeader(F("Content-Encoding"), F("gzip")); + _callback = nullptr; // Unable to process gzipped templates + _sendContentLength = true; + _chunked = false; + } + + _content = content; + _contentLength = _content.size(); + + if (contentType.length() == 0) + _setContentType(path); + else + _contentType = contentType; + + int filenameStart = path.lastIndexOf('/') + 1; + char buf[26 + path.length() - filenameStart]; + char* filename = (char*)path.c_str() + filenameStart; + + if (download) { + snprintf_P(buf, sizeof(buf), PSTR("attachment; filename=\"%s\""), filename); + } else { + snprintf_P(buf, sizeof(buf), PSTR("inline")); + } + addHeader(F("Content-Disposition"), buf); +} + +size_t AsyncFileResponse::_fillBuffer(uint8_t* data, size_t len) { + return _content.read(data, len); +} + +/* + * Stream Response + * */ + +AsyncStreamResponse::AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { + _code = 200; + _content = &stream; + _contentLength = len; + _contentType = contentType; +} + +size_t AsyncStreamResponse::_fillBuffer(uint8_t* data, size_t len) { + size_t available = _content->available(); + size_t outLen = (available > len) ? len : available; + size_t i; + for (i = 0; i < outLen; i++) + data[i] = _content->read(); + return outLen; +} + +/* + * Callback Response + * */ + +AsyncCallbackResponse::AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) : AsyncAbstractResponse(templateCallback) { + _code = 200; + _content = callback; + _contentLength = len; + if (!len) + _sendContentLength = false; + _contentType = contentType; + _filledLength = 0; +} + +size_t AsyncCallbackResponse::_fillBuffer(uint8_t* data, size_t len) { + size_t ret = _content(data, len, _filledLength); + if (ret != RESPONSE_TRY_AGAIN) { + _filledLength += ret; + } + return ret; +} + +/* + * Chunked Response + * */ + +AsyncChunkedResponse::AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor processorCallback) : AsyncAbstractResponse(processorCallback) { + _code = 200; + _content = callback; + _contentLength = 0; + _contentType = contentType; + _sendContentLength = false; + _chunked = true; + _filledLength = 0; +} + +size_t AsyncChunkedResponse::_fillBuffer(uint8_t* data, size_t len) { + size_t ret = _content(data, len, _filledLength); + if (ret != RESPONSE_TRY_AGAIN) { + _filledLength += ret; + } + return ret; +} + +/* + * Progmem Response + * */ + +AsyncProgmemResponse::AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { + _code = code; + _content = content; + _contentType = contentType; + _contentLength = len; + _readLength = 0; +} + +size_t AsyncProgmemResponse::_fillBuffer(uint8_t* data, size_t len) { + size_t left = _contentLength - _readLength; + if (left > len) { + memcpy_P(data, _content + _readLength, len); + _readLength += len; + return len; + } + memcpy_P(data, _content + _readLength, left); + _readLength += left; + return left; +} + +/* + * Response Stream (You can print/write/printf to it, up to the contentLen bytes) + * */ + +AsyncResponseStream::AsyncResponseStream(const String& contentType, size_t bufferSize) { + _code = 200; + _contentLength = 0; + _contentType = contentType; + _content = std::unique_ptr(new cbuf(bufferSize)); // std::make_unique(bufferSize); +} + +AsyncResponseStream::~AsyncResponseStream() = default; + +size_t AsyncResponseStream::_fillBuffer(uint8_t* buf, size_t maxLen) { + return _content->read((char*)buf, maxLen); +} + +size_t AsyncResponseStream::write(const uint8_t* data, size_t len) { + if (_started()) + return 0; + + if (len > _content->room()) { + size_t needed = len - _content->room(); + _content->resizeAdd(needed); + } + size_t written = _content->write((const char*)data, len); + _contentLength += written; + return written; +} + +size_t AsyncResponseStream::write(uint8_t data) { + return write(&data, 1); +} diff --git a/lib/ESP Async WebServer/src/WebServer.cpp b/lib/ESP Async WebServer/src/WebServer.cpp new file mode 100644 index 0000000..9d78e02 --- /dev/null +++ b/lib/ESP Async WebServer/src/WebServer.cpp @@ -0,0 +1,217 @@ +/* + Asynchronous WebServer library for Espressif MCUs + + Copyright (c) 2016 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "ESPAsyncWebServer.h" +#include "WebHandlerImpl.h" + +bool ON_STA_FILTER(AsyncWebServerRequest* request) { + return WiFi.localIP() == request->client()->localIP(); +} + +bool ON_AP_FILTER(AsyncWebServerRequest* request) { + return WiFi.localIP() != request->client()->localIP(); +} + +#ifndef HAVE_FS_FILE_OPEN_MODE +const char* fs::FileOpenMode::read = "r"; +const char* fs::FileOpenMode::write = "w"; +const char* fs::FileOpenMode::append = "a"; +#endif + +AsyncWebServer::AsyncWebServer(uint16_t port) + : _server(port) { + _catchAllHandler = new AsyncCallbackWebHandler(); + if (_catchAllHandler == NULL) + return; + _server.onClient([](void* s, AsyncClient* c) { + if (c == NULL) + return; + c->setRxTimeout(3); + AsyncWebServerRequest* r = new AsyncWebServerRequest((AsyncWebServer*)s, c); + if (r == NULL) { + c->close(true); + c->free(); + delete c; + } + }, + this); +} + +AsyncWebServer::~AsyncWebServer() { + reset(); + end(); + if (_catchAllHandler) + delete _catchAllHandler; +} + +AsyncWebRewrite& AsyncWebServer::addRewrite(std::shared_ptr rewrite) { + _rewrites.emplace_back(rewrite); + return *_rewrites.back().get(); +} + +AsyncWebRewrite& AsyncWebServer::addRewrite(AsyncWebRewrite* rewrite) { + _rewrites.emplace_back(rewrite); + return *_rewrites.back().get(); +} + +bool AsyncWebServer::removeRewrite(AsyncWebRewrite* rewrite) { + return removeRewrite(rewrite->from().c_str(), rewrite->toUrl().c_str()); +} + +bool AsyncWebServer::removeRewrite(const char* from, const char* to) { + for (auto r = _rewrites.begin(); r != _rewrites.end(); ++r) { + if (r->get()->from() == from && r->get()->toUrl() == to) { + _rewrites.erase(r); + return true; + } + } + return false; +} + +AsyncWebRewrite& AsyncWebServer::rewrite(const char* from, const char* to) { + _rewrites.emplace_back(std::make_shared(from, to)); + return *_rewrites.back().get(); +} + +AsyncWebHandler& AsyncWebServer::addHandler(AsyncWebHandler* handler) { + _handlers.emplace_back(handler); + return *(_handlers.back().get()); +} + +bool AsyncWebServer::removeHandler(AsyncWebHandler* handler) { + for (auto i = _handlers.begin(); i != _handlers.end(); ++i) { + if (i->get() == handler) { + _handlers.erase(i); + return true; + } + } + return false; +} + +void AsyncWebServer::begin() { + _server.setNoDelay(true); + _server.begin(); +} + +void AsyncWebServer::end() { + _server.end(); +} + +#if ASYNC_TCP_SSL_ENABLED +void AsyncWebServer::onSslFileRequest(AcSSlFileHandler cb, void* arg) { + _server.onSslFileRequest(cb, arg); +} + +void AsyncWebServer::beginSecure(const char* cert, const char* key, const char* password) { + _server.beginSecure(cert, key, password); +} +#endif + +void AsyncWebServer::_handleDisconnect(AsyncWebServerRequest* request) { + delete request; +} + +void AsyncWebServer::_rewriteRequest(AsyncWebServerRequest* request) { + for (const auto& r : _rewrites) { + if (r->match(request)) { + request->_url = r->toUrl(); + request->_addGetParams(r->params()); + } + } +} + +void AsyncWebServer::_attachHandler(AsyncWebServerRequest* request) { + for (auto& h : _handlers) { + if (h->filter(request) && h->canHandle(request)) { + request->setHandler(h.get()); + return; + } + } + + request->addInterestingHeader(F("ANY")); + request->setHandler(_catchAllHandler); +} + +AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody) { + AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler(); + handler->setUri(uri); + handler->setMethod(method); + handler->onRequest(onRequest); + handler->onUpload(onUpload); + handler->onBody(onBody); + addHandler(handler); + return *handler; +} + +AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload) { + AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler(); + handler->setUri(uri); + handler->setMethod(method); + handler->onRequest(onRequest); + handler->onUpload(onUpload); + addHandler(handler); + return *handler; +} + +AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest) { + AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler(); + handler->setUri(uri); + handler->setMethod(method); + handler->onRequest(onRequest); + addHandler(handler); + return *handler; +} + +AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, ArRequestHandlerFunction onRequest) { + AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler(); + handler->setUri(uri); + handler->onRequest(onRequest); + addHandler(handler); + return *handler; +} + +AsyncStaticWebHandler& AsyncWebServer::serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control) { + AsyncStaticWebHandler* handler = new AsyncStaticWebHandler(uri, fs, path, cache_control); + addHandler(handler); + return *handler; +} + +void AsyncWebServer::onNotFound(ArRequestHandlerFunction fn) { + _catchAllHandler->onRequest(fn); +} + +void AsyncWebServer::onFileUpload(ArUploadHandlerFunction fn) { + _catchAllHandler->onUpload(fn); +} + +void AsyncWebServer::onRequestBody(ArBodyHandlerFunction fn) { + _catchAllHandler->onBody(fn); +} + +void AsyncWebServer::reset() { + _rewrites.clear(); + _handlers.clear(); + + if (_catchAllHandler != NULL) { + _catchAllHandler->onRequest(NULL); + _catchAllHandler->onUpload(NULL); + _catchAllHandler->onBody(NULL); + } +} diff --git a/lib/ESP Async WebServer/src/port/SHA1Builder.cpp b/lib/ESP Async WebServer/src/port/SHA1Builder.cpp new file mode 100644 index 0000000..901fb80 --- /dev/null +++ b/lib/ESP Async WebServer/src/port/SHA1Builder.cpp @@ -0,0 +1,284 @@ +/* + * FIPS-180-1 compliant SHA-1 implementation + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * Modified for esp32 by Lucas Saavedra Vaz on 11 Jan 2024 + */ + +#include +#if ESP_IDF_VERSION_MAJOR < 5 + +#include "SHA1Builder.h" + +// 32-bit integer manipulation macros (big endian) + +#ifndef GET_UINT32_BE +#define GET_UINT32_BE(n, b, i) \ + { (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]); } +#endif + +#ifndef PUT_UINT32_BE +#define PUT_UINT32_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 24); \ + (b)[(i) + 1] = (uint8_t)((n) >> 16); \ + (b)[(i) + 2] = (uint8_t)((n) >> 8); \ + (b)[(i) + 3] = (uint8_t)((n)); \ + } +#endif + +// Constants + +static const uint8_t sha1_padding[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + +// Private methods + +void SHA1Builder::process(const uint8_t *data) { + uint32_t temp, W[16], A, B, C, D, E; + + GET_UINT32_BE(W[0], data, 0); + GET_UINT32_BE(W[1], data, 4); + GET_UINT32_BE(W[2], data, 8); + GET_UINT32_BE(W[3], data, 12); + GET_UINT32_BE(W[4], data, 16); + GET_UINT32_BE(W[5], data, 20); + GET_UINT32_BE(W[6], data, 24); + GET_UINT32_BE(W[7], data, 28); + GET_UINT32_BE(W[8], data, 32); + GET_UINT32_BE(W[9], data, 36); + GET_UINT32_BE(W[10], data, 40); + GET_UINT32_BE(W[11], data, 44); + GET_UINT32_BE(W[12], data, 48); + GET_UINT32_BE(W[13], data, 52); + GET_UINT32_BE(W[14], data, 56); + GET_UINT32_BE(W[15], data, 60); + +#define sha1_S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) + +#define sha1_R(t) (temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ W[(t - 14) & 0x0F] ^ W[t & 0x0F], (W[t & 0x0F] = sha1_S(temp, 1))) + +#define sha1_P(a, b, c, d, e, x) \ + { \ + e += sha1_S(a, 5) + sha1_F(b, c, d) + sha1_K + x; \ + b = sha1_S(b, 30); \ + } + + A = state[0]; + B = state[1]; + C = state[2]; + D = state[3]; + E = state[4]; + +#define sha1_F(x, y, z) (z ^ (x & (y ^ z))) +#define sha1_K 0x5A827999 + + sha1_P(A, B, C, D, E, W[0]); + sha1_P(E, A, B, C, D, W[1]); + sha1_P(D, E, A, B, C, W[2]); + sha1_P(C, D, E, A, B, W[3]); + sha1_P(B, C, D, E, A, W[4]); + sha1_P(A, B, C, D, E, W[5]); + sha1_P(E, A, B, C, D, W[6]); + sha1_P(D, E, A, B, C, W[7]); + sha1_P(C, D, E, A, B, W[8]); + sha1_P(B, C, D, E, A, W[9]); + sha1_P(A, B, C, D, E, W[10]); + sha1_P(E, A, B, C, D, W[11]); + sha1_P(D, E, A, B, C, W[12]); + sha1_P(C, D, E, A, B, W[13]); + sha1_P(B, C, D, E, A, W[14]); + sha1_P(A, B, C, D, E, W[15]); + sha1_P(E, A, B, C, D, sha1_R(16)); + sha1_P(D, E, A, B, C, sha1_R(17)); + sha1_P(C, D, E, A, B, sha1_R(18)); + sha1_P(B, C, D, E, A, sha1_R(19)); + +#undef sha1_K +#undef sha1_F + +#define sha1_F(x, y, z) (x ^ y ^ z) +#define sha1_K 0x6ED9EBA1 + + sha1_P(A, B, C, D, E, sha1_R(20)); + sha1_P(E, A, B, C, D, sha1_R(21)); + sha1_P(D, E, A, B, C, sha1_R(22)); + sha1_P(C, D, E, A, B, sha1_R(23)); + sha1_P(B, C, D, E, A, sha1_R(24)); + sha1_P(A, B, C, D, E, sha1_R(25)); + sha1_P(E, A, B, C, D, sha1_R(26)); + sha1_P(D, E, A, B, C, sha1_R(27)); + sha1_P(C, D, E, A, B, sha1_R(28)); + sha1_P(B, C, D, E, A, sha1_R(29)); + sha1_P(A, B, C, D, E, sha1_R(30)); + sha1_P(E, A, B, C, D, sha1_R(31)); + sha1_P(D, E, A, B, C, sha1_R(32)); + sha1_P(C, D, E, A, B, sha1_R(33)); + sha1_P(B, C, D, E, A, sha1_R(34)); + sha1_P(A, B, C, D, E, sha1_R(35)); + sha1_P(E, A, B, C, D, sha1_R(36)); + sha1_P(D, E, A, B, C, sha1_R(37)); + sha1_P(C, D, E, A, B, sha1_R(38)); + sha1_P(B, C, D, E, A, sha1_R(39)); + +#undef sha1_K +#undef sha1_F + +#define sha1_F(x, y, z) ((x & y) | (z & (x | y))) +#define sha1_K 0x8F1BBCDC + + sha1_P(A, B, C, D, E, sha1_R(40)); + sha1_P(E, A, B, C, D, sha1_R(41)); + sha1_P(D, E, A, B, C, sha1_R(42)); + sha1_P(C, D, E, A, B, sha1_R(43)); + sha1_P(B, C, D, E, A, sha1_R(44)); + sha1_P(A, B, C, D, E, sha1_R(45)); + sha1_P(E, A, B, C, D, sha1_R(46)); + sha1_P(D, E, A, B, C, sha1_R(47)); + sha1_P(C, D, E, A, B, sha1_R(48)); + sha1_P(B, C, D, E, A, sha1_R(49)); + sha1_P(A, B, C, D, E, sha1_R(50)); + sha1_P(E, A, B, C, D, sha1_R(51)); + sha1_P(D, E, A, B, C, sha1_R(52)); + sha1_P(C, D, E, A, B, sha1_R(53)); + sha1_P(B, C, D, E, A, sha1_R(54)); + sha1_P(A, B, C, D, E, sha1_R(55)); + sha1_P(E, A, B, C, D, sha1_R(56)); + sha1_P(D, E, A, B, C, sha1_R(57)); + sha1_P(C, D, E, A, B, sha1_R(58)); + sha1_P(B, C, D, E, A, sha1_R(59)); + +#undef sha1_K +#undef sha1_F + +#define sha1_F(x, y, z) (x ^ y ^ z) +#define sha1_K 0xCA62C1D6 + + sha1_P(A, B, C, D, E, sha1_R(60)); + sha1_P(E, A, B, C, D, sha1_R(61)); + sha1_P(D, E, A, B, C, sha1_R(62)); + sha1_P(C, D, E, A, B, sha1_R(63)); + sha1_P(B, C, D, E, A, sha1_R(64)); + sha1_P(A, B, C, D, E, sha1_R(65)); + sha1_P(E, A, B, C, D, sha1_R(66)); + sha1_P(D, E, A, B, C, sha1_R(67)); + sha1_P(C, D, E, A, B, sha1_R(68)); + sha1_P(B, C, D, E, A, sha1_R(69)); + sha1_P(A, B, C, D, E, sha1_R(70)); + sha1_P(E, A, B, C, D, sha1_R(71)); + sha1_P(D, E, A, B, C, sha1_R(72)); + sha1_P(C, D, E, A, B, sha1_R(73)); + sha1_P(B, C, D, E, A, sha1_R(74)); + sha1_P(A, B, C, D, E, sha1_R(75)); + sha1_P(E, A, B, C, D, sha1_R(76)); + sha1_P(D, E, A, B, C, sha1_R(77)); + sha1_P(C, D, E, A, B, sha1_R(78)); + sha1_P(B, C, D, E, A, sha1_R(79)); + +#undef sha1_K +#undef sha1_F + + state[0] += A; + state[1] += B; + state[2] += C; + state[3] += D; + state[4] += E; +} + +// Public methods + +void SHA1Builder::begin(void) { + total[0] = 0; + total[1] = 0; + + state[0] = 0x67452301; + state[1] = 0xEFCDAB89; + state[2] = 0x98BADCFE; + state[3] = 0x10325476; + state[4] = 0xC3D2E1F0; + + memset(buffer, 0x00, sizeof(buffer)); + memset(hash, 0x00, sizeof(hash)); +} + +void SHA1Builder::add(const uint8_t *data, size_t len) { + size_t fill; + uint32_t left; + + if (len == 0) { + return; + } + + left = total[0] & 0x3F; + fill = 64 - left; + + total[0] += (uint32_t)len; + total[0] &= 0xFFFFFFFF; + + if (total[0] < (uint32_t)len) { + total[1]++; + } + + if (left && len >= fill) { + memcpy((void *)(buffer + left), data, fill); + process(buffer); + data += fill; + len -= fill; + left = 0; + } + + while (len >= 64) { + process(data); + data += 64; + len -= 64; + } + + if (len > 0) { + memcpy((void *)(buffer + left), data, len); + } +} + +void SHA1Builder::calculate(void) { + uint32_t last, padn; + uint32_t high, low; + uint8_t msglen[8]; + + high = (total[0] >> 29) | (total[1] << 3); + low = (total[0] << 3); + + PUT_UINT32_BE(high, msglen, 0); + PUT_UINT32_BE(low, msglen, 4); + + last = total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); + + add((uint8_t *)sha1_padding, padn); + add(msglen, 8); + + PUT_UINT32_BE(state[0], hash, 0); + PUT_UINT32_BE(state[1], hash, 4); + PUT_UINT32_BE(state[2], hash, 8); + PUT_UINT32_BE(state[3], hash, 12); + PUT_UINT32_BE(state[4], hash, 16); +} + +void SHA1Builder::getBytes(uint8_t *output) { + memcpy(output, hash, SHA1_HASH_SIZE); +} + +#endif // ESP_IDF_VERSION_MAJOR < 5 diff --git a/lib/ESP Async WebServer/src/port/SHA1Builder.h b/lib/ESP Async WebServer/src/port/SHA1Builder.h new file mode 100644 index 0000000..da9a77a --- /dev/null +++ b/lib/ESP Async WebServer/src/port/SHA1Builder.h @@ -0,0 +1,39 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SHA1Builder_h +#define SHA1Builder_h + +#include +#include + +#define SHA1_HASH_SIZE 20 + +class SHA1Builder { + private: + uint32_t total[2]; /* number of bytes processed */ + uint32_t state[5]; /* intermediate digest state */ + unsigned char buffer[64]; /* data block being processed */ + uint8_t hash[SHA1_HASH_SIZE]; /* SHA-1 result */ + + void process(const uint8_t* data); + + public: + void begin(); + void add(const uint8_t* data, size_t len); + void calculate(); + void getBytes(uint8_t* output); +}; + +#endif // SHA1Builder_h diff --git a/lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-core-esp8266.sh b/lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-core-esp8266.sh deleted file mode 100644 index 048cd02..0000000 --- a/lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-core-esp8266.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash - -echo "Installing ESP8266 Arduino Core ..." -script_init_path="$PWD" -mkdir -p "$ARDUINO_USR_PATH/hardware/esp8266com" -cd "$ARDUINO_USR_PATH/hardware/esp8266com" - -echo "Installing Python Serial ..." -pip install pyserial > /dev/null - -if [ "$OS_IS_WINDOWS" == "1" ]; then - echo "Installing Python Requests ..." - pip install requests > /dev/null -fi - -echo "Cloning Core Repository ..." -git clone https://github.com/esp8266/Arduino.git esp8266 > /dev/null 2>&1 - -echo "Updating submodules ..." -cd esp8266 -git submodule update --init --recursive > /dev/null 2>&1 - -echo "Installing Platform Tools ..." -cd tools -python get.py > /dev/null -cd $script_init_path - -echo "ESP8266 Arduino has been installed in '$ARDUINO_USR_PATH/hardware/esp8266com'" -echo "" diff --git a/lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-ide.sh b/lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-ide.sh deleted file mode 100644 index 7e268b1..0000000 --- a/lib/ESPAsyncTCP-esphome/.github/scripts/install-arduino-ide.sh +++ /dev/null @@ -1,220 +0,0 @@ -#!/bin/bash - -#OSTYPE: 'linux-gnu', ARCH: 'x86_64' => linux64 -#OSTYPE: 'msys', ARCH: 'x86_64' => win32 -#OSTYPE: 'darwin18', ARCH: 'i386' => macos - -OSBITS=`arch` -if [[ "$OSTYPE" == "linux"* ]]; then - export OS_IS_LINUX="1" - ARCHIVE_FORMAT="tar.xz" - if [[ "$OSBITS" == "i686" ]]; then - OS_NAME="linux32" - elif [[ "$OSBITS" == "x86_64" ]]; then - OS_NAME="linux64" - elif [[ "$OSBITS" == "armv7l" || "$OSBITS" == "aarch64" ]]; then - OS_NAME="linuxarm" - else - OS_NAME="$OSTYPE-$OSBITS" - echo "Unknown OS '$OS_NAME'" - exit 1 - fi -elif [[ "$OSTYPE" == "darwin"* ]]; then - export OS_IS_MACOS="1" - ARCHIVE_FORMAT="zip" - OS_NAME="macosx" -elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then - export OS_IS_WINDOWS="1" - ARCHIVE_FORMAT="zip" - OS_NAME="windows" -else - OS_NAME="$OSTYPE-$OSBITS" - echo "Unknown OS '$OS_NAME'" - exit 1 -fi -export OS_NAME - -ARDUINO_BUILD_DIR="$HOME/.arduino/build.tmp" -ARDUINO_CACHE_DIR="$HOME/.arduino/cache.tmp" - -if [ "$OS_IS_MACOS" == "1" ]; then - export ARDUINO_IDE_PATH="/Applications/Arduino.app/Contents/Java" - export ARDUINO_USR_PATH="$HOME/Documents/Arduino" -elif [ "$OS_IS_WINDOWS" == "1" ]; then - export ARDUINO_IDE_PATH="$HOME/arduino_ide" - export ARDUINO_USR_PATH="$HOME/Documents/Arduino" -else - export ARDUINO_IDE_PATH="$HOME/arduino_ide" - export ARDUINO_USR_PATH="$HOME/Arduino" -fi - -if [ ! -d "$ARDUINO_IDE_PATH" ]; then - echo "Installing Arduino IDE on $OS_NAME ..." - echo "Downloading 'arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT' to 'arduino.$ARCHIVE_FORMAT' ..." - if [ "$OS_IS_LINUX" == "1" ]; then - wget -O "arduino.$ARCHIVE_FORMAT" "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1 - echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..." - tar xf "arduino.$ARCHIVE_FORMAT" > /dev/null - mv arduino-nightly "$ARDUINO_IDE_PATH" - else - curl -o "arduino.$ARCHIVE_FORMAT" -L "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1 - echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..." - unzip "arduino.$ARCHIVE_FORMAT" > /dev/null - if [ "$OS_IS_MACOS" == "1" ]; then - mv "Arduino.app" "/Applications/Arduino.app" - else - mv arduino-nightly "$ARDUINO_IDE_PATH" - fi - fi - rm -rf "arduino.$ARCHIVE_FORMAT" - - mkdir -p "$ARDUINO_USR_PATH/libraries" - mkdir -p "$ARDUINO_USR_PATH/hardware" - - echo "Arduino IDE Installed in '$ARDUINO_IDE_PATH'" - echo "" -fi - -function build_sketch(){ # build_sketch [extra-options] - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_sketch [extra-options]" - return 1 - fi - - local fqbn="$1" - local sketch="$2" - local xtra_opts="$3" - local win_opts="" - if [ "$OS_IS_WINDOWS" == "1" ]; then - local ctags_version=`ls "$ARDUINO_IDE_PATH/tools-builder/ctags/"` - local preprocessor_version=`ls "$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/"` - win_opts="-prefs=runtime.tools.ctags.path=$ARDUINO_IDE_PATH/tools-builder/ctags/$ctags_version -prefs=runtime.tools.arduino-preprocessor.path=$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/$preprocessor_version" - fi - - echo "" - echo "Compiling '"$(basename "$sketch")"' ..." - mkdir -p "$ARDUINO_BUILD_DIR" - mkdir -p "$ARDUINO_CACHE_DIR" - $ARDUINO_IDE_PATH/arduino-builder -compile -logger=human -core-api-version=10810 \ - -fqbn=$fqbn \ - -warnings="all" \ - -tools "$ARDUINO_IDE_PATH/tools-builder" \ - -tools "$ARDUINO_IDE_PATH/tools" \ - -built-in-libraries "$ARDUINO_IDE_PATH/libraries" \ - -hardware "$ARDUINO_IDE_PATH/hardware" \ - -hardware "$ARDUINO_USR_PATH/hardware" \ - -libraries "$ARDUINO_USR_PATH/libraries" \ - -build-cache "$ARDUINO_CACHE_DIR" \ - -build-path "$ARDUINO_BUILD_DIR" \ - $win_opts $xtra_opts "$sketch" -} - -function count_sketches() # count_sketches -{ - local examples="$1" - rm -rf sketches.txt - if [ ! -d "$examples" ]; then - touch sketches.txt - return 0 - fi - local sketches=$(find $examples -name *.ino) - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then - continue - fi; - if [[ -f "$sketchdir/.test.skip" ]]; then - continue - fi - echo $sketch >> sketches.txt - sketchnum=$(($sketchnum + 1)) - done - return $sketchnum -} - -function build_sketches() # build_sketches [extra-options] -{ - local fqbn=$1 - local examples=$2 - local chunk_idex=$3 - local chunks_num=$4 - local xtra_opts=$5 - - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_sketches [ ] [extra-options]" - return 1 - fi - - if [ "$#" -lt 4 ]; then - chunk_idex="0" - chunks_num="1" - xtra_opts=$3 - fi - - if [ "$chunks_num" -le 0 ]; then - echo "ERROR: Chunks count must be positive number" - return 1 - fi - if [ "$chunk_idex" -ge "$chunks_num" ]; then - echo "ERROR: Chunk index must be less than chunks count" - return 1 - fi - - set +e - count_sketches "$examples" - local sketchcount=$? - set -e - local sketches=$(cat sketches.txt) - rm -rf sketches.txt - - local chunk_size=$(( $sketchcount / $chunks_num )) - local all_chunks=$(( $chunks_num * $chunk_size )) - if [ "$all_chunks" -lt "$sketchcount" ]; then - chunk_size=$(( $chunk_size + 1 )) - fi - - local start_index=$(( $chunk_idex * $chunk_size )) - if [ "$sketchcount" -le "$start_index" ]; then - echo "Skipping job" - return 0 - fi - - local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) - if [ "$end_index" -gt "$sketchcount" ]; then - end_index=$sketchcount - fi - - local start_num=$(( $start_index + 1 )) - echo "Found $sketchcount Sketches"; - echo "Chunk Count : $chunks_num" - echo "Chunk Size : $chunk_size" - echo "Start Sketch: $start_num" - echo "End Sketch : $end_index" - - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [ "${sketchdirname}.ino" != "$sketchname" ] \ - || [ -f "$sketchdir/.test.skip" ]; then - continue - fi - sketchnum=$(($sketchnum + 1)) - if [ "$sketchnum" -le "$start_index" ] \ - || [ "$sketchnum" -gt "$end_index" ]; then - continue - fi - build_sketch "$fqbn" "$sketch" "$xtra_opts" - local result=$? - if [ $result -ne 0 ]; then - return $result - fi - done - return 0 -} diff --git a/lib/ESPAsyncTCP-esphome/.github/scripts/install-platformio.sh b/lib/ESPAsyncTCP-esphome/.github/scripts/install-platformio.sh deleted file mode 100644 index 61c94fe..0000000 --- a/lib/ESPAsyncTCP-esphome/.github/scripts/install-platformio.sh +++ /dev/null @@ -1,133 +0,0 @@ -#!/bin/bash - -echo "Installing Python Wheel ..." -pip install wheel > /dev/null 2>&1 - -echo "Installing PlatformIO ..." -pip install -U platformio > /dev/null 2>&1 - -echo "PlatformIO has been installed" -echo "" - - -function build_pio_sketch(){ # build_pio_sketch - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_pio_sketch " - return 1 - fi - - local board="$1" - local sketch="$2" - local sketch_dir=$(dirname "$sketch") - echo "" - echo "Compiling '"$(basename "$sketch")"' ..." - python -m platformio ci -l '.' --board "$board" "$sketch_dir" --project-option="board_build.partitions = huge_app.csv" -} - -function count_sketches() # count_sketches -{ - local examples="$1" - rm -rf sketches.txt - if [ ! -d "$examples" ]; then - touch sketches.txt - return 0 - fi - local sketches=$(find $examples -name *.ino) - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then - continue - fi; - if [[ -f "$sketchdir/.test.skip" ]]; then - continue - fi - echo $sketch >> sketches.txt - sketchnum=$(($sketchnum + 1)) - done - return $sketchnum -} - -function build_pio_sketches() # build_pio_sketches -{ - if [ "$#" -lt 2 ]; then - echo "ERROR: Illegal number of parameters" - echo "USAGE: build_pio_sketches [ ]" - return 1 - fi - - local board=$1 - local examples=$2 - local chunk_idex=$3 - local chunks_num=$4 - - if [ "$#" -lt 4 ]; then - chunk_idex="0" - chunks_num="1" - fi - - if [ "$chunks_num" -le 0 ]; then - echo "ERROR: Chunks count must be positive number" - return 1 - fi - if [ "$chunk_idex" -ge "$chunks_num" ]; then - echo "ERROR: Chunk index must be less than chunks count" - return 1 - fi - - set +e - count_sketches "$examples" - local sketchcount=$? - set -e - local sketches=$(cat sketches.txt) - rm -rf sketches.txt - - local chunk_size=$(( $sketchcount / $chunks_num )) - local all_chunks=$(( $chunks_num * $chunk_size )) - if [ "$all_chunks" -lt "$sketchcount" ]; then - chunk_size=$(( $chunk_size + 1 )) - fi - - local start_index=$(( $chunk_idex * $chunk_size )) - if [ "$sketchcount" -le "$start_index" ]; then - echo "Skipping job" - return 0 - fi - - local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) - if [ "$end_index" -gt "$sketchcount" ]; then - end_index=$sketchcount - fi - - local start_num=$(( $start_index + 1 )) - echo "Found $sketchcount Sketches"; - echo "Chunk Count : $chunks_num" - echo "Chunk Size : $chunk_size" - echo "Start Sketch: $start_num" - echo "End Sketch : $end_index" - - local sketchnum=0 - for sketch in $sketches; do - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [ "${sketchdirname}.ino" != "$sketchname" ] \ - || [ -f "$sketchdir/.test.skip" ]; then - continue - fi - sketchnum=$(($sketchnum + 1)) - if [ "$sketchnum" -le "$start_index" ] \ - || [ "$sketchnum" -gt "$end_index" ]; then - continue - fi - build_pio_sketch "$board" "$sketch" - local result=$? - if [ $result -ne 0 ]; then - return $result - fi - done - return 0 -} diff --git a/lib/ESPAsyncTCP-esphome/.github/scripts/on-push.sh b/lib/ESPAsyncTCP-esphome/.github/scripts/on-push.sh deleted file mode 100644 index 7ae8c43..0000000 --- a/lib/ESPAsyncTCP-esphome/.github/scripts/on-push.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/bin/bash - -set -e - -if [ ! -z "$TRAVIS_BUILD_DIR" ]; then - export GITHUB_WORKSPACE="$TRAVIS_BUILD_DIR" - export GITHUB_REPOSITORY="$TRAVIS_REPO_SLUG" -elif [ -z "$GITHUB_WORKSPACE" ]; then - export GITHUB_WORKSPACE="$PWD" - export GITHUB_REPOSITORY="me-no-dev/ESPAsyncTCP" -fi - -CHUNK_INDEX=$1 -CHUNKS_CNT=$2 -BUILD_PIO=0 -if [ "$#" -lt 2 ] || [ "$CHUNKS_CNT" -le 0 ]; then - CHUNK_INDEX=0 - CHUNKS_CNT=1 -elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ]; then - CHUNK_INDEX=$CHUNKS_CNT -elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then - BUILD_PIO=1 -fi - -if [ "$BUILD_PIO" -eq 0 ]; then - # ArduinoIDE Test - source ./.github/scripts/install-arduino-ide.sh - source ./.github/scripts/install-arduino-core-esp8266.sh - - echo "Installing ESPAsyncTCP ..." - cp -rf "$GITHUB_WORKSPACE" "$ARDUINO_USR_PATH/libraries/ESPAsyncTCP" - - FQBN="esp8266com:esp8266:generic:eesz=4M1M,ip=lm2f" - build_sketches "$FQBN" "$GITHUB_WORKSPACE/examples" - if [ ! "$OS_IS_WINDOWS" == "1" ]; then - echo "Installing ESPAsyncWebServer ..." - git clone https://github.com/me-no-dev/ESPAsyncWebServer "$ARDUINO_USR_PATH/libraries/ESPAsyncWebServer" > /dev/null 2>&1 - - echo "Installing ArduinoJson ..." - git clone https://github.com/bblanchon/ArduinoJson "$ARDUINO_USR_PATH/libraries/ArduinoJson" > /dev/null 2>&1 - - build_sketches "$FQBN" "$ARDUINO_USR_PATH/libraries/ESPAsyncWebServer/examples" - fi -else - # PlatformIO Test - source ./.github/scripts/install-platformio.sh - - echo "Installing ESPAsyncTCP ..." - python -m platformio lib --storage-dir "$GITHUB_WORKSPACE" install - - BOARD="esp12e" - build_pio_sketches "$BOARD" "$GITHUB_WORKSPACE/examples" - - if [[ "$OSTYPE" != "cygwin" ]] && [[ "$OSTYPE" != "msys" ]] && [[ "$OSTYPE" != "win32" ]]; then - echo "Installing ESPAsyncWebServer ..." - python -m platformio lib -g install https://github.com/me-no-dev/ESPAsyncWebServer.git > /dev/null 2>&1 - git clone https://github.com/me-no-dev/ESPAsyncWebServer "$HOME/ESPAsyncWebServer" > /dev/null 2>&1 - - echo "Installing ArduinoJson ..." - python -m platformio lib -g install https://github.com/bblanchon/ArduinoJson.git > /dev/null 2>&1 - - build_pio_sketches "$BOARD" "$HOME/ESPAsyncWebServer/examples" - fi -fi diff --git a/lib/ESPAsyncTCP-esphome/.github/stale.yml b/lib/ESPAsyncTCP-esphome/.github/stale.yml deleted file mode 100644 index ce7a8e3..0000000 --- a/lib/ESPAsyncTCP-esphome/.github/stale.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Configuration for probot-stale - https://github.com/probot/stale - -daysUntilStale: 60 -daysUntilClose: 14 -limitPerRun: 30 -staleLabel: stale -exemptLabels: - - pinned - - security - - "to be implemented" - - "for reference" - - "move to PR" - - "enhancement" - -only: issues -onlyLabels: [] -exemptProjects: false -exemptMilestones: false -exemptAssignees: false - -markComment: > - [STALE_SET] This issue has been automatically marked as stale because it has not had - recent activity. It will be closed in 14 days if no further activity occurs. Thank you - for your contributions. - -unmarkComment: > - [STALE_CLR] This issue has been removed from the stale queue. Please ensure activity to keep it openin the future. - -closeComment: > - [STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions. - diff --git a/lib/ESPAsyncTCP-esphome/.github/workflows/push.yml b/lib/ESPAsyncTCP-esphome/.github/workflows/push.yml deleted file mode 100644 index d3e7011..0000000 --- a/lib/ESPAsyncTCP-esphome/.github/workflows/push.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: ESP Async TCP CI - -on: - push: - branches: - - master - - release/* - pull_request: - -jobs: - - build-pio: - name: PlatformIO on ${{ matrix.os }} - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - steps: - - uses: actions/checkout@v3 - - uses: actions/cache@v3 - with: - path: | - ~/.cache/pip - ~/.platformio/.cache - key: ${{ runner.os }}-pio - - uses: actions/setup-python@v4 - with: - python-version: '3.11' - - name: Install PlatformIO Core - run: pip install --upgrade platformio - - name: Build Tests - run: bash ./.github/scripts/on-push.sh 1 1 diff --git a/lib/ESPAsyncTCP-esphome/.gitignore b/lib/ESPAsyncTCP-esphome/.gitignore deleted file mode 100644 index 9bea433..0000000 --- a/lib/ESPAsyncTCP-esphome/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ - -.DS_Store diff --git a/lib/ESPAsyncTCP-esphome/.piopm b/lib/ESPAsyncTCP-esphome/.piopm deleted file mode 100644 index 35a6b62..0000000 --- a/lib/ESPAsyncTCP-esphome/.piopm +++ /dev/null @@ -1 +0,0 @@ -{"type": "library", "name": "ESPAsyncTCP-esphome", "version": "2.0.0", "spec": {"owner": "esphome", "id": 15476, "name": "ESPAsyncTCP-esphome", "requirements": null, "uri": null}} \ No newline at end of file diff --git a/lib/ESPAsyncTCP-esphome/LICENSE.txt b/lib/ESPAsyncTCP-esphome/LICENSE.txt deleted file mode 100644 index 65c5ca8..0000000 --- a/lib/ESPAsyncTCP-esphome/LICENSE.txt +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/lib/ESPAsyncTCP-esphome/README.md b/lib/ESPAsyncTCP-esphome/README.md deleted file mode 100644 index aac448a..0000000 --- a/lib/ESPAsyncTCP-esphome/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# ESPAsyncTCP - -A fork of the [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) library by [@me-no-dev](https://github.com/me-no-dev) for [ESPHome](https://esphome.io). - -### Async TCP Library for ESP8266 Arduino - -For ESP32 look [HERE](https://github.com/me-no-dev/AsyncTCP) - -[![Join the chat at https://gitter.im/me-no-dev/ESPAsyncWebServer](https://badges.gitter.im/me-no-dev/ESPAsyncWebServer.svg)](https://gitter.im/me-no-dev/ESPAsyncWebServer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -This is a fully asynchronous TCP library, aimed at enabling trouble-free, multi-connection network environment for Espressif's ESP8266 MCUs. - -This library is the base for [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) - -## AsyncClient and AsyncServer -The base classes on which everything else is built. They expose all possible scenarios, but are really raw and require more skills to use. - -## AsyncPrinter -This class can be used to send data like any other ```Print``` interface (```Serial``` for example). -The object then can be used outside of the Async callbacks (the loop) and receive asynchronously data using ```onData```. The object can be checked if the underlying ```AsyncClient```is connected, or hook to the ```onDisconnect``` callback. - -## AsyncTCPbuffer -This class is really similar to the ```AsyncPrinter```, but it differs in the fact that it can buffer some of the incoming data. - -## SyncClient -It is exactly what it sounds like. This is a standard, blocking TCP Client, similar to the one included in ```ESP8266WiFi``` - -## Libraries and projects that use AsyncTCP -- [ESP Async Web Server](https://github.com/me-no-dev/ESPAsyncWebServer) -- [Async MQTT client](https://github.com/marvinroger/async-mqtt-client) -- [arduinoWebSockets](https://github.com/Links2004/arduinoWebSockets) -- [ESP8266 Smart Home](https://github.com/baruch/esp8266_smart_home) -- [KBox Firmware](https://github.com/sarfata/kbox-firmware) diff --git a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/Client.ino b/lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/Client.ino deleted file mode 100644 index b30d791..0000000 --- a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/Client.ino +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include - -extern "C" { -#include -#include -} - -#include "config.h" - -static os_timer_t intervalTimer; - -static void replyToServer(void* arg) { - AsyncClient* client = reinterpret_cast(arg); - - // send reply - if (client->space() > 32 && client->canSend()) { - char message[32]; - sprintf(message, "this is from %s", WiFi.localIP().toString().c_str()); - client->add(message, strlen(message)); - client->send(); - } -} - -/* event callbacks */ -static void handleData(void* arg, AsyncClient* client, void *data, size_t len) { - Serial.printf("\n data received from %s \n", client->remoteIP().toString().c_str()); - Serial.write((uint8_t*)data, len); - - os_timer_arm(&intervalTimer, 2000, true); // schedule for reply to server at next 2s -} - -void onConnect(void* arg, AsyncClient* client) { - Serial.printf("\n client has been connected to %s on port %d \n", SERVER_HOST_NAME, TCP_PORT); - replyToServer(client); -} - - -void setup() { - Serial.begin(115200); - delay(20); - - // connects to access point - WiFi.mode(WIFI_STA); - WiFi.begin(SSID, PASSWORD); - while (WiFi.status() != WL_CONNECTED) { - Serial.print('.'); - delay(500); - } - - AsyncClient* client = new AsyncClient; - client->onData(&handleData, client); - client->onConnect(&onConnect, client); - client->connect(SERVER_HOST_NAME, TCP_PORT); - - os_timer_disarm(&intervalTimer); - os_timer_setfn(&intervalTimer, &replyToServer, client); -} - -void loop() { - -} diff --git a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/config.h b/lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/config.h deleted file mode 100644 index cf51e91..0000000 --- a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Client/config.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef CONFIG_H -#define CONFIG_H - -/* - * This example demonstrate how to use asynchronous client & server APIs - * in order to establish tcp socket connections in client server manner. - * server is running (on port 7050) on one ESP, acts as AP, and other clients running on - * remaining ESPs acts as STAs. after connection establishment between server and clients - * there is a simple message transfer in every 2s. clients connect to server via it's host name - * (in this case 'esp_server') with help of DNS service running on server side. - * - * Note: default MSS for ESPAsyncTCP is 536 byte and defualt ACK timeout is 5s. -*/ - -#define SSID "ESP-TEST" -#define PASSWORD "123456789" - -#define SERVER_HOST_NAME "esp_server" - -#define TCP_PORT 7050 -#define DNS_PORT 53 - -#endif // CONFIG_H diff --git a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/Server.ino b/lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/Server.ino deleted file mode 100644 index c8c9b7f..0000000 --- a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/Server.ino +++ /dev/null @@ -1,73 +0,0 @@ -#include -#include -#include -#include - -#include "config.h" - -static DNSServer DNS; - -static std::vector clients; // a list to hold all clients - - /* clients events */ -static void handleError(void* arg, AsyncClient* client, int8_t error) { - Serial.printf("\n connection error %s from client %s \n", client->errorToString(error), client->remoteIP().toString().c_str()); -} - -static void handleData(void* arg, AsyncClient* client, void *data, size_t len) { - Serial.printf("\n data received from client %s \n", client->remoteIP().toString().c_str()); - Serial.write((uint8_t*)data, len); - - // reply to client - if (client->space() > 32 && client->canSend()) { - char reply[32]; - sprintf(reply, "this is from %s", SERVER_HOST_NAME); - client->add(reply, strlen(reply)); - client->send(); - } -} - -static void handleDisconnect(void* arg, AsyncClient* client) { - Serial.printf("\n client %s disconnected \n", client->remoteIP().toString().c_str()); -} - -static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) { - Serial.printf("\n client ACK timeout ip: %s \n", client->remoteIP().toString().c_str()); -} - - -/* server events */ -static void handleNewClient(void* arg, AsyncClient* client) { - Serial.printf("\n new client has been connected to server, ip: %s", client->remoteIP().toString().c_str()); - - // add to list - clients.push_back(client); - - // register events - client->onData(&handleData, NULL); - client->onError(&handleError, NULL); - client->onDisconnect(&handleDisconnect, NULL); - client->onTimeout(&handleTimeOut, NULL); -} - -void setup() { - Serial.begin(115200); - delay(20); - - // create access point - while (!WiFi.softAP(SSID, PASSWORD, 6, false, 15)) { - delay(500); - } - - // start dns server - if (!DNS.start(DNS_PORT, SERVER_HOST_NAME, WiFi.softAPIP())) - Serial.printf("\n failed to start dns service \n"); - - AsyncServer* server = new AsyncServer(TCP_PORT); // start listening on tcp port 7050 - server->onClient(&handleNewClient, server); - server->begin(); -} - -void loop() { - DNS.processNextRequest(); -} diff --git a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/config.h b/lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/config.h deleted file mode 100644 index cf51e91..0000000 --- a/lib/ESPAsyncTCP-esphome/examples/ClientServer/Server/config.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef CONFIG_H -#define CONFIG_H - -/* - * This example demonstrate how to use asynchronous client & server APIs - * in order to establish tcp socket connections in client server manner. - * server is running (on port 7050) on one ESP, acts as AP, and other clients running on - * remaining ESPs acts as STAs. after connection establishment between server and clients - * there is a simple message transfer in every 2s. clients connect to server via it's host name - * (in this case 'esp_server') with help of DNS service running on server side. - * - * Note: default MSS for ESPAsyncTCP is 536 byte and defualt ACK timeout is 5s. -*/ - -#define SSID "ESP-TEST" -#define PASSWORD "123456789" - -#define SERVER_HOST_NAME "esp_server" - -#define TCP_PORT 7050 -#define DNS_PORT 53 - -#endif // CONFIG_H diff --git a/lib/ESPAsyncTCP-esphome/examples/SyncClient/.esp31b.skip b/lib/ESPAsyncTCP-esphome/examples/SyncClient/.esp31b.skip deleted file mode 100644 index e69de29..0000000 diff --git a/lib/ESPAsyncTCP-esphome/examples/SyncClient/SyncClient.ino b/lib/ESPAsyncTCP-esphome/examples/SyncClient/SyncClient.ino deleted file mode 100644 index 6ecc525..0000000 --- a/lib/ESPAsyncTCP-esphome/examples/SyncClient/SyncClient.ino +++ /dev/null @@ -1,54 +0,0 @@ -#ifdef ESP8266 -#include -#include -#include -#else -#include -#endif -#include "ESPAsyncTCP.h" -#include "SyncClient.h" - -const char* ssid = "**********"; -const char* password = "************"; - -void setup(){ - Serial.begin(115200); - WiFi.begin(ssid, password); - if (WiFi.waitForConnectResult() != WL_CONNECTED) { - Serial.printf("WiFi Failed!\n"); - return; - } - Serial.printf("WiFi Connected!\n"); - Serial.println(WiFi.localIP()); -#ifdef ESP8266 - ArduinoOTA.begin(); -#endif - - SyncClient client; - if(!client.connect("www.google.com", 80)){ - Serial.println("Connect Failed"); - return; - } - client.setTimeout(2); - if(client.printf("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n") > 0){ - while(client.connected() && client.available() == 0){ - delay(1); - } - while(client.available()){ - Serial.write(client.read()); - } - if(client.connected()){ - client.stop(); - } - } else { - client.stop(); - Serial.println("Send Failed"); - while(client.connected()) delay(0); - } -} - -void loop(){ -#ifdef ESP8266 - ArduinoOTA.handle(); -#endif -} diff --git a/lib/ESPAsyncTCP-esphome/library.json b/lib/ESPAsyncTCP-esphome/library.json deleted file mode 100644 index 0538519..0000000 --- a/lib/ESPAsyncTCP-esphome/library.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name":"ESPAsyncTCP-esphome", - "description":"Asynchronous TCP Library for ESP8266", - "keywords":"async,tcp", - "authors": - { - "name": "Hristo Gochkov", - "maintainer": true - }, - "repository": - { - "type": "git", - "url": "https://github.com/esphome/ESPAsyncTCP.git" - }, - "version": "2.0.0", - "license": "LGPL-3.0", - "frameworks": "arduino", - "platforms": "espressif8266", - "build": { - "libCompatMode": 2 - } -} diff --git a/lib/ESPAsyncTCP-esphome/src/AsyncPrinter.cpp b/lib/ESPAsyncTCP-esphome/src/AsyncPrinter.cpp deleted file mode 100644 index 8a63f20..0000000 --- a/lib/ESPAsyncTCP-esphome/src/AsyncPrinter.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "AsyncPrinter.h" - -AsyncPrinter::AsyncPrinter() - : _client(NULL) - , _data_cb(NULL) - , _data_arg(NULL) - , _close_cb(NULL) - , _close_arg(NULL) - , _tx_buffer(NULL) - , _tx_buffer_size(TCP_MSS) - , next(NULL) -{} - -AsyncPrinter::AsyncPrinter(AsyncClient *client, size_t txBufLen) - : _client(client) - , _data_cb(NULL) - , _data_arg(NULL) - , _close_cb(NULL) - , _close_arg(NULL) - , _tx_buffer(NULL) - , _tx_buffer_size(txBufLen) - , next(NULL) -{ - _attachCallbacks(); - _tx_buffer = new (std::nothrow) cbuf(_tx_buffer_size); - if(_tx_buffer == NULL) { - panic(); //What should we do? - } -} - -AsyncPrinter::~AsyncPrinter(){ - _on_close(); -} - -void AsyncPrinter::onData(ApDataHandler cb, void *arg){ - _data_cb = cb; - _data_arg = arg; -} - -void AsyncPrinter::onClose(ApCloseHandler cb, void *arg){ - _close_cb = cb; - _close_arg = arg; -} - -int AsyncPrinter::connect(IPAddress ip, uint16_t port){ - if(_client != NULL && connected()) - return 0; - _client = new (std::nothrow) AsyncClient(); - if (_client == NULL) { - panic(); - } - - _client->onConnect([](void *obj, AsyncClient *c){ ((AsyncPrinter*)(obj))->_onConnect(c); }, this); - if(_client->connect(ip, port)){ - while(_client && _client->state() < 4) - delay(1); - return connected(); - } - return 0; -} - -int AsyncPrinter::connect(const char *host, uint16_t port){ - if(_client != NULL && connected()) - return 0; - _client = new (std::nothrow) AsyncClient(); - if (_client == NULL) { - panic(); - } - - _client->onConnect([](void *obj, AsyncClient *c){ ((AsyncPrinter*)(obj))->_onConnect(c); }, this); - if(_client->connect(host, port)){ - while(_client && _client->state() < 4) - delay(1); - return connected(); - } - return 0; -} - -void AsyncPrinter::_onConnect(AsyncClient *c){ - (void)c; - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } - _tx_buffer = new (std::nothrow) cbuf(_tx_buffer_size); - if(_tx_buffer) { - panic(); - } - - _attachCallbacks(); -} - -AsyncPrinter::operator bool(){ return connected(); } - -AsyncPrinter & AsyncPrinter::operator=(const AsyncPrinter &other){ - if(_client != NULL){ - _client->close(true); - _client = NULL; - } - _tx_buffer_size = other._tx_buffer_size; - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } - _tx_buffer = new (std::nothrow) cbuf(other._tx_buffer_size); - if(_tx_buffer == NULL) { - panic(); - } - - _client = other._client; - _attachCallbacks(); - return *this; -} - -size_t AsyncPrinter::write(uint8_t data){ - return write(&data, 1); -} - -size_t AsyncPrinter::write(const uint8_t *data, size_t len){ - if(_tx_buffer == NULL || !connected()) - return 0; - size_t toWrite = 0; - size_t toSend = len; - while(_tx_buffer->room() < toSend){ - toWrite = _tx_buffer->room(); - _tx_buffer->write((const char*)data, toWrite); - while(connected() && !_client->canSend()) - delay(0); - if(!connected()) - return 0; // or len - toSend; - _sendBuffer(); - toSend -= toWrite; - } - _tx_buffer->write((const char*)(data+(len - toSend)), toSend); - while(connected() && !_client->canSend()) delay(0); - if(!connected()) return 0; // or len - toSend; - _sendBuffer(); - return len; -} - -bool AsyncPrinter::connected(){ - return (_client != NULL && _client->connected()); -} - -void AsyncPrinter::close(){ - if(_client != NULL) - _client->close(true); -} - -size_t AsyncPrinter::_sendBuffer(){ - size_t available = _tx_buffer->available(); - if(!connected() || !_client->canSend() || available == 0) - return 0; - size_t sendable = _client->space(); - if(sendable < available) - available= sendable; - char *out = new (std::nothrow) char[available]; - if (out == NULL) { - panic(); // Connection should be aborted instead - } - - _tx_buffer->read(out, available); - size_t sent = _client->write(out, available); - delete out; - return sent; -} - -void AsyncPrinter::_onData(void *data, size_t len){ - if(_data_cb) - _data_cb(_data_arg, this, (uint8_t*)data, len); -} - -void AsyncPrinter::_on_close(){ - if(_client != NULL){ - _client = NULL; - } - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } - if(_close_cb) - _close_cb(_close_arg, this); -} - -void AsyncPrinter::_attachCallbacks(){ - _client->onPoll([](void *obj, AsyncClient* c){ (void)c; ((AsyncPrinter*)(obj))->_sendBuffer(); }, this); - _client->onAck([](void *obj, AsyncClient* c, size_t len, uint32_t time){ (void)c; (void)len; (void)time; ((AsyncPrinter*)(obj))->_sendBuffer(); }, this); - _client->onDisconnect([](void *obj, AsyncClient* c){ ((AsyncPrinter*)(obj))->_on_close(); delete c; }, this); - _client->onData([](void *obj, AsyncClient* c, void *data, size_t len){ (void)c; ((AsyncPrinter*)(obj))->_onData(data, len); }, this); -} diff --git a/lib/ESPAsyncTCP-esphome/src/AsyncPrinter.h b/lib/ESPAsyncTCP-esphome/src/AsyncPrinter.h deleted file mode 100644 index c3ebe3a..0000000 --- a/lib/ESPAsyncTCP-esphome/src/AsyncPrinter.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef ASYNCPRINTER_H_ -#define ASYNCPRINTER_H_ - -#include "Arduino.h" -#include "ESPAsyncTCP.h" -#include "cbuf.h" - -class AsyncPrinter; - -typedef std::function ApDataHandler; -typedef std::function ApCloseHandler; - -class AsyncPrinter: public Print { - private: - AsyncClient *_client; - ApDataHandler _data_cb; - void *_data_arg; - ApCloseHandler _close_cb; - void *_close_arg; - cbuf *_tx_buffer; - size_t _tx_buffer_size; - - void _onConnect(AsyncClient *c); - public: - AsyncPrinter *next; - - AsyncPrinter(); - AsyncPrinter(AsyncClient *client, size_t txBufLen = TCP_MSS); - virtual ~AsyncPrinter(); - - int connect(IPAddress ip, uint16_t port); - int connect(const char *host, uint16_t port); - - void onData(ApDataHandler cb, void *arg); - void onClose(ApCloseHandler cb, void *arg); - - operator bool(); - AsyncPrinter & operator=(const AsyncPrinter &other); - - size_t write(uint8_t data); - size_t write(const uint8_t *data, size_t len); - - bool connected(); - void close(); - - size_t _sendBuffer(); - void _onData(void *data, size_t len); - void _on_close(); - void _attachCallbacks(); -}; - -#endif /* ASYNCPRINTER_H_ */ diff --git a/lib/ESPAsyncTCP-esphome/src/DebugPrintMacros.h b/lib/ESPAsyncTCP-esphome/src/DebugPrintMacros.h deleted file mode 100644 index 30ed706..0000000 --- a/lib/ESPAsyncTCP-esphome/src/DebugPrintMacros.h +++ /dev/null @@ -1,112 +0,0 @@ -#ifndef _DEBUG_PRINT_MACROS_H -#define _DEBUG_PRINT_MACROS_H -// Some customizable print macros to suite the debug needs de jour. - -// Debug macros -// #include -// https://stackoverflow.com/questions/8487986/file-macro-shows-full-path -// This value is resolved at compile time. -#define _FILENAME_ strrchr("/" __FILE__, '/') - -// #define DEBUG_ESP_ASYNC_TCP 1 -// #define DEBUG_ESP_TCP_SSL 1 -// #define DEBUG_ESP_PORT Serial - -#if defined(DEBUG_ESP_PORT) && !defined(DEBUG_TIME_STAMP_FMT) -#define DEBUG_TIME_STAMP_FMT "%06u.%03u " -struct _DEBUG_TIME_STAMP { - unsigned dec; - unsigned whole; -}; -inline struct _DEBUG_TIME_STAMP debugTimeStamp(void) { - struct _DEBUG_TIME_STAMP st; - unsigned now = millis() % 1000000000; - st.dec = now % 1000; - st.whole = now / 1000; - return st; -} -#endif - -#if defined(DEBUG_ESP_PORT) && !defined(DEBUG_ESP_PORT_PRINTF) - -#ifdef __cplusplus -#define DEBUG_ESP_PORT_PRINTF(format, ...) DEBUG_ESP_PORT.printf((format), ##__VA_ARGS__) -#define DEBUG_ESP_PORT_PRINTF_F(format, ...) DEBUG_ESP_PORT.printf_P(PSTR(format), ##__VA_ARGS__) -#define DEBUG_ESP_PORT_FLUSH DEBUG_ESP_PORT.flush -#else -// Handle debug printing from .c without CPP Stream, Print, ... classes -// Cannot handle flash strings in this setting -#define DEBUG_ESP_PORT_PRINTF ets_uart_printf -#define DEBUG_ESP_PORT_PRINTF_F ets_uart_printf -#define DEBUG_ESP_PORT_FLUSH (void)0 -#endif - -#endif - -#if defined(DEBUG_ESP_PORT) && !defined(DEBUG_GENERIC) - #define DEBUG_GENERIC( module, format, ... ) \ - do { \ - struct _DEBUG_TIME_STAMP st = debugTimeStamp(); \ - DEBUG_ESP_PORT_PRINTF( (DEBUG_TIME_STAMP_FMT module " " format), st.whole, st.dec, ##__VA_ARGS__ ); \ - } while(false) -#endif -#if defined(DEBUG_ESP_PORT) && !defined(DEBUG_GENERIC_F) - #define DEBUG_GENERIC_F( module, format, ... ) \ - do { \ - struct _DEBUG_TIME_STAMP st = debugTimeStamp(); \ - DEBUG_ESP_PORT_PRINTF_F( (DEBUG_TIME_STAMP_FMT module " " format), st.whole, st.dec, ##__VA_ARGS__ ); \ - } while(false) -#endif - -#if defined(DEBUG_GENERIC) && !defined(ASSERT_GENERIC) -#define ASSERT_GENERIC( a, module ) \ - do { \ - if ( !(a) ) { \ - DEBUG_GENERIC( module, "%s:%s:%u: ASSERT("#a") failed!\n", __FILE__, __func__, __LINE__); \ - DEBUG_ESP_PORT_FLUSH(); \ - } \ - } while(false) -#endif -#if defined(DEBUG_GENERIC_F) && !defined(ASSERT_GENERIC_F) -#define ASSERT_GENERIC_F( a, module ) \ - do { \ - if ( !(a) ) { \ - DEBUG_GENERIC_F( module, "%s:%s:%u: ASSERT("#a") failed!\n", __FILE__, __func__, __LINE__); \ - DEBUG_ESP_PORT_FLUSH(); \ - } \ - } while(false) -#endif - -#ifndef DEBUG_GENERIC -#define DEBUG_GENERIC(...) do { (void)0;} while(false) -#endif - -#ifndef DEBUG_GENERIC_F -#define DEBUG_GENERIC_F(...) do { (void)0;} while(false) -#endif - -#ifndef ASSERT_GENERIC -#define ASSERT_GENERIC(...) do { (void)0;} while(false) -#endif - -#ifndef ASSERT_GENERIC_F -#define ASSERT_GENERIC_F(...) do { (void)0;} while(false) -#endif - -#ifndef DEBUG_ESP_PRINTF -#define DEBUG_ESP_PRINTF( format, ...) DEBUG_GENERIC_F("[%s]", format, &_FILENAME_[1], ##__VA_ARGS__) -#endif - -#if defined(DEBUG_ESP_ASYNC_TCP) && !defined(ASYNC_TCP_DEBUG) -#define ASYNC_TCP_DEBUG( format, ...) DEBUG_GENERIC_F("[ASYNC_TCP]", format, ##__VA_ARGS__) -#endif - -#ifndef ASYNC_TCP_ASSERT -#define ASYNC_TCP_ASSERT( a ) ASSERT_GENERIC_F( (a), "[ASYNC_TCP]") -#endif - -#if defined(DEBUG_ESP_TCP_SSL) && !defined(TCP_SSL_DEBUG) -#define TCP_SSL_DEBUG( format, ...) DEBUG_GENERIC_F("[TCP_SSL]", format, ##__VA_ARGS__) -#endif - -#endif //_DEBUG_PRINT_MACROS_H diff --git a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.cpp b/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.cpp deleted file mode 100644 index fe08b93..0000000 --- a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.cpp +++ /dev/null @@ -1,1406 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -/* -Changes for July 2019 - -The operator "new ..." was changed to "new (std::nothrow) ...", which will -return NULL when the heap is out of memory. Without the change "soft WDT" -was the result, starting with Arduino ESP8266 Core 2.5.0. (Note, RE:"soft -WDT" - the error reporting may improve with core 2.6.) With proir core -versions the library appears to work fine. -ref: https://github.com/esp8266/Arduino/issues/6269#issue-464978944 - -To support newer lwIP versions and buffer models. All references to 1460 -were replaced with TCP_MSS. If TCP_MSS is not defined (exp. 1.4v lwIP) -1460 is assumed. - -The ESPAsyncTCP library should build for Arduino ESP8266 Core releases: -2.3.0, 2.4.1, 2.4.2, 2.5.1, 2.5.2. It may still build with core versions -2.4.0 and 2.5.0. I did not do any regression testing with these, since -they had too many issues and were quickly superseded. - -lwIP tcp_err() callback often resulted in crashes. The problem was a -tcp_err() would come in, while processing a send or receive in the -forground. The tcp_err() callback would be passed down to a client's -registered disconnect CB. A common problem with SyncClient and other -modules as well as some client code was: the freeing of ESPAsyncTCP -AsyncClient objects via disconnect CB handlers while the library was -waiting for an operstion to finished. Attempts to access bad pointers -followed. For SyncClient this commonly occured during a call to delay(). -On return to SyncClient _client was invalid. Also the problem described by -issue #94 also surfaced - -Use of tcp_abort() required some very special handling and was very -challenging to make work without changing client API. ERR_ABRT can only be -used once on a return to lwIP for a given connection and since the -AsyncClient structure was sometimes deleted before returning to lwIP, the -state tracking became tricky. While ugly, a global variable for this -seemed to work; however, I abanded it when I saw a possible -reentrancy/concurrency issue. After several approaches I settled the -problem by creating "class ACErrorTracker" to manage the issue. - - -Additional Async Client considerations: - -The client sketch must always test if the connection is still up at loop() -entry and after the return of any function call, that may have done a -delay() or yield() or any ESPAsyncTCP library family call. For example, -the connection could be lost during a call to _client->write(...). Client -sketches that delete _client as part of their onDisconnect() handler must -be very careful as _client will become invalid after calls to delay(), -yield(), etc. - - - */ - -#include "Arduino.h" - -#include "ESPAsyncTCP.h" -extern "C"{ - #include "lwip/opt.h" - #include "lwip/tcp.h" - #include "lwip/inet.h" - #include "lwip/dns.h" - #include "lwip/init.h" -} -#include - -/* - Async Client Error Return Tracker -*/ -// Assumption: callbacks are never called with err == ERR_ABRT; however, -// they may return ERR_ABRT. - -ACErrorTracker::ACErrorTracker(AsyncClient *c): - _client(c) - , _close_error(ERR_OK) - , _errored(EE_OK) -#ifdef DEBUG_MORE - , _error_event_cb(NULL) - , _error_event_cb_arg(NULL) -#endif -{} - -#ifdef DEBUG_MORE -/** - * This is not necessary, but a start at gathering some statistics on - * errored out connections. Used from AsyncServer. - */ -void ACErrorTracker::onErrorEvent(AsNotifyHandler cb, void *arg) { - _error_event_cb = cb; - _error_event_cb_arg = arg; -} -#endif - -void ACErrorTracker::setCloseError(err_t e) { - if (e != ERR_OK) - ASYNC_TCP_DEBUG("setCloseError() to: %s(%ld)\n", _client->errorToString(e), e); - if(_errored == EE_OK) - _close_error = e; -} -/** - * Called mainly by callback routines, called when err is not ERR_OK. - * This prevents the possiblity of aborting an already errored out - * connection. - */ -void ACErrorTracker::setErrored(size_t errorEvent){ - if(EE_OK == _errored) - _errored = errorEvent; -#ifdef DEBUG_MORE - if (_error_event_cb) - _error_event_cb(_error_event_cb_arg, errorEvent); -#endif -} -/** - * Used by callback functions only. Used for proper ERR_ABRT return value - * reporting. ERR_ABRT is only reported/returned once; thereafter ERR_OK - * is always returned. - */ -err_t ACErrorTracker::getCallbackCloseError(void){ - if (EE_OK != _errored) - return ERR_OK; - if (ERR_ABRT == _close_error) - setErrored(EE_ABORTED); - return _close_error; -} - -/* - Async TCP Client -*/ -#if DEBUG_ESP_ASYNC_TCP -static size_t _connectionCount=0; -#endif - -#if ASYNC_TCP_SSL_ENABLED -AsyncClient::AsyncClient(tcp_pcb* pcb, SSL_CTX * ssl_ctx): -#else -AsyncClient::AsyncClient(tcp_pcb* pcb): -#endif - _connect_cb(0) - , _connect_cb_arg(0) - , _discard_cb(0) - , _discard_cb_arg(0) - , _sent_cb(0) - , _sent_cb_arg(0) - , _error_cb(0) - , _error_cb_arg(0) - , _recv_cb(0) - , _recv_cb_arg(0) - , _pb_cb(0) - , _pb_cb_arg(0) - , _timeout_cb(0) - , _timeout_cb_arg(0) - , _poll_cb(0) - , _poll_cb_arg(0) - , _pcb_busy(false) -#if ASYNC_TCP_SSL_ENABLED - , _pcb_secure(false) - , _handshake_done(true) -#endif - , _pcb_sent_at(0) - , _close_pcb(false) - , _ack_pcb(true) - , _tx_unacked_len(0) - , _tx_acked_len(0) - , _rx_ack_len(0) - , _rx_last_packet(0) - , _rx_since_timeout(0) - , _ack_timeout(ASYNC_MAX_ACK_TIME) - , _connect_port(0) - , _recv_pbuf_flags(0) - , _errorTracker(NULL) - , prev(NULL) - , next(NULL) -{ - _pcb = pcb; - if(_pcb){ - _rx_last_packet = millis(); - tcp_setprio(_pcb, TCP_PRIO_MIN); - tcp_arg(_pcb, this); - tcp_recv(_pcb, &_s_recv); - tcp_sent(_pcb, &_s_sent); - tcp_err(_pcb, &_s_error); - tcp_poll(_pcb, &_s_poll, 1); -#if ASYNC_TCP_SSL_ENABLED - if(ssl_ctx){ - if(tcp_ssl_new_server(_pcb, ssl_ctx) < 0){ - _close(); - return; - } - tcp_ssl_arg(_pcb, this); - tcp_ssl_data(_pcb, &_s_data); - tcp_ssl_handshake(_pcb, &_s_handshake); - tcp_ssl_err(_pcb, &_s_ssl_error); - - _pcb_secure = true; - _handshake_done = false; - } -#endif - } - - _errorTracker = std::make_shared(this); -#if DEBUG_ESP_ASYNC_TCP - _errorTracker->setConnectionId(++_connectionCount); -#endif -} - -AsyncClient::~AsyncClient(){ - if(_pcb) - _close(); - - _errorTracker->clearClient(); -} - -inline void clearTcpCallbacks(tcp_pcb* pcb){ - tcp_arg(pcb, NULL); - tcp_sent(pcb, NULL); - tcp_recv(pcb, NULL); - tcp_err(pcb, NULL); - tcp_poll(pcb, NULL, 0); -} - -#if ASYNC_TCP_SSL_ENABLED -bool AsyncClient::connect(IPAddress ip, uint16_t port, bool secure){ -#else -bool AsyncClient::connect(IPAddress ip, uint16_t port){ -#endif - if (_pcb) //already connected - return false; - IPAddress addr; - addr = ip; -#if LWIP_VERSION_MAJOR == 1 - netif* interface = ip_route(&addr); - if (!interface){ //no route to host - return false; - } -#endif - tcp_pcb* pcb = tcp_new(); - if (!pcb){ //could not allocate pcb - return false; - } - - tcp_setprio(pcb, TCP_PRIO_MIN); -#if ASYNC_TCP_SSL_ENABLED - _pcb_secure = secure; - _handshake_done = !secure; -#endif - tcp_arg(pcb, this); - tcp_err(pcb, &_s_error); - size_t err = tcp_connect(pcb, addr, port,(tcp_connected_fn)&_s_connected); - return (ERR_OK == err); -} - -#if ASYNC_TCP_SSL_ENABLED -bool AsyncClient::connect(const char* host, uint16_t port, bool secure){ -#else -bool AsyncClient::connect(const char* host, uint16_t port){ -#endif - IPAddress addr; - err_t err = dns_gethostbyname(host, addr, (dns_found_callback)&_s_dns_found, this); - if(err == ERR_OK) { -#if ASYNC_TCP_SSL_ENABLED - return connect(addr, port, secure); -#else - return connect(addr, port); -#endif - } else if(err == ERR_INPROGRESS) { -#if ASYNC_TCP_SSL_ENABLED - _pcb_secure = secure; - _handshake_done = !secure; -#endif - _connect_port = port; - return true; - } - return false; -} - -AsyncClient& AsyncClient::operator=(const AsyncClient& other){ - if (_pcb) { - ASYNC_TCP_DEBUG("operator=[%u]: Abandoned _pcb(0x%" PRIXPTR ") forced close.\n", getConnectionId(), uintptr_t(_pcb)); - _close(); - } - _errorTracker = other._errorTracker; - - // I am confused when "other._pcb" falls out of scope the destructor will - // close it? TODO: Look to see where this is used and how it might work. - _pcb = other._pcb; - if (_pcb) { - _rx_last_packet = millis(); - tcp_setprio(_pcb, TCP_PRIO_MIN); - tcp_arg(_pcb, this); - tcp_recv(_pcb, &_s_recv); - tcp_sent(_pcb, &_s_sent); - tcp_err(_pcb, &_s_error); - tcp_poll(_pcb, &_s_poll, 1); -#if ASYNC_TCP_SSL_ENABLED - if(tcp_ssl_has(_pcb)){ - _pcb_secure = true; - _handshake_done = false; - tcp_ssl_arg(_pcb, this); - tcp_ssl_data(_pcb, &_s_data); - tcp_ssl_handshake(_pcb, &_s_handshake); - tcp_ssl_err(_pcb, &_s_ssl_error); - } else { - _pcb_secure = false; - _handshake_done = true; - } -#endif - } - return *this; -} - -bool AsyncClient::operator==(const AsyncClient &other) { - return (_pcb != NULL && other._pcb != NULL && (IPAddress(_pcb->remote_ip) == IPAddress(other._pcb->remote_ip)) && (_pcb->remote_port == other._pcb->remote_port)); -} - -void AsyncClient::abort(){ - // Notes: - // 1) _pcb is set to NULL, so we cannot call tcp_abort() more than once. - // 2) setCloseError(ERR_ABRT) is only done here! - // 3) Using this abort() function guarantees only one tcp_abort() call is - // made and only one CB returns with ERR_ABORT. - // 4) After abort() is called from _close(), no callbacks with an err - // parameter will be called. eg. _recv(), _error(), _connected(). - // _close() will reset there CB handlers before calling. - // 5) A callback to _error(), will set _pcb to NULL, thus avoiding the - // of a 2nd call to tcp_abort(). - // 6) Callbacks to _recv() or _connected() with err set, will result in _pcb - // set to NULL. Thus, preventing possible calls later to tcp_abort(). - if(_pcb) { - tcp_abort(_pcb); - _pcb = NULL; - setCloseError(ERR_ABRT); - } - return; -} - -void AsyncClient::close(bool now){ - if(_pcb) - tcp_recved(_pcb, _rx_ack_len); - if(now) { - ASYNC_TCP_DEBUG("close[%u]: AsyncClient 0x%" PRIXPTR "\n", getConnectionId(), uintptr_t(this)); - _close(); - } else { - _close_pcb = true; - } -} - -void AsyncClient::stop() { - close(false); -} - -bool AsyncClient::free(){ - if(!_pcb) - return true; - if(_pcb->state == 0 || _pcb->state > 4) - return true; - return false; -} - -size_t AsyncClient::write(const char* data) { - if(data == NULL) - return 0; - return write(data, strlen(data)); -} - -size_t AsyncClient::write(const char* data, size_t size, uint8_t apiflags) { - size_t will_send = add(data, size, apiflags); - - if(!will_send || !send()) - return 0; - return will_send; -} - -size_t AsyncClient::add(const char* data, size_t size, uint8_t apiflags) { - if(!_pcb || size == 0 || data == NULL) - return 0; - size_t room = space(); - if(!room) - return 0; -#if ASYNC_TCP_SSL_ENABLED - if(_pcb_secure){ - int sent = tcp_ssl_write(_pcb, (uint8_t*)data, size); - if(sent >= 0){ - _tx_unacked_len += sent; - return sent; - } - _close(); - return 0; - } -#endif - size_t will_send = (room < size) ? room : size; - err_t err = tcp_write(_pcb, data, will_send, apiflags); - if(err != ERR_OK) { - ASYNC_TCP_DEBUG("_add[%u]: tcp_write() returned err: %s(%ld)\n", getConnectionId(), errorToString(err), err); - return 0; - } - _tx_unacked_len += will_send; - return will_send; -} - -bool AsyncClient::send(){ -#if ASYNC_TCP_SSL_ENABLED - if(_pcb_secure) - return true; -#endif - err_t err = tcp_output(_pcb); - if(err == ERR_OK){ - _pcb_busy = true; - _pcb_sent_at = millis(); - return true; - } - - ASYNC_TCP_DEBUG("send[%u]: tcp_output() returned err: %s(%ld)", getConnectionId(), errorToString(err), err); - return false; -} - -size_t AsyncClient::ack(size_t len){ - if(len > _rx_ack_len) - len = _rx_ack_len; - if(len) - tcp_recved(_pcb, len); - _rx_ack_len -= len; - return len; -} - -// Private Callbacks - -void AsyncClient::_connected(std::shared_ptr& errorTracker, void* pcb, err_t err){ - //(void)err; // LWIP v1.4 appears to always call with ERR_OK - // Documentation for 2.1.0 also says: - // "err - An unused error code, always ERR_OK currently ;-)" - // https://www.nongnu.org/lwip/2_1_x/tcp_8h.html#a939867106bd492caf2d85852fb7f6ae8 - // Based on that wording and emoji lets just handle it now. - // After all, the API does allow for an err != ERR_OK. - if(NULL == pcb || ERR_OK != err) { - ASYNC_TCP_DEBUG("_connected[%u]:%s err: %s(%ld)\n", errorTracker->getConnectionId(), ((NULL == pcb) ? " NULL == pcb!," : ""), errorToString(err), err); - errorTracker->setCloseError(err); - errorTracker->setErrored(EE_CONNECTED_CB); - _pcb = reinterpret_cast(pcb); - if (_pcb) - clearTcpCallbacks(_pcb); - _pcb = NULL; - _error(err); - return; - } - - _pcb = reinterpret_cast(pcb); - if(_pcb){ - _pcb_busy = false; - _rx_last_packet = millis(); - tcp_setprio(_pcb, TCP_PRIO_MIN); - tcp_recv(_pcb, &_s_recv); - tcp_sent(_pcb, &_s_sent); - tcp_poll(_pcb, &_s_poll, 1); -#if ASYNC_TCP_SSL_ENABLED - if(_pcb_secure){ - if(tcp_ssl_new_client(_pcb) < 0){ - _close(); - return; - } - tcp_ssl_arg(_pcb, this); - tcp_ssl_data(_pcb, &_s_data); - tcp_ssl_handshake(_pcb, &_s_handshake); - tcp_ssl_err(_pcb, &_s_ssl_error); - } - } - if(!_pcb_secure && _connect_cb) -#else - } - if(_connect_cb) -#endif - _connect_cb(_connect_cb_arg, this); - return; -} - -void AsyncClient::_close(){ - if(_pcb) { -#if ASYNC_TCP_SSL_ENABLED - if(_pcb_secure){ - tcp_ssl_free(_pcb); - } -#endif - clearTcpCallbacks(_pcb); - err_t err = tcp_close(_pcb); - if(ERR_OK == err) { - setCloseError(err); - ASYNC_TCP_DEBUG("_close[%u]: AsyncClient 0x%" PRIXPTR "\n", getConnectionId(), uintptr_t(this)); - } else { - ASYNC_TCP_DEBUG("_close[%u]: abort() called for AsyncClient 0x%" PRIXPTR "\n", getConnectionId(), uintptr_t(this)); - abort(); - } - _pcb = NULL; - if(_discard_cb) - _discard_cb(_discard_cb_arg, this); - } - return; -} - -void AsyncClient::_error(err_t err) { - ASYNC_TCP_DEBUG("_error[%u]:%s err: %s(%ld)\n", getConnectionId(), ((NULL == _pcb) ? " NULL == _pcb!," : ""), errorToString(err), err); - if(_pcb){ -#if ASYNC_TCP_SSL_ENABLED - if(_pcb_secure){ - tcp_ssl_free(_pcb); - } -#endif - // At this callback _pcb is possible already freed. Thus, no calls are - // made to set to NULL other callbacks. - _pcb = NULL; - } - if(_error_cb) - _error_cb(_error_cb_arg, this, err); - if(_discard_cb) - _discard_cb(_discard_cb_arg, this); -} - -#if ASYNC_TCP_SSL_ENABLED -void AsyncClient::_ssl_error(int8_t err){ - if(_error_cb) - _error_cb(_error_cb_arg, this, err+64); -} -#endif - -void AsyncClient::_sent(std::shared_ptr& errorTracker, tcp_pcb* pcb, uint16_t len) { - (void)pcb; -#if ASYNC_TCP_SSL_ENABLED - if (_pcb_secure && !_handshake_done) - return; -#endif - _rx_last_packet = millis(); - _tx_unacked_len -= len; - _tx_acked_len += len; - ASYNC_TCP_DEBUG("_sent[%u]: %4u, unacked=%4u, acked=%4u, space=%4u\n", errorTracker->getConnectionId(), len, _tx_unacked_len, _tx_acked_len, space()); - if(_tx_unacked_len == 0){ - _pcb_busy = false; - errorTracker->setCloseError(ERR_OK); - if(_sent_cb) { - _sent_cb(_sent_cb_arg, this, _tx_acked_len, (millis() - _pcb_sent_at)); - if(!errorTracker->hasClient()) - return; - } - _tx_acked_len = 0; - } - return; -} - -void AsyncClient::_recv(std::shared_ptr& errorTracker, tcp_pcb* pcb, pbuf* pb, err_t err) { - // While lwIP v1.4 appears to always call with ERR_OK, 2.x lwIP may present - // a non-ERR_OK value. - // https://www.nongnu.org/lwip/2_1_x/tcp_8h.html#a780cfac08b02c66948ab94ea974202e8 - if(NULL == pcb || ERR_OK != err){ - ASYNC_TCP_DEBUG("_recv[%u]:%s err: %s(%ld)\n", errorTracker->getConnectionId(), ((NULL == pcb) ? " NULL == pcb!," : ""), errorToString(err), err); - ASYNC_TCP_ASSERT(ERR_ABRT != err); - errorTracker->setCloseError(err); - errorTracker->setErrored(EE_RECV_CB); - _pcb = pcb; - if(_pcb) - clearTcpCallbacks(_pcb); - _pcb = NULL; - // I think we are safe from being called from an interrupt context. - // Best Hint that calling _error() is safe: - // https://www.nongnu.org/lwip/2_1_x/group__lwip__nosys.html - // "Feed incoming packets to netif->input(pbuf, netif) function from - // mainloop, not from interrupt context. You can allocate a Packet buffers - // (PBUF) in interrupt context and put them into a queue which is processed - // from mainloop." - // And the description of "Mainloop Mode" option 2: - // https://www.nongnu.org/lwip/2_1_x/pitfalls.html - // "2) Run lwIP in a mainloop. ... lwIP is ONLY called from mainloop - // callstacks here. The ethernet IRQ has to put received telegrams into a - // queue which is polled in the mainloop. Ensure lwIP is NEVER called from - // an interrupt, ...!" - // Based on these comments I am thinking tcp_recv_fn() is called - // from somebody's mainloop(), which could only have been reached from a - // delay like function or the Arduino sketch loop() function has returned. - // What I don't want is for the client sketch to delete the AsyncClient - // object via _error() while it is in the middle of using it. However, - // the client sketch must always test that the connection is still up - // at loop() entry and after the return of any function call, that may - // have done a delay() or yield(). - _error(err); - return; - } - - if(pb == NULL){ - ASYNC_TCP_DEBUG("_recv[%u]: pb == NULL! Closing... %ld\n", errorTracker->getConnectionId(), err); - _close(); - return; - } - _rx_last_packet = millis(); - errorTracker->setCloseError(ERR_OK); -#if ASYNC_TCP_SSL_ENABLED - if(_pcb_secure){ - ASYNC_TCP_DEBUG("_recv[%u]: %d\n", getConnectionId(), pb->tot_len); - int read_bytes = tcp_ssl_read(pcb, pb); - if(read_bytes < 0){ - if (read_bytes != SSL_CLOSE_NOTIFY) { - ASYNC_TCP_DEBUG("_recv[%u] err: %d\n", getConnectionId(), read_bytes); - _close(); - } - } - return; - } -#endif - while(pb != NULL){ - // IF this callback function returns ERR_OK or ERR_ABRT - // then it is assummed we freed the pbufs. - // https://www.nongnu.org/lwip/2_1_x/group__tcp__raw.html#ga8afd0b316a87a5eeff4726dc95006ed0 - if(!errorTracker->hasClient()){ - while(pb != NULL){ - pbuf *b = pb; - pb = b->next; - b->next = NULL; - pbuf_free(b); - } - return; - } - //we should not ack before we assimilate the data - _ack_pcb = true; - pbuf *b = pb; - pb = b->next; - b->next = NULL; - ASYNC_TCP_DEBUG("_recv[%u]: %d%s\n", errorTracker->getConnectionId(), b->len, (b->flags&PBUF_FLAG_PUSH)?", PBUF_FLAG_PUSH":""); - if(_pb_cb){ - _pb_cb(_pb_cb_arg, this, b); - } else { - if(_recv_cb){ - _recv_pbuf_flags = b->flags; - _recv_cb(_recv_cb_arg, this, b->payload, b->len); - } - if(errorTracker->hasClient()){ - if(!_ack_pcb) - _rx_ack_len += b->len; - else - tcp_recved(pcb, b->len); - } - pbuf_free(b); - } - } - return; -} - -void AsyncClient::_poll(std::shared_ptr& errorTracker, tcp_pcb* pcb){ - (void)pcb; - errorTracker->setCloseError(ERR_OK); - - // Close requested - if(_close_pcb){ - ASYNC_TCP_DEBUG("_poll[%u]: Process _close_pcb.\n", errorTracker->getConnectionId() ); - _close_pcb = false; - _close(); - return; - } - uint32_t now = millis(); - - // ACK Timeout - if(_pcb_busy && _ack_timeout && (now - _pcb_sent_at) >= _ack_timeout){ - _pcb_busy = false; - if(_timeout_cb) - _timeout_cb(_timeout_cb_arg, this, (now - _pcb_sent_at)); - return; - } - // RX Timeout - if(_rx_since_timeout && (now - _rx_last_packet) >= (_rx_since_timeout * 1000)){ - ASYNC_TCP_DEBUG("_poll[%u]: RX Timeout.\n", errorTracker->getConnectionId() ); - _close(); - return; - } -#if ASYNC_TCP_SSL_ENABLED - // SSL Handshake Timeout - if(_pcb_secure && !_handshake_done && (now - _rx_last_packet) >= 2000){ - ASYNC_TCP_DEBUG("_poll[%u]: SSL Handshake Timeout.\n", errorTracker->getConnectionId() ); - _close(); - return; - } -#endif - // Everything is fine - if(_poll_cb) - _poll_cb(_poll_cb_arg, this); - return; -} - -#if LWIP_VERSION_MAJOR == 1 -void AsyncClient::_dns_found(struct ip_addr *ipaddr){ -#else -void AsyncClient::_dns_found(const ip_addr *ipaddr){ -#endif - if(ipaddr){ -#if ASYNC_TCP_SSL_ENABLED - connect(ipaddr, _connect_port, _pcb_secure); -#else - connect(ipaddr, _connect_port); -#endif - } else { - if(_error_cb) - _error_cb(_error_cb_arg, this, -55); - if(_discard_cb) - _discard_cb(_discard_cb_arg, this); - } -} - -// lwIP Callbacks -#if LWIP_VERSION_MAJOR == 1 -void AsyncClient::_s_dns_found(const char *name, ip_addr_t *ipaddr, void *arg){ -#else -void AsyncClient::_s_dns_found(const char *name, const ip_addr *ipaddr, void *arg){ -#endif - (void)name; - reinterpret_cast(arg)->_dns_found(ipaddr); -} - -err_t AsyncClient::_s_poll(void *arg, struct tcp_pcb *tpcb) { - AsyncClient *c = reinterpret_cast(arg); - std::shared_ptrerrorTracker = c->getACErrorTracker(); - c->_poll(errorTracker, tpcb); - return errorTracker->getCallbackCloseError(); -} - -err_t AsyncClient::_s_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, err_t err) { - AsyncClient *c = reinterpret_cast(arg); - auto errorTracker = c->getACErrorTracker(); - c->_recv(errorTracker, tpcb, pb, err); - return errorTracker->getCallbackCloseError(); -} - -void AsyncClient::_s_error(void *arg, err_t err) { - AsyncClient *c = reinterpret_cast(arg); - auto errorTracker = c->getACErrorTracker(); - errorTracker->setCloseError(err); - errorTracker->setErrored(EE_ERROR_CB); - c->_error(err); -} - -err_t AsyncClient::_s_sent(void *arg, struct tcp_pcb *tpcb, uint16_t len) { - AsyncClient *c = reinterpret_cast(arg); - auto errorTracker = c->getACErrorTracker(); - c->_sent(errorTracker, tpcb, len); - return errorTracker->getCallbackCloseError(); -} - -err_t AsyncClient::_s_connected(void* arg, void* tpcb, err_t err){ - AsyncClient *c = reinterpret_cast(arg); - auto errorTracker = c->getACErrorTracker(); - c->_connected(errorTracker, tpcb, err); - return errorTracker->getCallbackCloseError(); -} - -#if ASYNC_TCP_SSL_ENABLED -void AsyncClient::_s_data(void *arg, struct tcp_pcb *tcp, uint8_t * data, size_t len){ - (void)tcp; - AsyncClient *c = reinterpret_cast(arg); - if(c->_recv_cb) - c->_recv_cb(c->_recv_cb_arg, c, data, len); -} - -void AsyncClient::_s_handshake(void *arg, struct tcp_pcb *tcp, SSL *ssl){ - (void)tcp; - (void)ssl; - AsyncClient *c = reinterpret_cast(arg); - c->_handshake_done = true; - if(c->_connect_cb) - c->_connect_cb(c->_connect_cb_arg, c); -} - -void AsyncClient::_s_ssl_error(void *arg, struct tcp_pcb *tcp, int8_t err){ - (void)tcp; -#ifdef DEBUG_ESP_ASYNC_TCP - AsyncClient *c = reinterpret_cast(arg); - auto errorTracker = c->getACErrorTracker(); - ASYNC_TCP_DEBUG("_ssl_error[%u] err = %d\n", errorTracker->getConnectionId(), err); -#endif - reinterpret_cast(arg)->_ssl_error(err); -} -#endif - -// Operators - -AsyncClient & AsyncClient::operator+=(const AsyncClient &other) { - if(next == NULL){ - next = (AsyncClient*)(&other); - next->prev = this; - } else { - AsyncClient *c = next; - while(c->next != NULL) c = c->next; - c->next =(AsyncClient*)(&other); - c->next->prev = c; - } - return *this; -} - -void AsyncClient::setRxTimeout(uint32_t timeout){ - _rx_since_timeout = timeout; -} - -uint32_t AsyncClient::getRxTimeout(){ - return _rx_since_timeout; -} - -uint32_t AsyncClient::getAckTimeout(){ - return _ack_timeout; -} - -void AsyncClient::setAckTimeout(uint32_t timeout){ - _ack_timeout = timeout; -} - -void AsyncClient::setNoDelay(bool nodelay){ - if(!_pcb) - return; - if(nodelay) - tcp_nagle_disable(_pcb); - else - tcp_nagle_enable(_pcb); -} - -bool AsyncClient::getNoDelay(){ - if(!_pcb) - return false; - return tcp_nagle_disabled(_pcb); -} - -uint16_t AsyncClient::getMss(){ - if(_pcb) - return tcp_mss(_pcb); - return 0; -} - -uint16_t AsyncClient::getRemotePort() { - if(!_pcb) - return 0; - return _pcb->remote_port; -} - - -uint16_t AsyncClient::getLocalPort() { - if(!_pcb) - return 0; - return _pcb->local_port; -} - -IPAddress AsyncClient::remoteIP() { - if(!_pcb) - return IPAddress(0); - return _pcb->remote_ip; -} - -uint16_t AsyncClient::remotePort() { - return getRemotePort(); -} - -IPAddress AsyncClient::localIP() { - if(!_pcb) - return IPAddress(0); - return _pcb->local_ip; -} - -uint16_t AsyncClient::localPort() { - return getLocalPort(); -} - -#if ASYNC_TCP_SSL_ENABLED -SSL * AsyncClient::getSSL(){ - if(_pcb && _pcb_secure){ - return tcp_ssl_get_ssl(_pcb); - } - return NULL; -} -#endif - -uint8_t AsyncClient::state() { - if(!_pcb) - return 0; - return _pcb->state; -} - -bool AsyncClient::connected(){ - if (!_pcb) - return false; -#if ASYNC_TCP_SSL_ENABLED - return _pcb->state == 4 && _handshake_done; -#else - return _pcb->state == 4; -#endif -} - -bool AsyncClient::connecting(){ - if (!_pcb) - return false; - return _pcb->state > 0 && _pcb->state < 4; -} - -bool AsyncClient::disconnecting(){ - if (!_pcb) - return false; - return _pcb->state > 4 && _pcb->state < 10; -} - -bool AsyncClient::disconnected(){ - if (!_pcb) - return true; - return _pcb->state == 0 || _pcb->state == 10; -} - -bool AsyncClient::freeable(){ - if (!_pcb) - return true; - return _pcb->state == 0 || _pcb->state > 4; -} - -bool AsyncClient::canSend(){ - return !_pcb_busy && (space() > 0); -} - - -// Callback Setters - -void AsyncClient::onConnect(AcConnectHandler cb, void* arg){ - _connect_cb = cb; - _connect_cb_arg = arg; -} - -void AsyncClient::onDisconnect(AcConnectHandler cb, void* arg){ - _discard_cb = cb; - _discard_cb_arg = arg; -} - -void AsyncClient::onAck(AcAckHandler cb, void* arg){ - _sent_cb = cb; - _sent_cb_arg = arg; -} - -void AsyncClient::onError(AcErrorHandler cb, void* arg){ - _error_cb = cb; - _error_cb_arg = arg; -} - -void AsyncClient::onData(AcDataHandler cb, void* arg){ - _recv_cb = cb; - _recv_cb_arg = arg; -} - -void AsyncClient::onPacket(AcPacketHandler cb, void* arg){ - _pb_cb = cb; - _pb_cb_arg = arg; -} - -void AsyncClient::onTimeout(AcTimeoutHandler cb, void* arg){ - _timeout_cb = cb; - _timeout_cb_arg = arg; -} - -void AsyncClient::onPoll(AcConnectHandler cb, void* arg){ - _poll_cb = cb; - _poll_cb_arg = arg; -} - - -size_t AsyncClient::space(){ -#if ASYNC_TCP_SSL_ENABLED - if((_pcb != NULL) && (_pcb->state == 4) && _handshake_done){ - uint16_t s = tcp_sndbuf(_pcb); - if(_pcb_secure){ -#ifdef AXTLS_2_0_0_SNDBUF - return tcp_ssl_sndbuf(_pcb); -#else - if(s >= 128) //safe approach - return s - 128; - return 0; -#endif - } - return s; - } -#else // ASYNC_TCP_SSL_ENABLED - if((_pcb != NULL) && (_pcb->state == 4)){ - return tcp_sndbuf(_pcb); - } -#endif // ASYNC_TCP_SSL_ENABLED - return 0; -} - -void AsyncClient::ackPacket(struct pbuf * pb){ - if(!pb){ - return; - } - tcp_recved(_pcb, pb->len); - pbuf_free(pb); -} - -const char * AsyncClient::errorToString(err_t error) { - switch (error) { - case ERR_OK: return "No error, everything OK"; - case ERR_MEM: return "Out of memory error"; - case ERR_BUF: return "Buffer error"; - case ERR_TIMEOUT: return "Timeout"; - case ERR_RTE: return "Routing problem"; - case ERR_INPROGRESS: return "Operation in progress"; - case ERR_VAL: return "Illegal value"; - case ERR_WOULDBLOCK: return "Operation would block"; - case ERR_ABRT: return "Connection aborted"; - case ERR_RST: return "Connection reset"; - case ERR_CLSD: return "Connection closed"; - case ERR_CONN: return "Not connected"; - case ERR_ARG: return "Illegal argument"; - case ERR_USE: return "Address in use"; -#if defined(LWIP_VERSION_MAJOR) && (LWIP_VERSION_MAJOR > 1) - case ERR_ALREADY: return "Already connectioning"; -#endif - case ERR_IF: return "Low-level netif error"; - case ERR_ISCONN: return "Connection already established"; - case -55: return "DNS failed"; - default: return "Unknown error"; - } -} - -const char * AsyncClient::stateToString(){ - switch(state()){ - case 0: return "Closed"; - case 1: return "Listen"; - case 2: return "SYN Sent"; - case 3: return "SYN Received"; - case 4: return "Established"; - case 5: return "FIN Wait 1"; - case 6: return "FIN Wait 2"; - case 7: return "Close Wait"; - case 8: return "Closing"; - case 9: return "Last ACK"; - case 10: return "Time Wait"; - default: return "UNKNOWN"; - } -} - -/* - Async TCP Server -*/ -struct pending_pcb { - tcp_pcb* pcb; - pbuf *pb; - struct pending_pcb * next; -}; - -AsyncServer::AsyncServer(IPAddress addr, uint16_t port) - : _port(port) - , _addr(addr) - , _noDelay(false) - , _pcb(0) - , _connect_cb(0) - , _connect_cb_arg(0) -#if ASYNC_TCP_SSL_ENABLED - , _pending(NULL) - , _ssl_ctx(NULL) - , _file_cb(0) - , _file_cb_arg(0) -#endif -{ -#ifdef DEBUG_MORE - for (size_t i=0; inext; - if(p->pb){ - pbuf_free(p->pb); - } - free(p); - } - } - } -#endif -} - -void AsyncServer::setNoDelay(bool nodelay){ - _noDelay = nodelay; -} - -bool AsyncServer::getNoDelay(){ - return _noDelay; -} - -uint8_t AsyncServer::status(){ - if (!_pcb) - return 0; - return _pcb->state; -} - -err_t AsyncServer::_accept(tcp_pcb* pcb, err_t err){ - //http://savannah.nongnu.org/bugs/?43739 - if(NULL == pcb || ERR_OK != err){ - // https://www.nongnu.org/lwip/2_1_x/tcp_8h.html#a00517abce6856d6c82f0efebdafb734d - // An error code if there has been an error accepting. Only return ERR_ABRT - // if you have called tcp_abort from within the callback function! - // eg. 2.1.0 could call with error on failure to allocate pcb. - ASYNC_TCP_DEBUG("_accept:%s err: %ld\n", ((NULL == pcb) ? " NULL == pcb!," : ""), err); - ASYNC_TCP_ASSERT(ERR_ABRT != err); -#ifdef DEBUG_MORE - incEventCount(EE_ACCEPT_CB); -#endif - return ERR_OK; - } - - if(_connect_cb){ -#if ASYNC_TCP_SSL_ENABLED - if (_noDelay || _ssl_ctx) -#else - if (_noDelay) -#endif - tcp_nagle_disable(pcb); - else - tcp_nagle_enable(pcb); - -#if ASYNC_TCP_SSL_ENABLED - if(_ssl_ctx){ - if(tcp_ssl_has_client() || _pending){ - struct pending_pcb * new_item = (struct pending_pcb*)malloc(sizeof(struct pending_pcb)); - if(!new_item){ - ASYNC_TCP_DEBUG("### malloc new pending failed!\n"); - if(tcp_close(pcb) != ERR_OK){ - tcp_abort(pcb); - return ERR_ABRT; - } - return ERR_OK; - } - //1 ASYNC_TCP_DEBUG("### put to wait: %d\n", _clients_waiting); - new_item->pcb = pcb; - new_item->pb = NULL; - new_item->next = NULL; - tcp_setprio(_pcb, TCP_PRIO_MIN); - tcp_arg(pcb, this); - tcp_poll(pcb, &_s_poll, 1); - tcp_recv(pcb, &_s_recv); - - if(_pending == NULL){ - _pending = new_item; - } else { - struct pending_pcb * p = _pending; - while(p->next != NULL) - p = p->next; - p->next = new_item; - } - } else { - AsyncClient *c = new (std::nothrow) AsyncClient(pcb, _ssl_ctx); - if(c){ - ASYNC_TCP_DEBUG("_accept[%u]: SSL connected\n", c->getConnectionId()); - c->onConnect([this](void * arg, AsyncClient *c){ - (void)arg; - _connect_cb(_connect_cb_arg, c); - }, this); - } else { - ASYNC_TCP_DEBUG("_accept[_ssl_ctx]: new AsyncClient() failed, connection aborted!\n"); - if(tcp_close(pcb) != ERR_OK){ - tcp_abort(pcb); - return ERR_ABRT; - } - } - } - return ERR_OK; - } else { - AsyncClient *c = new (std::nothrow) AsyncClient(pcb, NULL); -#else - AsyncClient *c = new (std::nothrow) AsyncClient(pcb); -#endif - - if(c){ - auto errorTracker = c->getACErrorTracker(); -#ifdef DEBUG_MORE - errorTracker->onErrorEvent( - [](void *obj, size_t ee){ ((AsyncServer*)(obj))->incEventCount(ee); }, - this); -#endif - ASYNC_TCP_DEBUG("_accept[%u]: connected\n", errorTracker->getConnectionId()); - _connect_cb(_connect_cb_arg, c); - return errorTracker->getCallbackCloseError(); - } else { - ASYNC_TCP_DEBUG("_accept: new AsyncClient() failed, connection aborted!\n"); - if(tcp_close(pcb) != ERR_OK){ - tcp_abort(pcb); - return ERR_ABRT; - } - } -#if ASYNC_TCP_SSL_ENABLED - } -#endif - } - if(tcp_close(pcb) != ERR_OK){ - tcp_abort(pcb); - return ERR_ABRT; - } - return ERR_OK; -} - -err_t AsyncServer::_s_accept(void *arg, tcp_pcb* pcb, err_t err){ - return reinterpret_cast(arg)->_accept(pcb, err); -} - -#if ASYNC_TCP_SSL_ENABLED -err_t AsyncServer::_poll(tcp_pcb* pcb){ - err_t err = ERR_OK; - if(!tcp_ssl_has_client() && _pending){ - struct pending_pcb * p = _pending; - if(p->pcb == pcb){ - _pending = _pending->next; - } else { - while(p->next && p->next->pcb != pcb) p = p->next; - if(!p->next) return 0; - struct pending_pcb * b = p->next; - p->next = b->next; - p = b; - } - //1 ASYNC_TCP_DEBUG("### remove from wait: %d\n", _clients_waiting); - AsyncClient *c = new (std::nothrow) AsyncClient(pcb, _ssl_ctx); - if(c){ - c->onConnect([this](void * arg, AsyncClient *c){ - (void)arg; - _connect_cb(_connect_cb_arg, c); - }, this); - if(p->pb) { - auto errorTracker = c->getACErrorTracker(); - c->_recv(errorTracker, pcb, p->pb, 0); - err = errorTracker->getCallbackCloseError(); - } - } - // Should there be error handling for when "new AsynClient" fails?? - free(p); - } - return err; -} - -err_t AsyncServer::_recv(struct tcp_pcb *pcb, struct pbuf *pb, err_t err){ - (void)err; - if(!_pending) - return ERR_OK; - - struct pending_pcb * p; - - if(!pb){ - //1 ASYNC_TCP_DEBUG("### close from wait: %d\n", _clients_waiting); - p = _pending; - if(p->pcb == pcb){ - _pending = _pending->next; - } else { - while(p->next && p->next->pcb != pcb) p = p->next; - if(!p->next) return 0; - struct pending_pcb * b = p->next; - p->next = b->next; - p = b; - } - if(p->pb){ - pbuf_free(p->pb); - } - free(p); - size_t err = tcp_close(pcb); - if (err != ERR_OK) { - tcp_abort(pcb); - return ERR_ABRT; - } - } else { - //1 ASYNC_TCP_DEBUG("### wait _recv: %u %d\n", pb->tot_len, _clients_waiting); - p = _pending; - while(p && p->pcb != pcb) - p = p->next; - if(p){ - if(p->pb){ - pbuf_chain(p->pb, pb); - } else { - p->pb = pb; - } - } - } - return ERR_OK; -} - -int AsyncServer::_cert(const char *filename, uint8_t **buf){ - if(_file_cb){ - return _file_cb(_file_cb_arg, filename, buf); - } - *buf = 0; - return 0; -} - -int AsyncServer::_s_cert(void *arg, const char *filename, uint8_t **buf){ - return reinterpret_cast(arg)->_cert(filename, buf); -} - -err_t AsyncServer::_s_poll(void *arg, struct tcp_pcb *pcb){ - return reinterpret_cast(arg)->_poll(pcb); -} - -err_t AsyncServer::_s_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *pb, err_t err){ - return reinterpret_cast(arg)->_recv(pcb, pb, err); -} -#endif diff --git a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.h b/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.h deleted file mode 100644 index e0541ab..0000000 --- a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCP.h +++ /dev/null @@ -1,324 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef ASYNCTCP_H_ -#define ASYNCTCP_H_ - -#include -#include "IPAddress.h" -#include -#include - -extern "C" { - #include "lwip/init.h" - #include "lwip/err.h" - #include "lwip/pbuf.h" -}; - -class AsyncClient; -class AsyncServer; -class ACErrorTracker; - -#define ASYNC_MAX_ACK_TIME 5000 -#define ASYNC_WRITE_FLAG_COPY 0x01 //will allocate new buffer to hold the data while sending (else will hold reference to the data given) -#define ASYNC_WRITE_FLAG_MORE 0x02 //will not send PSH flag, meaning that there should be more data to be sent before the application should react. - -struct tcp_pcb; -struct ip_addr; -#if ASYNC_TCP_SSL_ENABLED -struct SSL_; -typedef struct SSL_ SSL; -struct SSL_CTX_; -typedef struct SSL_CTX_ SSL_CTX; -#endif - -typedef std::function AcConnectHandler; -typedef std::function AcAckHandler; -typedef std::function AcErrorHandler; -typedef std::function AcDataHandler; -typedef std::function AcPacketHandler; -typedef std::function AcTimeoutHandler; -typedef std::function AsNotifyHandler; - -enum error_events { - EE_OK = 0, - EE_ABORTED, // Callback or foreground aborted connections - EE_ERROR_CB, // Stack initiated aborts via error Callbacks. - EE_CONNECTED_CB, - EE_RECV_CB, - EE_ACCEPT_CB, - EE_MAX -}; -// DEBUG_MORE is for gathering more information on which CBs close events are -// occuring and count. -// #define DEBUG_MORE 1 -class ACErrorTracker { - private: - AsyncClient *_client; - err_t _close_error; - int _errored; -#if DEBUG_ESP_ASYNC_TCP - size_t _connectionId; -#endif -#ifdef DEBUG_MORE - AsNotifyHandler _error_event_cb; - void* _error_event_cb_arg; -#endif - - protected: - friend class AsyncClient; - friend class AsyncServer; -#ifdef DEBUG_MORE - void onErrorEvent(AsNotifyHandler cb, void *arg); -#endif -#if DEBUG_ESP_ASYNC_TCP - void setConnectionId(size_t id) { _connectionId=id;} - size_t getConnectionId(void) { return _connectionId;} -#endif - void setCloseError(err_t e); - void setErrored(size_t errorEvent); - err_t getCallbackCloseError(void); - void clearClient(void){ if (_client) _client = NULL;} - - public: - err_t getCloseError(void) const { return _close_error;} - bool hasClient(void) const { return (_client != NULL);} - ACErrorTracker(AsyncClient *c); - ~ACErrorTracker() {} -}; - -class AsyncClient { - protected: - friend class AsyncTCPbuffer; - friend class AsyncServer; - tcp_pcb* _pcb; - AcConnectHandler _connect_cb; - void* _connect_cb_arg; - AcConnectHandler _discard_cb; - void* _discard_cb_arg; - AcAckHandler _sent_cb; - void* _sent_cb_arg; - AcErrorHandler _error_cb; - void* _error_cb_arg; - AcDataHandler _recv_cb; - void* _recv_cb_arg; - AcPacketHandler _pb_cb; - void* _pb_cb_arg; - AcTimeoutHandler _timeout_cb; - void* _timeout_cb_arg; - AcConnectHandler _poll_cb; - void* _poll_cb_arg; - bool _pcb_busy; -#if ASYNC_TCP_SSL_ENABLED - bool _pcb_secure; - bool _handshake_done; -#endif - uint32_t _pcb_sent_at; - bool _close_pcb; - bool _ack_pcb; - uint32_t _tx_unacked_len; - uint32_t _tx_acked_len; - uint32_t _rx_ack_len; - uint32_t _rx_last_packet; - uint32_t _rx_since_timeout; - uint32_t _ack_timeout; - uint16_t _connect_port; - u8_t _recv_pbuf_flags; - std::shared_ptr _errorTracker; - - void _close(); - void _connected(std::shared_ptr& closeAbort, void* pcb, err_t err); - void _error(err_t err); -#if ASYNC_TCP_SSL_ENABLED - void _ssl_error(int8_t err); -#endif - void _poll(std::shared_ptr& closeAbort, tcp_pcb* pcb); - void _sent(std::shared_ptr& closeAbort, tcp_pcb* pcb, uint16_t len); -#if LWIP_VERSION_MAJOR == 1 - void _dns_found(struct ip_addr *ipaddr); -#else - void _dns_found(const ip_addr *ipaddr); -#endif - static err_t _s_poll(void *arg, struct tcp_pcb *tpcb); - static err_t _s_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, err_t err); - static void _s_error(void *arg, err_t err); - static err_t _s_sent(void *arg, struct tcp_pcb *tpcb, uint16_t len); - static err_t _s_connected(void* arg, void* tpcb, err_t err); -#if LWIP_VERSION_MAJOR == 1 - static void _s_dns_found(const char *name, struct ip_addr *ipaddr, void *arg); -#else - static void _s_dns_found(const char *name, const ip_addr *ipaddr, void *arg); -#endif -#if ASYNC_TCP_SSL_ENABLED - static void _s_data(void *arg, struct tcp_pcb *tcp, uint8_t * data, size_t len); - static void _s_handshake(void *arg, struct tcp_pcb *tcp, SSL *ssl); - static void _s_ssl_error(void *arg, struct tcp_pcb *tcp, int8_t err); -#endif - std::shared_ptr getACErrorTracker(void) const { return _errorTracker; }; - void setCloseError(err_t e) const { _errorTracker->setCloseError(e);} - - public: - AsyncClient* prev; - AsyncClient* next; - -#if ASYNC_TCP_SSL_ENABLED - AsyncClient(tcp_pcb* pcb = 0, SSL_CTX * ssl_ctx = NULL); -#else - AsyncClient(tcp_pcb* pcb = 0); -#endif - ~AsyncClient(); - - AsyncClient & operator=(const AsyncClient &other); - AsyncClient & operator+=(const AsyncClient &other); - - bool operator==(const AsyncClient &other); - - bool operator!=(const AsyncClient &other) { - return !(*this == other); - } -#if ASYNC_TCP_SSL_ENABLED - bool connect(IPAddress ip, uint16_t port, bool secure=false); - bool connect(const char* host, uint16_t port, bool secure=false); -#else - bool connect(IPAddress ip, uint16_t port); - bool connect(const char* host, uint16_t port); -#endif - void close(bool now = false); - void stop(); - void abort(); - bool free(); - - bool canSend();//ack is not pending - size_t space(); - size_t add(const char* data, size_t size, uint8_t apiflags=0);//add for sending - bool send();//send all data added with the method above - size_t ack(size_t len); //ack data that you have not acked using the method below - void ackLater(){ _ack_pcb = false; } //will not ack the current packet. Call from onData - bool isRecvPush(){ return !!(_recv_pbuf_flags & PBUF_FLAG_PUSH); } -#if DEBUG_ESP_ASYNC_TCP - size_t getConnectionId(void) const { return _errorTracker->getConnectionId();} -#endif -#if ASYNC_TCP_SSL_ENABLED - SSL *getSSL(); -#endif - - size_t write(const char* data); - size_t write(const char* data, size_t size, uint8_t apiflags=0); //only when canSend() == true - - uint8_t state(); - bool connecting(); - bool connected(); - bool disconnecting(); - bool disconnected(); - bool freeable();//disconnected or disconnecting - - uint16_t getMss(); - uint32_t getRxTimeout(); - void setRxTimeout(uint32_t timeout);//no RX data timeout for the connection in seconds - uint32_t getAckTimeout(); - void setAckTimeout(uint32_t timeout);//no ACK timeout for the last sent packet in milliseconds - void setNoDelay(bool nodelay); - bool getNoDelay(); - uint16_t getRemotePort(); - uint16_t getLocalPort(); - - IPAddress remoteIP(); - uint16_t remotePort(); - IPAddress localIP(); - uint16_t localPort(); - - void onConnect(AcConnectHandler cb, void* arg = 0); //on successful connect - void onDisconnect(AcConnectHandler cb, void* arg = 0); //disconnected - void onAck(AcAckHandler cb, void* arg = 0); //ack received - void onError(AcErrorHandler cb, void* arg = 0); //unsuccessful connect or error - void onData(AcDataHandler cb, void* arg = 0); //data received (called if onPacket is not used) - void onPacket(AcPacketHandler cb, void* arg = 0); //data received - void onTimeout(AcTimeoutHandler cb, void* arg = 0); //ack timeout - void onPoll(AcConnectHandler cb, void* arg = 0); //every 125ms when connected - void ackPacket(struct pbuf * pb); - - const char * errorToString(err_t error); - const char * stateToString(); - - void _recv(std::shared_ptr& closeAbort, tcp_pcb* pcb, pbuf* pb, err_t err); - err_t getCloseError(void) const { return _errorTracker->getCloseError();} -}; - -#if ASYNC_TCP_SSL_ENABLED -typedef std::function AcSSlFileHandler; -struct pending_pcb; -#endif - - -class AsyncServer { - protected: - uint16_t _port; - IPAddress _addr; - bool _noDelay; - tcp_pcb* _pcb; - AcConnectHandler _connect_cb; - void* _connect_cb_arg; -#if ASYNC_TCP_SSL_ENABLED - struct pending_pcb * _pending; - SSL_CTX * _ssl_ctx; - AcSSlFileHandler _file_cb; - void* _file_cb_arg; -#endif -#ifdef DEBUG_MORE - int _event_count[EE_MAX]; -#endif - - public: - - AsyncServer(IPAddress addr, uint16_t port); - AsyncServer(uint16_t port); - ~AsyncServer(); - void onClient(AcConnectHandler cb, void* arg); -#if ASYNC_TCP_SSL_ENABLED - void onSslFileRequest(AcSSlFileHandler cb, void* arg); - void beginSecure(const char *cert, const char *private_key_file, const char *password); -#endif - void begin(); - void end(); - void setNoDelay(bool nodelay); - bool getNoDelay(); - uint8_t status(); -#ifdef DEBUG_MORE - int getEventCount(size_t ee) const { return _event_count[ee];} -#endif - protected: - err_t _accept(tcp_pcb* newpcb, err_t err); - static err_t _s_accept(void *arg, tcp_pcb* newpcb, err_t err); -#ifdef DEBUG_MORE - int incEventCount(size_t ee) { return ++_event_count[ee];} -#endif -#if ASYNC_TCP_SSL_ENABLED - int _cert(const char *filename, uint8_t **buf); - err_t _poll(tcp_pcb* pcb); - err_t _recv(tcp_pcb *pcb, struct pbuf *pb, err_t err); - static int _s_cert(void *arg, const char *filename, uint8_t **buf); - static err_t _s_poll(void *arg, struct tcp_pcb *tpcb); - static err_t _s_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, err_t err); -#endif -}; - - -#endif /* ASYNCTCP_H_ */ diff --git a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.cpp b/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.cpp deleted file mode 100644 index d2261da..0000000 --- a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.cpp +++ /dev/null @@ -1,555 +0,0 @@ -/** - * @file ESPAsyncTCPbuffer.cpp - * @date 22.01.2016 - * @author Markus Sattler - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the Asynv TCP for ESP. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -#include -#include - -#include "ESPAsyncTCPbuffer.h" - - -AsyncTCPbuffer::AsyncTCPbuffer(AsyncClient* client) { - if(client == NULL) { - DEBUG_ASYNC_TCP("[A-TCP] client is null!!!\n"); - panic(); - } - - _client = client; - _TXbufferWrite = new (std::nothrow) cbuf(TCP_MSS); - _TXbufferRead = _TXbufferWrite; - _RXbuffer = new (std::nothrow) cbuf(100); - _RXmode = ATB_RX_MODE_FREE; - _rxSize = 0; - _rxTerminator = 0x00; - _rxReadBytesPtr = NULL; - _rxReadStringPtr = NULL; - _cbDisconnect = NULL; - - _cbRX = NULL; - _cbDone = NULL; - _attachCallbacks(); -} - -AsyncTCPbuffer::~AsyncTCPbuffer() { - if(_client) { - _client->close(); - } - - if(_RXbuffer) { - delete _RXbuffer; - _RXbuffer = NULL; - } - - if(_TXbufferWrite) { - // will be deleted in _TXbufferRead chain - _TXbufferWrite = NULL; - } - - if(_TXbufferRead) { - cbuf * next = _TXbufferRead->next; - delete _TXbufferRead; - while(next != NULL) { - _TXbufferRead = next; - next = _TXbufferRead->next; - delete _TXbufferRead; - } - _TXbufferRead = NULL; - } -} - -size_t AsyncTCPbuffer::write(String & data) { - return write(data.c_str(), data.length()); -} - -size_t AsyncTCPbuffer::write(uint8_t data) { - return write(&data, 1); -} - -size_t AsyncTCPbuffer::write(const char* data) { - return write((const uint8_t *) data, strlen(data)); -} - -size_t AsyncTCPbuffer::write(const char *data, size_t len) { - return write((const uint8_t *) data, len); -} - -/** - * write data in to buffer and try to send the data - * @param data - * @param len - * @return - */ -size_t AsyncTCPbuffer::write(const uint8_t *data, size_t len) { - if(_TXbufferWrite == NULL || _client == NULL || !_client->connected() || data == NULL || len == 0) { - return 0; - } - - size_t bytesLeft = len; - while(bytesLeft) { - size_t w = _TXbufferWrite->write((const char*) data, bytesLeft); - bytesLeft -= w; - data += w; - _sendBuffer(); - - // add new buffer since we have more data - if(_TXbufferWrite->full() && bytesLeft > 0) { - - // to less ram!!! - if(ESP.getFreeHeap() < 4096) { - DEBUG_ASYNC_TCP("[A-TCP] run out of Heap can not send all Data!\n"); - return (len - bytesLeft); - } - - cbuf * next = new (std::nothrow) cbuf(TCP_MSS); - if(next == NULL) { - DEBUG_ASYNC_TCP("[A-TCP] run out of Heap!\n"); - panic(); - } else { - DEBUG_ASYNC_TCP("[A-TCP] new cbuf\n"); - } - - // add new buffer to chain (current cbuf) - _TXbufferWrite->next = next; - - // move ptr for next data - _TXbufferWrite = next; - } - } - - return len; - -} - -/** - * wait until all data has send out - */ -void AsyncTCPbuffer::flush() { - while(!_TXbufferWrite->empty()) { - while(connected() && !_client->canSend()) { - delay(0); - } - if(!connected()) - return; - _sendBuffer(); - } -} - -void AsyncTCPbuffer::noCallback() { - _RXmode = ATB_RX_MODE_NONE; -} - -void AsyncTCPbuffer::readStringUntil(char terminator, String * str, AsyncTCPbufferDoneCb done) { - if(_client == NULL) { - return; - } - DEBUG_ASYNC_TCP("[A-TCP] readStringUntil terminator: %02X\n", terminator); - _RXmode = ATB_RX_MODE_NONE; - _cbDone = done; - _rxReadStringPtr = str; - _rxTerminator = terminator; - _rxSize = 0; - _RXmode = ATB_RX_MODE_TERMINATOR_STRING; -} - -/* - void AsyncTCPbuffer::readBytesUntil(char terminator, char *buffer, size_t length, AsyncTCPbufferDoneCb done) { - _RXmode = ATB_RX_MODE_NONE; - _cbDone = done; - _rxReadBytesPtr = (uint8_t *) buffer; - _rxTerminator = terminator; - _rxSize = length; - _RXmode = ATB_RX_MODE_TERMINATOR; - _handleRxBuffer(NULL, 0); - } - - void AsyncTCPbuffer::readBytesUntil(char terminator, uint8_t *buffer, size_t length, AsyncTCPbufferDoneCb done) { - readBytesUntil(terminator, (char *) buffer, length, done); - } - */ - -void AsyncTCPbuffer::readBytes(char *buffer, size_t length, AsyncTCPbufferDoneCb done) { - if(_client == NULL) { - return; - } - DEBUG_ASYNC_TCP("[A-TCP] readBytes length: %d\n", length); - _RXmode = ATB_RX_MODE_NONE; - _cbDone = done; - _rxReadBytesPtr = (uint8_t *) buffer; - _rxSize = length; - _RXmode = ATB_RX_MODE_READ_BYTES; -} - -void AsyncTCPbuffer::readBytes(uint8_t *buffer, size_t length, AsyncTCPbufferDoneCb done) { - readBytes((char *) buffer, length, done); -} - -void AsyncTCPbuffer::onData(AsyncTCPbufferDataCb cb) { - if(_client == NULL) { - return; - } - DEBUG_ASYNC_TCP("[A-TCP] onData\n"); - _RXmode = ATB_RX_MODE_NONE; - _cbDone = NULL; - _cbRX = cb; - _RXmode = ATB_RX_MODE_FREE; -} - -void AsyncTCPbuffer::onDisconnect(AsyncTCPbufferDisconnectCb cb) { - _cbDisconnect = cb; -} - -IPAddress AsyncTCPbuffer::remoteIP() { - if(!_client) { - return IPAddress(0U); - } - return _client->remoteIP(); -} - -uint16_t AsyncTCPbuffer::remotePort() { - if(!_client) { - return 0; - } - return _client->remotePort(); -} - -bool AsyncTCPbuffer::connected() { - if(!_client) { - return false; - } - return _client->connected(); -} - -void AsyncTCPbuffer::stop() { - - if(!_client) { - return; - } - _client->stop(); - _client = NULL; - - if(_cbDone) { - switch(_RXmode) { - case ATB_RX_MODE_READ_BYTES: - case ATB_RX_MODE_TERMINATOR: - case ATB_RX_MODE_TERMINATOR_STRING: - _RXmode = ATB_RX_MODE_NONE; - _cbDone(false, NULL); - break; - default: - break; - } - } - _RXmode = ATB_RX_MODE_NONE; -} - -void AsyncTCPbuffer::close() { - stop(); -} - - -///-------------------------------- - -/** - * attachCallbacks to AsyncClient class - */ -void AsyncTCPbuffer::_attachCallbacks() { - if(!_client) { - return; - } - DEBUG_ASYNC_TCP("[A-TCP] attachCallbacks\n"); - - _client->onPoll([](void *obj, AsyncClient* c) { - (void)c; - AsyncTCPbuffer* b = ((AsyncTCPbuffer*)(obj)); - if((b->_TXbufferRead != NULL) && !b->_TXbufferRead->empty()) { - b->_sendBuffer(); - } - // if(!b->_RXbuffer->empty()) { - // b->_handleRxBuffer(NULL, 0); - // } - }, this); - - _client->onAck([](void *obj, AsyncClient* c, size_t len, uint32_t time) { - (void)c; - (void)len; - (void)time; - DEBUG_ASYNC_TCP("[A-TCP] onAck\n"); - ((AsyncTCPbuffer*)(obj))->_sendBuffer(); - }, this); - - _client->onDisconnect([](void *obj, AsyncClient* c) { - DEBUG_ASYNC_TCP("[A-TCP] onDisconnect\n"); - AsyncTCPbuffer* b = ((AsyncTCPbuffer*)(obj)); - b->_client = NULL; - bool del = true; - if(b->_cbDisconnect) { - del = b->_cbDisconnect(b); - } - delete c; - if(del) { - delete b; - } - }, this); - - _client->onData([](void *obj, AsyncClient* c, void *buf, size_t len) { - (void)c; - AsyncTCPbuffer* b = ((AsyncTCPbuffer*)(obj)); - b->_rxData((uint8_t *)buf, len); - }, this); - - _client->onTimeout([](void *obj, AsyncClient* c, uint32_t time){ - (void)obj; - (void)time; - DEBUG_ASYNC_TCP("[A-TCP] onTimeout\n"); - c->close(); - }, this); - - DEBUG_ASYNC_TCP("[A-TCP] attachCallbacks Done.\n"); -} - -/** - * send TX buffer if possible - */ -void AsyncTCPbuffer::_sendBuffer() { - //DEBUG_ASYNC_TCP("[A-TCP] _sendBuffer...\n"); - size_t available = _TXbufferRead->available(); - if(available == 0 || _client == NULL || !_client->connected() || !_client->canSend()) { - return; - } - - while(connected() && (_client->space() > 0) && (_TXbufferRead->available() > 0) && _client->canSend()) { - - available = _TXbufferRead->available(); - - if(available > _client->space()) { - available = _client->space(); - } - - char *out = new (std::nothrow) char[available]; - if(out == NULL) { - DEBUG_ASYNC_TCP("[A-TCP] to less heap, try later.\n"); - return; - } - - // read data from buffer - _TXbufferRead->peek(out, available); - - // send data - size_t send = _client->write((const char*) out, available); - if(send != available) { - DEBUG_ASYNC_TCP("[A-TCP] write failed send: %d available: %d \n", send, available); - if(!connected()) { - DEBUG_ASYNC_TCP("[A-TCP] incomplete transfer, connection lost.\n"); - } - } - - // remove really send data from buffer - _TXbufferRead->remove(send); - - // if buffer is empty and there is a other buffer in chain delete the empty one - if(_TXbufferRead->available() == 0 && _TXbufferRead->next != NULL) { - cbuf * old = _TXbufferRead; - _TXbufferRead = _TXbufferRead->next; - delete old; - DEBUG_ASYNC_TCP("[A-TCP] delete cbuf\n"); - } - - delete out; - } - -} - -/** - * called on incoming data - * @param buf - * @param len - */ -void AsyncTCPbuffer::_rxData(uint8_t *buf, size_t len) { - if(!_client || !_client->connected()) { - DEBUG_ASYNC_TCP("[A-TCP] not connected!\n"); - return; - } - if(!_RXbuffer) { - DEBUG_ASYNC_TCP("[A-TCP] _rxData no _RXbuffer!\n"); - return; - } - DEBUG_ASYNC_TCP("[A-TCP] _rxData len: %d RXmode: %d\n", len, _RXmode); - - size_t handled = 0; - - if(_RXmode != ATB_RX_MODE_NONE) { - handled = _handleRxBuffer((uint8_t *) buf, len); - buf += handled; - len -= handled; - - // handle as much as possible before using the buffer - if(_RXbuffer->empty()) { - while(_RXmode != ATB_RX_MODE_NONE && handled != 0 && len > 0) { - handled = _handleRxBuffer(buf, len); - buf += handled; - len -= handled; - } - } - } - - if(len > 0) { - - if(_RXbuffer->room() < len) { - // to less space - DEBUG_ASYNC_TCP("[A-TCP] _rxData buffer full try resize\n"); - _RXbuffer->resizeAdd((len + _RXbuffer->room())); - - if(_RXbuffer->room() < len) { - DEBUG_ASYNC_TCP("[A-TCP] _rxData buffer to full can only handle %d!!!\n", _RXbuffer->room()); - } - } - - _RXbuffer->write((const char *) (buf), len); - } - - if(!_RXbuffer->empty() && _RXmode != ATB_RX_MODE_NONE) { - // handle as much as possible data in buffer - handled = _handleRxBuffer(NULL, 0); - while(_RXmode != ATB_RX_MODE_NONE && handled != 0) { - handled = _handleRxBuffer(NULL, 0); - } - } - - // clean up ram - if(_RXbuffer->empty() && _RXbuffer->room() != 100) { - _RXbuffer->resize(100); - } - -} - -/** - * - */ -size_t AsyncTCPbuffer::_handleRxBuffer(uint8_t *buf, size_t len) { - if(!_client || !_client->connected() || _RXbuffer == NULL) { - return 0; - } - - DEBUG_ASYNC_TCP("[A-TCP] _handleRxBuffer len: %d RXmode: %d\n", len, _RXmode); - - size_t BufferAvailable = _RXbuffer->available(); - size_t r = 0; - - if(_RXmode == ATB_RX_MODE_NONE) { - return 0; - } else if(_RXmode == ATB_RX_MODE_FREE) { - if(_cbRX == NULL) { - return 0; - } - - if(BufferAvailable > 0) { - uint8_t * b = new (std::nothrow) uint8_t[BufferAvailable]; - if(b == NULL){ - panic(); //TODO: What action should this be ? - } - _RXbuffer->peek((char *) b, BufferAvailable); - r = _cbRX(b, BufferAvailable); - _RXbuffer->remove(r); - } - - if(r == BufferAvailable && buf && (len > 0)) { - return _cbRX(buf, len); - } else { - return 0; - } - - } else if(_RXmode == ATB_RX_MODE_READ_BYTES) { - if(_rxReadBytesPtr == NULL || _cbDone == NULL) { - return 0; - } - - size_t newReadCount = 0; - - if(BufferAvailable) { - r = _RXbuffer->read((char *) _rxReadBytesPtr, _rxSize); - _rxSize -= r; - _rxReadBytesPtr += r; - } - - if(_RXbuffer->empty() && (len > 0) && buf) { - r = len; - if(r > _rxSize) { - r = _rxSize; - } - memcpy(_rxReadBytesPtr, buf, r); - _rxReadBytesPtr += r; - _rxSize -= r; - newReadCount += r; - } - - if(_rxSize == 0) { - _RXmode = ATB_RX_MODE_NONE; - _cbDone(true, NULL); - } - - // add left over bytes to Buffer - return newReadCount; - - } else if(_RXmode == ATB_RX_MODE_TERMINATOR) { - // TODO implement read terminator non string - - } else if(_RXmode == ATB_RX_MODE_TERMINATOR_STRING) { - if(_rxReadStringPtr == NULL || _cbDone == NULL) { - return 0; - } - - // handle Buffer - if(BufferAvailable > 0) { - while(!_RXbuffer->empty()) { - char c = _RXbuffer->read(); - if(c == _rxTerminator || c == 0x00) { - _RXmode = ATB_RX_MODE_NONE; - _cbDone(true, _rxReadStringPtr); - return 0; - } else { - (*_rxReadStringPtr) += c; - } - } - } - - if(_RXbuffer->empty() && (len > 0) && buf) { - size_t newReadCount = 0; - while(newReadCount < len) { - char c = (char) *buf; - buf++; - newReadCount++; - if(c == _rxTerminator || c == 0x00) { - _RXmode = ATB_RX_MODE_NONE; - _cbDone(true, _rxReadStringPtr); - return newReadCount; - } else { - (*_rxReadStringPtr) += c; - } - } - return newReadCount; - } - } - - return 0; -} diff --git a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.h b/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.h deleted file mode 100644 index 08a57c7..0000000 --- a/lib/ESPAsyncTCP-esphome/src/ESPAsyncTCPbuffer.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file ESPAsyncTCPbuffer.h - * @date 22.01.2016 - * @author Markus Sattler - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the Asynv TCP for ESP. - * - * 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 ESPASYNCTCPBUFFER_H_ -#define ESPASYNCTCPBUFFER_H_ - -//#define DEBUG_ASYNC_TCP(...) while(((U0S >> USTXC) & 0x7F) != 0x00); os_printf( __VA_ARGS__ ); while(((U0S >> USTXC) & 0x7F) != 0x00) -//#define DEBUG_ASYNC_TCP ASYNC_TCP_DEBUG -#ifndef DEBUG_ASYNC_TCP -#define DEBUG_ASYNC_TCP(...) -#endif - -#include -#include - -#include "ESPAsyncTCP.h" - - - -typedef enum { - ATB_RX_MODE_NONE, - ATB_RX_MODE_FREE, - ATB_RX_MODE_READ_BYTES, - ATB_RX_MODE_TERMINATOR, - ATB_RX_MODE_TERMINATOR_STRING -} atbRxMode_t; - -class AsyncTCPbuffer: public Print { - - public: - - typedef std::function AsyncTCPbufferDataCb; - typedef std::function AsyncTCPbufferDoneCb; - typedef std::function AsyncTCPbufferDisconnectCb; - - AsyncTCPbuffer(AsyncClient* c); - virtual ~AsyncTCPbuffer(); - - size_t write(String & data); - size_t write(uint8_t data); - size_t write(const char* data); - size_t write(const char *data, size_t len); - size_t write(const uint8_t *data, size_t len); - - void flush(); - - void noCallback(); - - void readStringUntil(char terminator, String * str, AsyncTCPbufferDoneCb done); - - // TODO implement read terminator non string - //void readBytesUntil(char terminator, char *buffer, size_t length, AsyncTCPbufferDoneCb done); - //void readBytesUntil(char terminator, uint8_t *buffer, size_t length, AsyncTCPbufferDoneCb done); - - void readBytes(char *buffer, size_t length, AsyncTCPbufferDoneCb done); - void readBytes(uint8_t *buffer, size_t length, AsyncTCPbufferDoneCb done); - - // TODO implement - // void setTimeout(size_t timeout); - - void onData(AsyncTCPbufferDataCb cb); - void onDisconnect(AsyncTCPbufferDisconnectCb cb); - - IPAddress remoteIP(); - uint16_t remotePort(); - IPAddress localIP(); - uint16_t localPort(); - - bool connected(); - - void stop(); - void close(); - - protected: - AsyncClient* _client; - cbuf * _TXbufferRead; - cbuf * _TXbufferWrite; - cbuf * _RXbuffer; - atbRxMode_t _RXmode; - size_t _rxSize; - char _rxTerminator; - uint8_t * _rxReadBytesPtr; - String * _rxReadStringPtr; - - AsyncTCPbufferDataCb _cbRX; - AsyncTCPbufferDoneCb _cbDone; - AsyncTCPbufferDisconnectCb _cbDisconnect; - - void _attachCallbacks(); - void _sendBuffer(); - void _on_close(); - void _rxData(uint8_t *buf, size_t len); - size_t _handleRxBuffer(uint8_t *buf, size_t len); - -}; - -#endif /* ESPASYNCTCPBUFFER_H_ */ diff --git a/lib/ESPAsyncTCP-esphome/src/SyncClient.cpp b/lib/ESPAsyncTCP-esphome/src/SyncClient.cpp deleted file mode 100644 index 8335358..0000000 --- a/lib/ESPAsyncTCP-esphome/src/SyncClient.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -#include "Arduino.h" -#include "SyncClient.h" -#include "ESPAsyncTCP.h" -#include "cbuf.h" -#include - -#define DEBUG_ESP_SYNC_CLIENT -#if defined(DEBUG_ESP_SYNC_CLIENT) && !defined(SYNC_CLIENT_DEBUG) -#define SYNC_CLIENT_DEBUG( format, ...) DEBUG_GENERIC_P("[SYNC_CLIENT]", format, ##__VA_ARGS__) -#endif -#ifndef SYNC_CLIENT_DEBUG -#define SYNC_CLIENT_DEBUG(...) do { (void)0;} while(false) -#endif - -/* - Without LWIP_NETIF_TX_SINGLE_PBUF, all tcp_writes default to "no copy". - Referenced data must be preserved and free-ed from the specified tcp_sent() - callback. Alternative, tcp_writes need to use the TCP_WRITE_FLAG_COPY - attribute. -*/ -static_assert(LWIP_NETIF_TX_SINGLE_PBUF, "Required, tcp_write() must always copy."); - -SyncClient::SyncClient(size_t txBufLen) - : _client(NULL) - , _tx_buffer(NULL) - , _tx_buffer_size(txBufLen) - , _rx_buffer(NULL) - , _ref(NULL) -{ - ref(); -} - -SyncClient::SyncClient(AsyncClient *client, size_t txBufLen) - : _client(client) - , _tx_buffer(new (std::nothrow) cbuf(txBufLen)) - , _tx_buffer_size(txBufLen) - , _rx_buffer(NULL) - , _ref(NULL) -{ - if(ref() > 0 && _client != NULL) - _attachCallbacks(); -} - -SyncClient::~SyncClient(){ - if (0 == unref()) - _release(); -} - -void SyncClient::_release(){ - if(_client != NULL){ - _client->onData(NULL, NULL); - _client->onAck(NULL, NULL); - _client->onPoll(NULL, NULL); - _client->abort(); - _client = NULL; - } - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } - while(_rx_buffer != NULL){ - cbuf *b = _rx_buffer; - _rx_buffer = _rx_buffer->next; - delete b; - } -} - -int SyncClient::ref(){ - if(_ref == NULL){ - _ref = new (std::nothrow) int; - if(_ref != NULL) - *_ref = 0; - else - return -1; - } - return (++*_ref); -} - -int SyncClient::unref(){ - int count = -1; - if (_ref != NULL) { - count = --*_ref; - if (0 == count) { - delete _ref; - _ref = NULL; - } - } - return count; -} - -#if ASYNC_TCP_SSL_ENABLED -int SyncClient::_connect(const IPAddress& ip, uint16_t port, bool secure){ -#else -int SyncClient::_connect(const IPAddress& ip, uint16_t port){ -#endif - if(connected()) - return 0; - if(_client != NULL) - delete _client; - - _client = new (std::nothrow) AsyncClient(); - if (_client == NULL) - return 0; - - _client->onConnect([](void *obj, AsyncClient *c){ ((SyncClient*)(obj))->_onConnect(c); }, this); - _attachCallbacks_Disconnect(); -#if ASYNC_TCP_SSL_ENABLED - if(_client->connect(ip, port, secure)){ -#else - if(_client->connect(ip, port)){ -#endif - while(_client != NULL && !_client->connected() && !_client->disconnecting()) - delay(1); - return connected(); - } - return 0; -} - -#if ASYNC_TCP_SSL_ENABLED -int SyncClient::connect(const char *host, uint16_t port, bool secure){ -#else -int SyncClient::connect(const char *host, uint16_t port){ -#endif - if(connected()) - return 0; - if(_client != NULL) - delete _client; - - _client = new (std::nothrow) AsyncClient(); - if (_client == NULL) - return 0; - - _client->onConnect([](void *obj, AsyncClient *c){ ((SyncClient*)(obj))->_onConnect(c); }, this); - _attachCallbacks_Disconnect(); -#if ASYNC_TCP_SSL_ENABLED - if(_client->connect(host, port, secure)){ -#else - if(_client->connect(host, port)){ -#endif - while(_client != NULL && !_client->connected() && !_client->disconnecting()) - delay(1); - return connected(); - } - return 0; -} -//#define SYNCCLIENT_NEW_OPERATOR_EQUAL -#ifdef SYNCCLIENT_NEW_OPERATOR_EQUAL -/* - New behavior for operator= - - Allow for the object to be placed on a queue and transfered to a new container - with buffers still in tact. Avoiding receive data drops. Transfers rx and tx - buffers. Supports return by value. - - Note, this is optional, the old behavior is the default. - -*/ -SyncClient & SyncClient::operator=(const SyncClient &other){ - int *rhsref = other._ref; - ++*rhsref; // Just in case the left and right side are the same object with different containers - if (0 == unref()) - _release(); - _ref = other._ref; - ref(); - --*rhsref; - // Why do I not test _tx_buffer for != NULL and free? - // I allow for the lh target container, to be a copy of an active - // connection. Thus we are just reusing the container. - // The above unref() handles releaseing the previous client of the container. - _tx_buffer_size = other._tx_buffer_size; - _tx_buffer = other._tx_buffer; - _client = other._client; - if (_client != NULL && _tx_buffer == NULL) - _tx_buffer = new (std::nothrow) cbuf(_tx_buffer_size); - - _rx_buffer = other._rx_buffer; - if(_client) - _attachCallbacks(); - return *this; -} -#else // ! SYNCCLIENT_NEW_OPERATOR_EQUAL -// This is the origianl logic with null checks -SyncClient & SyncClient::operator=(const SyncClient &other){ - if(_client != NULL){ - _client->abort(); - _client->free(); - _client = NULL; - } - _tx_buffer_size = other._tx_buffer_size; - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } - while(_rx_buffer != NULL){ - cbuf *b = _rx_buffer; - _rx_buffer = b->next; - delete b; - } - if(other._client != NULL) - _tx_buffer = new (std::nothrow) cbuf(other._tx_buffer_size); - - _client = other._client; - if(_client) - _attachCallbacks(); - - return *this; -} -#endif - -void SyncClient::setTimeout(uint32_t seconds){ - if(_client != NULL) - _client->setRxTimeout(seconds); -} - -uint8_t SyncClient::status(){ - if(_client == NULL) - return 0; - return _client->state(); -} - -uint8_t SyncClient::connected(){ - return (_client != NULL && _client->connected()); -} - -bool SyncClient::stop(unsigned int maxWaitMs){ - (void)maxWaitMs; - if(_client != NULL) - _client->close(true); - return true; -} - -size_t SyncClient::_sendBuffer(){ - if(_client == NULL || _tx_buffer == NULL) - return 0; - size_t available = _tx_buffer->available(); - if(!connected() || !_client->canSend() || available == 0) - return 0; - size_t sendable = _client->space(); - if(sendable < available) - available= sendable; - char *out = new (std::nothrow) char[available]; - if(out == NULL) - return 0; - - _tx_buffer->read(out, available); - size_t sent = _client->write(out, available); - delete[] out; - return sent; -} - -void SyncClient::_onData(void *data, size_t len){ - _client->ackLater(); - cbuf *b = new (std::nothrow) cbuf(len+1); - if(b != NULL){ - b->write((const char *)data, len); - if(_rx_buffer == NULL) - _rx_buffer = b; - else { - cbuf *p = _rx_buffer; - while(p->next != NULL) - p = p->next; - p->next = b; - } - } else { - // We ran out of memory. This fail causes lost receive data. - // The connection should be closed in a manner that conveys something - // bad/abnormal has happened to the connection. Hence, we abort the - // connection to avoid possible data corruption. - // Note, callbacks maybe called. - _client->abort(); - } -} - -void SyncClient::_onDisconnect(){ - if(_client != NULL){ - _client = NULL; - } - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } -} - -void SyncClient::_onConnect(AsyncClient *c){ - _client = c; - if(_tx_buffer != NULL){ - cbuf *b = _tx_buffer; - _tx_buffer = NULL; - delete b; - } - _tx_buffer = new (std::nothrow) cbuf(_tx_buffer_size); - _attachCallbacks_AfterConnected(); -} - -void SyncClient::_attachCallbacks(){ - _attachCallbacks_Disconnect(); - _attachCallbacks_AfterConnected(); -} - -void SyncClient::_attachCallbacks_AfterConnected(){ - _client->onAck([](void *obj, AsyncClient* c, size_t len, uint32_t time){ (void)c; (void)len; (void)time; ((SyncClient*)(obj))->_sendBuffer(); }, this); - _client->onData([](void *obj, AsyncClient* c, void *data, size_t len){ (void)c; ((SyncClient*)(obj))->_onData(data, len); }, this); - _client->onTimeout([](void *obj, AsyncClient* c, uint32_t time){ (void)obj; (void)time; c->close(); }, this); -} - -void SyncClient::_attachCallbacks_Disconnect(){ - _client->onDisconnect([](void *obj, AsyncClient* c){ ((SyncClient*)(obj))->_onDisconnect(); delete c; }, this); -} - -size_t SyncClient::write(uint8_t data){ - return write(&data, 1); -} - -size_t SyncClient::write(const uint8_t *data, size_t len){ - if(_tx_buffer == NULL || !connected()){ - return 0; - } - size_t toWrite = 0; - size_t toSend = len; - while(_tx_buffer->room() < toSend){ - toWrite = _tx_buffer->room(); - _tx_buffer->write((const char*)data, toWrite); - while(connected() && !_client->canSend()) - delay(0); - if(!connected()) - return 0; - _sendBuffer(); - toSend -= toWrite; - } - _tx_buffer->write((const char*)(data+(len - toSend)), toSend); - if(connected() && _client->canSend()) - _sendBuffer(); - return len; -} - -int SyncClient::available(){ - if(_rx_buffer == NULL) return 0; - size_t a = 0; - cbuf *b = _rx_buffer; - while(b != NULL){ - a += b->available(); - b = b->next; - } - return a; -} - -int SyncClient::peek(){ - if(_rx_buffer == NULL) return -1; - return _rx_buffer->peek(); -} - -int SyncClient::read(uint8_t *data, size_t len){ - if(_rx_buffer == NULL) return -1; - - size_t readSoFar = 0; - while(_rx_buffer != NULL && (len - readSoFar) >= _rx_buffer->available()){ - cbuf *b = _rx_buffer; - _rx_buffer = _rx_buffer->next; - size_t toRead = b->available(); - readSoFar += b->read((char*)(data+readSoFar), toRead); - if(connected()){ - _client->ack(b->size() - 1); - } - delete b; - } - if(_rx_buffer != NULL && readSoFar < len){ - readSoFar += _rx_buffer->read((char*)(data+readSoFar), (len - readSoFar)); - } - return readSoFar; -} - -int SyncClient::read(){ - uint8_t res = 0; - if(read(&res, 1) != 1) - return -1; - return res; -} - -bool SyncClient::flush(unsigned int maxWaitMs){ - (void)maxWaitMs; - if(_tx_buffer == NULL || !connected()) - return false; - if(_tx_buffer->available()){ - while(connected() && !_client->canSend()) - delay(0); - if(_client == NULL || _tx_buffer == NULL) - return false; - _sendBuffer(); - } - return true; -} diff --git a/lib/ESPAsyncTCP-esphome/src/SyncClient.h b/lib/ESPAsyncTCP-esphome/src/SyncClient.h deleted file mode 100644 index cb568de..0000000 --- a/lib/ESPAsyncTCP-esphome/src/SyncClient.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef SYNCCLIENT_H_ -#define SYNCCLIENT_H_ - -#include "Client.h" -// Needed for Arduino core releases prior to 2.5.0, because of changes -// made to accommodate Arduino core 2.5.0 -// CONST was 1st defined in Core 2.5.0 in IPAddress.h -#ifndef CONST -#define CONST -#endif -#include -class cbuf; -class AsyncClient; - -class SyncClient: public Client { - private: - AsyncClient *_client; - cbuf *_tx_buffer; - size_t _tx_buffer_size; - cbuf *_rx_buffer; - int *_ref; - - size_t _sendBuffer(); - void _onData(void *data, size_t len); - void _onConnect(AsyncClient *c); - void _onDisconnect(); - void _attachCallbacks(); - void _attachCallbacks_Disconnect(); - void _attachCallbacks_AfterConnected(); - void _release(); - - public: - SyncClient(size_t txBufLen = TCP_MSS); - SyncClient(AsyncClient *client, size_t txBufLen = TCP_MSS); - virtual ~SyncClient(); - - int ref(); - int unref(); - operator bool(){ return connected(); } - SyncClient & operator=(const SyncClient &other); - -#if ASYNC_TCP_SSL_ENABLED - int _connect(const IPAddress& ip, uint16_t port, bool secure); - int connect(CONST IPAddress& ip, uint16_t port, bool secure){ - return _connect(ip, port, secure); - } - int connect(IPAddress ip, uint16_t port, bool secure){ - return _connect(reinterpret_cast(ip), port, secure); - } - int connect(const char *host, uint16_t port, bool secure); - int connect(CONST IPAddress& ip, uint16_t port){ - return _connect(ip, port, false); - } - int connect(IPAddress ip, uint16_t port){ - return _connect(reinterpret_cast(ip), port, false); - } - int connect(const char *host, uint16_t port){ - return connect(host, port, false); - } -#else - int _connect(const IPAddress& ip, uint16_t port); - int connect(CONST IPAddress& ip, uint16_t port){ - return _connect(ip, port); - } - int connect(IPAddress ip, uint16_t port){ - return _connect(reinterpret_cast(ip), port); - } - int connect(const char *host, uint16_t port); -#endif - void setTimeout(uint32_t seconds); - - uint8_t status(); - uint8_t connected(); - - bool stop(unsigned int maxWaitMs); - bool flush(unsigned int maxWaitMs); - void stop() { (void)stop(0);} - void flush() { (void)flush(0);} - size_t write(uint8_t data); - size_t write(const uint8_t *data, size_t len); - - int available(); - int peek(); - int read(); - int read(uint8_t *data, size_t len); -}; - -#endif /* SYNCCLIENT_H_ */ diff --git a/lib/ESPAsyncTCP-esphome/src/async_config.h b/lib/ESPAsyncTCP-esphome/src/async_config.h deleted file mode 100644 index 0ce336a..0000000 --- a/lib/ESPAsyncTCP-esphome/src/async_config.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef LIBRARIES_ESPASYNCTCP_SRC_ASYNC_CONFIG_H_ -#define LIBRARIES_ESPASYNCTCP_SRC_ASYNC_CONFIG_H_ - -#ifndef ASYNC_TCP_SSL_ENABLED -#define ASYNC_TCP_SSL_ENABLED 0 -#endif - -#ifndef TCP_MSS -// May have been definded as a -DTCP_MSS option on the compile line or not. -// Arduino core 2.3.0 or earlier does not do the -DTCP_MSS option. -// Later versions may set this option with info from board.txt. -// However, Core 2.4.0 and up board.txt does not define TCP_MSS for lwIP v1.4 -#define TCP_MSS (1460) -#endif - -// #define ASYNC_TCP_DEBUG(...) ets_printf(__VA_ARGS__) -// #define TCP_SSL_DEBUG(...) ets_printf(__VA_ARGS__) -// #define ASYNC_TCP_ASSERT( a ) do{ if(!(a)){ets_printf("ASSERT: %s %u \n", __FILE__, __LINE__);}}while(0) - -// Starting with Arduino Core 2.4.0 and up the define of DEBUG_ESP_PORT -// can be handled through the Arduino IDE Board options instead of here. -// #define DEBUG_ESP_PORT Serial -// #define DEBUG_ESP_ASYNC_TCP 1 -// #define DEBUG_ESP_TCP_SSL 1 - -#ifndef DEBUG_SKIP__DEBUG_PRINT_MACROS - -#include - -#ifndef ASYNC_TCP_ASSERT -#define ASYNC_TCP_ASSERT(...) do { (void)0;} while(false) -#endif -#ifndef ASYNC_TCP_DEBUG -#define ASYNC_TCP_DEBUG(...) do { (void)0;} while(false) -#endif -#ifndef TCP_SSL_DEBUG -#define TCP_SSL_DEBUG(...) do { (void)0;} while(false) -#endif - -#endif - -#endif /* LIBRARIES_ESPASYNCTCP_SRC_ASYNC_CONFIG_H_ */ diff --git a/lib/ESPAsyncTCP-esphome/src/tcp_axtls.c b/lib/ESPAsyncTCP-esphome/src/tcp_axtls.c deleted file mode 100644 index f026b5f..0000000 --- a/lib/ESPAsyncTCP-esphome/src/tcp_axtls.c +++ /dev/null @@ -1,613 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -/* - * Compatibility for AxTLS with LWIP raw tcp mode (http://lwip.wikia.com/wiki/Raw/TCP) - * Original Code and Inspiration: Slavey Karadzhov - */ - -// To handle all the definitions needed for debug printing, we need to delay -// macro definitions till later. -#define DEBUG_SKIP__DEBUG_PRINT_MACROS 1 -#include -#undef DEBUG_SKIP__DEBUG_PRINT_MACROS - -#if ASYNC_TCP_SSL_ENABLED - -#include "lwip/opt.h" -#include "lwip/tcp.h" -#include "lwip/inet.h" -#include -#include -#include -#include -#include - -// ets_uart_printf is defined in esp8266_undocumented.h, in newer Arduino ESP8266 Core. -extern int ets_uart_printf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); -#include -#ifndef TCP_SSL_DEBUG -#define TCP_SSL_DEBUG(...) do { (void)0;} while(false) -#endif - -uint8_t * default_private_key = NULL; -uint16_t default_private_key_len = 0; - -uint8_t * default_certificate = NULL; -uint16_t default_certificate_len = 0; - -static uint8_t _tcp_ssl_has_client = 0; - -SSL_CTX * tcp_ssl_new_server_ctx(const char *cert, const char *private_key_file, const char *password){ - uint32_t options = SSL_CONNECT_IN_PARTS; - SSL_CTX *ssl_ctx; - - if(private_key_file){ - options |= SSL_NO_DEFAULT_KEY; - } - - if ((ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_SVR_SESS)) == NULL){ - TCP_SSL_DEBUG("tcp_ssl_new_server_ctx: failed to allocate context\n"); - return NULL; - } - - if (private_key_file){ - int obj_type = SSL_OBJ_RSA_KEY; - if (strstr(private_key_file, ".p8")) - obj_type = SSL_OBJ_PKCS8; - else if (strstr(private_key_file, ".p12")) - obj_type = SSL_OBJ_PKCS12; - - if (ssl_obj_load(ssl_ctx, obj_type, private_key_file, password)){ - TCP_SSL_DEBUG("tcp_ssl_new_server_ctx: load private key '%s' failed\n", private_key_file); - return NULL; - } - } - - if (cert){ - if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, cert, NULL)){ - TCP_SSL_DEBUG("tcp_ssl_new_server_ctx: load certificate '%s' failed\n", cert); - return NULL; - } - } - return ssl_ctx; -} - -struct tcp_ssl_pcb { - struct tcp_pcb *tcp; - int fd; - SSL_CTX* ssl_ctx; - SSL *ssl; - uint8_t type; - int handshake; - void * arg; - tcp_ssl_data_cb_t on_data; - tcp_ssl_handshake_cb_t on_handshake; - tcp_ssl_error_cb_t on_error; - int last_wr; - struct pbuf *tcp_pbuf; - int pbuf_offset; - struct tcp_ssl_pcb * next; -}; - -typedef struct tcp_ssl_pcb tcp_ssl_t; - -static tcp_ssl_t * tcp_ssl_array = NULL; -static int tcp_ssl_next_fd = 0; - -uint8_t tcp_ssl_has_client(){ - return _tcp_ssl_has_client; -} - -tcp_ssl_t * tcp_ssl_new(struct tcp_pcb *tcp) { - - if(tcp_ssl_next_fd < 0){ - tcp_ssl_next_fd = 0;//overflow - } - - tcp_ssl_t * new_item = (tcp_ssl_t*)malloc(sizeof(tcp_ssl_t)); - if(!new_item){ - TCP_SSL_DEBUG("tcp_ssl_new: failed to allocate tcp_ssl\n"); - return NULL; - } - - new_item->tcp = tcp; - new_item->handshake = SSL_NOT_OK; - new_item->arg = NULL; - new_item->on_data = NULL; - new_item->on_handshake = NULL; - new_item->on_error = NULL; - new_item->tcp_pbuf = NULL; - new_item->pbuf_offset = 0; - new_item->next = NULL; - new_item->ssl_ctx = NULL; - new_item->ssl = NULL; - new_item->type = TCP_SSL_TYPE_CLIENT; - new_item->fd = tcp_ssl_next_fd++; - - if(tcp_ssl_array == NULL){ - tcp_ssl_array = new_item; - } else { - tcp_ssl_t * item = tcp_ssl_array; - while(item->next != NULL) - item = item->next; - item->next = new_item; - } - - TCP_SSL_DEBUG("tcp_ssl_new: %d\n", new_item->fd); - return new_item; -} - -tcp_ssl_t* tcp_ssl_get(struct tcp_pcb *tcp) { - if(tcp == NULL) { - return NULL; - } - tcp_ssl_t * item = tcp_ssl_array; - while(item && item->tcp != tcp){ - item = item->next; - } - return item; -} - -int tcp_ssl_new_client(struct tcp_pcb *tcp){ - SSL_CTX* ssl_ctx; - tcp_ssl_t * tcp_ssl; - - if(tcp == NULL) { - return -1; - } - - if(tcp_ssl_get(tcp) != NULL){ - TCP_SSL_DEBUG("tcp_ssl_new_client: tcp_ssl already exists\n"); - return -1; - } - - ssl_ctx = ssl_ctx_new(SSL_CONNECT_IN_PARTS | SSL_SERVER_VERIFY_LATER, 1); - if(ssl_ctx == NULL){ - TCP_SSL_DEBUG("tcp_ssl_new_client: failed to allocate ssl context\n"); - return -1; - } - - tcp_ssl = tcp_ssl_new(tcp); - if(tcp_ssl == NULL){ - ssl_ctx_free(ssl_ctx); - return -1; - } - - tcp_ssl->ssl_ctx = ssl_ctx; - - tcp_ssl->ssl = ssl_client_new(ssl_ctx, tcp_ssl->fd, NULL, 0, NULL); - if(tcp_ssl->ssl == NULL){ - TCP_SSL_DEBUG("tcp_ssl_new_client: failed to allocate ssl\n"); - tcp_ssl_free(tcp); - return -1; - } - - return tcp_ssl->fd; -} - -int tcp_ssl_new_server(struct tcp_pcb *tcp, SSL_CTX* ssl_ctx){ - tcp_ssl_t * tcp_ssl; - - if(tcp == NULL) { - return -1; - } - - if(ssl_ctx == NULL){ - return -1; - } - - if(tcp_ssl_get(tcp) != NULL){ - TCP_SSL_DEBUG("tcp_ssl_new_server: tcp_ssl already exists\n"); - return -1; - } - - tcp_ssl = tcp_ssl_new(tcp); - if(tcp_ssl == NULL){ - return -1; - } - - tcp_ssl->type = TCP_SSL_TYPE_SERVER; - tcp_ssl->ssl_ctx = ssl_ctx; - - _tcp_ssl_has_client = 1; - tcp_ssl->ssl = ssl_server_new(ssl_ctx, tcp_ssl->fd); - if(tcp_ssl->ssl == NULL){ - TCP_SSL_DEBUG("tcp_ssl_new_server: failed to allocate ssl\n"); - tcp_ssl_free(tcp); - return -1; - } - - return tcp_ssl->fd; -} - -int tcp_ssl_free(struct tcp_pcb *tcp) { - - if(tcp == NULL) { - return -1; - } - - tcp_ssl_t * item = tcp_ssl_array; - - if(item->tcp == tcp){ - tcp_ssl_array = tcp_ssl_array->next; - if(item->tcp_pbuf != NULL){ - pbuf_free(item->tcp_pbuf); - } - TCP_SSL_DEBUG("tcp_ssl_free: %d\n", item->fd); - if(item->ssl) - ssl_free(item->ssl); - if(item->type == TCP_SSL_TYPE_CLIENT && item->ssl_ctx) - ssl_ctx_free(item->ssl_ctx); - if(item->type == TCP_SSL_TYPE_SERVER) - _tcp_ssl_has_client = 0; - free(item); - return 0; - } - - while(item->next && item->next->tcp != tcp) - item = item->next; - - if(item->next == NULL){ - return ERR_TCP_SSL_INVALID_CLIENTFD_DATA;//item not found - } - - tcp_ssl_t * i = item->next; - item->next = i->next; - if(i->tcp_pbuf != NULL){ - pbuf_free(i->tcp_pbuf); - } - TCP_SSL_DEBUG("tcp_ssl_free: %d\n", i->fd); - if(i->ssl) - ssl_free(i->ssl); - if(i->type == TCP_SSL_TYPE_CLIENT && i->ssl_ctx) - ssl_ctx_free(i->ssl_ctx); - if(i->type == TCP_SSL_TYPE_SERVER) - _tcp_ssl_has_client = 0; - free(i); - return 0; -} - -#ifdef AXTLS_2_0_0_SNDBUF -int tcp_ssl_sndbuf(struct tcp_pcb *tcp){ - int expected; - int available; - int result = -1; - - if(tcp == NULL) { - return result; - } - tcp_ssl_t * tcp_ssl = tcp_ssl_get(tcp); - if(!tcp_ssl){ - TCP_SSL_DEBUG("tcp_ssl_sndbuf: tcp_ssl is NULL\n"); - return result; - } - available = tcp_sndbuf(tcp); - if(!available){ - TCP_SSL_DEBUG("tcp_ssl_sndbuf: tcp_sndbuf is zero\n"); - return 0; - } - result = available; - while((expected = ssl_calculate_write_length(tcp_ssl->ssl, result)) > available){ - result -= (expected - available) + 4; - } - - if(expected > 0){ - //TCP_SSL_DEBUG("tcp_ssl_sndbuf: tcp_sndbuf is %d from %d\n", result, available); - return result; - } - - return 0; -} -#endif - -int tcp_ssl_write(struct tcp_pcb *tcp, uint8_t *data, size_t len) { - if(tcp == NULL) { - return -1; - } - tcp_ssl_t * tcp_ssl = tcp_ssl_get(tcp); - if(!tcp_ssl){ - TCP_SSL_DEBUG("tcp_ssl_write: tcp_ssl is NULL\n"); - return 0; - } - tcp_ssl->last_wr = 0; - -#ifdef AXTLS_2_0_0_SNDBUF - int expected_len = ssl_calculate_write_length(tcp_ssl->ssl, len); - int available_len = tcp_sndbuf(tcp); - if(expected_len < 0 || expected_len > available_len){ - TCP_SSL_DEBUG("tcp_ssl_write: data will not fit! %u < %d(%u)\r\n", available_len, expected_len, len); - return -1; - } -#endif - - int rc = ssl_write(tcp_ssl->ssl, data, len); - - //TCP_SSL_DEBUG("tcp_ssl_write: %u -> %d (%d)\r\n", len, tcp_ssl->last_wr, rc); - - if (rc < 0){ - if(rc != SSL_CLOSE_NOTIFY) { - TCP_SSL_DEBUG("tcp_ssl_write error: %d\r\n", rc); - } - return rc; - } - - return tcp_ssl->last_wr; -} - -/** - * Reads data from the SSL over TCP stream. Returns decrypted data. - * @param tcp_pcb *tcp - pointer to the raw tcp object - * @param pbuf *p - pointer to the buffer with the TCP packet data - * - * @return int - * 0 - when everything is fine but there are no symbols to process yet - * < 0 - when there is an error - * > 0 - the length of the clear text characters that were read - */ -int tcp_ssl_read(struct tcp_pcb *tcp, struct pbuf *p) { - if(tcp == NULL) { - return -1; - } - tcp_ssl_t* fd_data = NULL; - - int read_bytes = 0; - int total_bytes = 0; - uint8_t *read_buf; - - fd_data = tcp_ssl_get(tcp); - if(fd_data == NULL) { - TCP_SSL_DEBUG("tcp_ssl_read: tcp_ssl is NULL\n"); - return ERR_TCP_SSL_INVALID_CLIENTFD_DATA; - } - - if(p == NULL) { - TCP_SSL_DEBUG("tcp_ssl_read:p == NULL\n"); - return ERR_TCP_SSL_INVALID_DATA; - } - - //TCP_SSL_DEBUG("READY TO READ SOME DATA\n"); - - fd_data->tcp_pbuf = p; - fd_data->pbuf_offset = 0; - - do { - read_bytes = ssl_read(fd_data->ssl, &read_buf); - TCP_SSL_DEBUG("tcp_ssl_ssl_read: %d\n", read_bytes); - - if(read_bytes < SSL_OK) { - if(read_bytes != SSL_CLOSE_NOTIFY) { - TCP_SSL_DEBUG("tcp_ssl_read: read error: %d\n", read_bytes); - } - total_bytes = read_bytes; - break; - } else if(read_bytes > 0){ - if(fd_data->on_data){ - fd_data->on_data(fd_data->arg, tcp, read_buf, read_bytes); - // fd_data may have been freed in callback - fd_data = tcp_ssl_get(tcp); - if(NULL == fd_data) - return SSL_CLOSE_NOTIFY; - } - total_bytes+= read_bytes; - } else { - if(fd_data->handshake != SSL_OK) { - // fd_data may be freed in callbacks. - int handshake = fd_data->handshake = ssl_handshake_status(fd_data->ssl); - if(handshake == SSL_OK){ - TCP_SSL_DEBUG("tcp_ssl_read: handshake OK\n"); - if(fd_data->on_handshake) - fd_data->on_handshake(fd_data->arg, fd_data->tcp, fd_data->ssl); - fd_data = tcp_ssl_get(tcp); - if(NULL == fd_data) - return SSL_CLOSE_NOTIFY; - } else if(handshake != SSL_NOT_OK){ - TCP_SSL_DEBUG("tcp_ssl_read: handshake error: %d\n", handshake); - if(fd_data->on_error) - fd_data->on_error(fd_data->arg, fd_data->tcp, handshake); - return handshake; - // With current code APP gets called twice at onError handler. - // Once here and again after return when handshake != SSL_CLOSE_NOTIFY. - // As always APP must never free resources at onError only at onDisconnect. - } - } - } - } while (p->tot_len - fd_data->pbuf_offset > 0); - - tcp_recved(tcp, p->tot_len); - fd_data->tcp_pbuf = NULL; - pbuf_free(p); - - return total_bytes; -} - -SSL * tcp_ssl_get_ssl(struct tcp_pcb *tcp){ - tcp_ssl_t * tcp_ssl = tcp_ssl_get(tcp); - if(tcp_ssl){ - return tcp_ssl->ssl; - } - return NULL; -} - -bool tcp_ssl_has(struct tcp_pcb *tcp){ - return tcp_ssl_get(tcp) != NULL; -} - -int tcp_ssl_is_server(struct tcp_pcb *tcp){ - tcp_ssl_t * tcp_ssl = tcp_ssl_get(tcp); - if(tcp_ssl){ - return tcp_ssl->type; - } - return -1; -} - -void tcp_ssl_arg(struct tcp_pcb *tcp, void * arg){ - tcp_ssl_t * item = tcp_ssl_get(tcp); - if(item) { - item->arg = arg; - } -} - -void tcp_ssl_data(struct tcp_pcb *tcp, tcp_ssl_data_cb_t arg){ - tcp_ssl_t * item = tcp_ssl_get(tcp); - if(item) { - item->on_data = arg; - } -} - -void tcp_ssl_handshake(struct tcp_pcb *tcp, tcp_ssl_handshake_cb_t arg){ - tcp_ssl_t * item = tcp_ssl_get(tcp); - if(item) { - item->on_handshake = arg; - } -} - -void tcp_ssl_err(struct tcp_pcb *tcp, tcp_ssl_error_cb_t arg){ - tcp_ssl_t * item = tcp_ssl_get(tcp); - if(item) { - item->on_error = arg; - } -} - -static tcp_ssl_file_cb_t _tcp_ssl_file_cb = NULL; -static void * _tcp_ssl_file_arg = NULL; - -void tcp_ssl_file(tcp_ssl_file_cb_t cb, void * arg){ - _tcp_ssl_file_cb = cb; - _tcp_ssl_file_arg = arg; -} - -int ax_get_file(const char *filename, uint8_t **buf) { - //TCP_SSL_DEBUG("ax_get_file: %s\n", filename); - if(_tcp_ssl_file_cb){ - return _tcp_ssl_file_cb(_tcp_ssl_file_arg, filename, buf); - } - *buf = 0; - return 0; -} - -tcp_ssl_t* tcp_ssl_get_by_fd(int fd) { - tcp_ssl_t * item = tcp_ssl_array; - while(item && item->fd != fd){ - item = item->next; - } - return item; -} -/* - * The LWIP tcp raw version of the SOCKET_WRITE(A, B, C) - */ -int ax_port_write(int fd, uint8_t *data, uint16_t len) { - tcp_ssl_t *fd_data = NULL; - int tcp_len = 0; - err_t err = ERR_OK; - - //TCP_SSL_DEBUG("ax_port_write: %d, %d\n", fd, len); - - fd_data = tcp_ssl_get_by_fd(fd); - if(fd_data == NULL) { - //TCP_SSL_DEBUG("ax_port_write: tcp_ssl[%d] is NULL\n", fd); - return ERR_MEM; - } - - if (data == NULL || len == 0) { - return 0; - } - - if (tcp_sndbuf(fd_data->tcp) < len) { - tcp_len = tcp_sndbuf(fd_data->tcp); - if(tcp_len == 0) { - TCP_SSL_DEBUG("ax_port_write: tcp_sndbuf is zero: %d\n", len); - return ERR_MEM; - } - } else { - tcp_len = len; - } - - if (tcp_len > 2 * fd_data->tcp->mss) { - tcp_len = 2 * fd_data->tcp->mss; - } - - err = tcp_write(fd_data->tcp, data, tcp_len, TCP_WRITE_FLAG_COPY); - if(err < ERR_OK) { - if (err == ERR_MEM) { - TCP_SSL_DEBUG("ax_port_write: No memory %d (%d)\n", tcp_len, len); - return err; - } - TCP_SSL_DEBUG("ax_port_write: tcp_write error: %ld\n", err); - return err; - } else if (err == ERR_OK) { - //TCP_SSL_DEBUG("ax_port_write: tcp_output: %d / %d\n", tcp_len, len); - err = tcp_output(fd_data->tcp); - if(err != ERR_OK) { - TCP_SSL_DEBUG("ax_port_write: tcp_output err: %ld\n", err); - return err; - } - } - - fd_data->last_wr += tcp_len; - - return tcp_len; -} - -/* - * The LWIP tcp raw version of the SOCKET_READ(A, B, C) - */ -int ax_port_read(int fd, uint8_t *data, int len) { - tcp_ssl_t *fd_data = NULL; - uint8_t *read_buf = NULL; - uint8_t *pread_buf = NULL; - u16_t recv_len = 0; - - //TCP_SSL_DEBUG("ax_port_read: %d, %d\n", fd, len); - - fd_data = tcp_ssl_get_by_fd(fd); - if (fd_data == NULL) { - TCP_SSL_DEBUG("ax_port_read: tcp_ssl[%d] is NULL\n", fd); - return ERR_TCP_SSL_INVALID_CLIENTFD_DATA; - } - - if(fd_data->tcp_pbuf == NULL || fd_data->tcp_pbuf->tot_len == 0) { - return 0; - } - - read_buf =(uint8_t*)calloc(fd_data->tcp_pbuf->len + 1, sizeof(uint8_t)); - pread_buf = read_buf; - if (pread_buf != NULL){ - recv_len = pbuf_copy_partial(fd_data->tcp_pbuf, read_buf, len, fd_data->pbuf_offset); - fd_data->pbuf_offset += recv_len; - } - - if (recv_len != 0) { - memcpy(data, read_buf, recv_len); - } - - if(len < recv_len) { - TCP_SSL_DEBUG("ax_port_read: got %d bytes more than expected\n", recv_len - len); - } - - free(pread_buf); - pread_buf = NULL; - - return recv_len; -} - -void ax_wdt_feed() {} - -#endif diff --git a/lib/ESPAsyncTCP-esphome/src/tcp_axtls.h b/lib/ESPAsyncTCP-esphome/src/tcp_axtls.h deleted file mode 100644 index 118e36f..0000000 --- a/lib/ESPAsyncTCP-esphome/src/tcp_axtls.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - Asynchronous TCP library for Espressif MCUs - - Copyright (c) 2016 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -/* - * Compatibility for AxTLS with LWIP raw tcp mode (http://lwip.wikia.com/wiki/Raw/TCP) - * Original Code and Inspiration: Slavey Karadzhov - */ - -#ifndef LWIPR_COMPAT_H -#define LWIPR_COMPAT_H - -#include - -#if ASYNC_TCP_SSL_ENABLED - -#include "lwipopts.h" -/* - * All those functions will run only if LWIP tcp raw mode is used - */ -#if LWIP_RAW==1 - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include "include/ssl.h" - -#define ERR_TCP_SSL_INVALID_SSL -101 -#define ERR_TCP_SSL_INVALID_TCP -102 -#define ERR_TCP_SSL_INVALID_CLIENTFD -103 -#define ERR_TCP_SSL_INVALID_CLIENTFD_DATA -104 -#define ERR_TCP_SSL_INVALID_DATA -105 - -#define TCP_SSL_TYPE_CLIENT 0 -#define TCP_SSL_TYPE_SERVER 1 - -#define tcp_ssl_ssl_write(A, B, C) tcp_ssl_write(A, B, C) -#define tcp_ssl_ssl_read(A, B) tcp_ssl_read(A, B) - -typedef void (* tcp_ssl_data_cb_t)(void *arg, struct tcp_pcb *tcp, uint8_t * data, size_t len); -typedef void (* tcp_ssl_handshake_cb_t)(void *arg, struct tcp_pcb *tcp, SSL *ssl); -typedef void (* tcp_ssl_error_cb_t)(void *arg, struct tcp_pcb *tcp, int8_t error); -typedef int (* tcp_ssl_file_cb_t)(void *arg, const char *filename, uint8_t **buf); - -uint8_t tcp_ssl_has_client(); - -int tcp_ssl_new_client(struct tcp_pcb *tcp); - -SSL_CTX * tcp_ssl_new_server_ctx(const char *cert, const char *private_key_file, const char *password); -int tcp_ssl_new_server(struct tcp_pcb *tcp, SSL_CTX* ssl_ctx); -int tcp_ssl_is_server(struct tcp_pcb *tcp); - -int tcp_ssl_free(struct tcp_pcb *tcp); -int tcp_ssl_read(struct tcp_pcb *tcp, struct pbuf *p); - -#ifdef AXTLS_2_0_0_SNDBUF -int tcp_ssl_sndbuf(struct tcp_pcb *tcp); -#endif - -int tcp_ssl_write(struct tcp_pcb *tcp, uint8_t *data, size_t len); - -void tcp_ssl_file(tcp_ssl_file_cb_t cb, void * arg); - -void tcp_ssl_arg(struct tcp_pcb *tcp, void * arg); -void tcp_ssl_data(struct tcp_pcb *tcp, tcp_ssl_data_cb_t arg); -void tcp_ssl_handshake(struct tcp_pcb *tcp, tcp_ssl_handshake_cb_t arg); -void tcp_ssl_err(struct tcp_pcb *tcp, tcp_ssl_error_cb_t arg); - -SSL * tcp_ssl_get_ssl(struct tcp_pcb *tcp); -bool tcp_ssl_has(struct tcp_pcb *tcp); - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_RAW==1 */ - -#endif /* ASYNC_TCP_SSL_ENABLED */ - -#endif /* LWIPR_COMPAT_H */ diff --git a/lib/ESPAsyncTCP-esphome/ssl/gen_server_cert.sh b/lib/ESPAsyncTCP-esphome/ssl/gen_server_cert.sh deleted file mode 100644 index fd749ed..0000000 --- a/lib/ESPAsyncTCP-esphome/ssl/gen_server_cert.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash - -cat > ca_cert.conf << EOF -[ req ] -distinguished_name = req_distinguished_name -prompt = no - -[ req_distinguished_name ] - O = Espressif Systems -EOF - -openssl genrsa -out axTLS.ca_key.pem 2048 -openssl req -new -config ./ca_cert.conf -key axTLS.ca_key.pem -out axTLS.ca_x509.req -openssl x509 -req -sha1 -days 5000 -signkey axTLS.ca_key.pem -CAkey axTLS.ca_key.pem -in axTLS.ca_x509.req -out axTLS.ca_x509.pem - -cat > certs.conf << EOF -[ req ] -distinguished_name = req_distinguished_name -prompt = no - -[ req_distinguished_name ] - O = axTLS on ESP8266 - CN = esp8266.local -EOF - -openssl genrsa -out axTLS.key_1024.pem 1024 -openssl req -new -config ./certs.conf -key axTLS.key_1024.pem -out axTLS.x509_1024.req -openssl x509 -req -sha1 -CAcreateserial -days 5000 -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem -in axTLS.x509_1024.req -out axTLS.x509_1024.pem - -openssl rsa -outform DER -in axTLS.key_1024.pem -out axTLS.key_1024 -openssl x509 -outform DER -in axTLS.x509_1024.pem -out axTLS.x509_1024.cer - -cat axTLS.key_1024 > server.key -cat axTLS.x509_1024.cer > server.cer - -rm axTLS.* ca_cert.conf certs.conf diff --git a/lib/ESPAsyncTCP-esphome/ssl/server.cer b/lib/ESPAsyncTCP-esphome/ssl/server.cer deleted file mode 100644 index b5e5f248c4a5e86231876e4a9d0188624355266d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 587 zcmXqLVsbZVV$^5iWSGpfaN~?!WzGh?Y@Awc9&O)w85vnw84P3$r3@t4m_u2(cm!RG z3yM;Ui!;*{f-8$lQge$9E++@_GkM4DONU`s!Yh*a3uA%Yr>0vuTxoGhl`X= zOm)@|y?rGhX-}oBV&|g6>yCF;GafqH|Lx56CmB)ZicHLm42;Om1BMZE6C)!7Q{4 zVCeqqWd!S26n2qiLoZd^)KFr)c^x5%qQkDoiF*OU#gF#P*W_qgHz5K80RRC4fq?*x z404IsAG!|uZhSjSEN@k>Opd#k7h|ttCdOIJSPO%wGa?lf^COVvG_XDD&e? zyvGxataxxV>tpH@0=8+~?+Q)L-YEeBK>*|f|LN$~bw50ah7!i*rhGxNWaSKQgYqgm z{hCLUY2^{1Hv@E?C}m=~;yrD$M#BP=%o;o()sx1v9dHi3c<};30Lr%&dusO-%he4r zCXmZGM{6`I6pLC{CISQo#O-Kr1!n69lpq7y(si&Q zF#kQUO^(d{A^ck;ARC_@8*h>ZYI(wDiee6p=K$&v!C*c49 diff --git a/lib/HTTPClient/examples/Authorization/Authorization.ino b/lib/HTTPClient/examples/Authorization/Authorization.ino new file mode 100644 index 0000000..02bf9ae --- /dev/null +++ b/lib/HTTPClient/examples/Authorization/Authorization.ino @@ -0,0 +1,79 @@ +/** + * Authorization.ino + * + * Created on: 09.12.2015 + * + */ + +#include + +#include +#include + +#include + +#define USE_SERIAL Serial + +WiFiMulti wifiMulti; + +void setup() { + + USE_SERIAL.begin(115200); + + USE_SERIAL.println(); + USE_SERIAL.println(); + USE_SERIAL.println(); + + for (uint8_t t = 4; t > 0; t--) { + USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); + USE_SERIAL.flush(); + delay(1000); + } + + wifiMulti.addAP("SSID", "PASSWORD"); +} + +void loop() { + // wait for WiFi connection + if ((wifiMulti.run() == WL_CONNECTED)) { + + HTTPClient http; + + USE_SERIAL.print("[HTTP] begin...\n"); + // configure traged server and url + + http.begin("http://user:password@192.168.1.12/test.html"); + + /* + // or + http.begin("http://192.168.1.12/test.html"); + http.setAuthorization("user", "password"); + + // or + http.begin("http://192.168.1.12/test.html"); + http.setAuthorization("dXNlcjpwYXN3b3Jk"); + */ + + USE_SERIAL.print("[HTTP] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + USE_SERIAL.println(payload); + } + } else { + USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } + + http.end(); + } + + delay(10000); +} diff --git a/lib/HTTPClient/examples/Authorization/ci.json b/lib/HTTPClient/examples/Authorization/ci.json new file mode 100644 index 0000000..d8b3664 --- /dev/null +++ b/lib/HTTPClient/examples/Authorization/ci.json @@ -0,0 +1,5 @@ +{ + "targets": { + "esp32h2": false + } +} diff --git a/lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino new file mode 100644 index 0000000..e8f5be6 --- /dev/null +++ b/lib/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino @@ -0,0 +1,100 @@ +/** + * BasicHTTPClient.ino + * + * Created on: 24.05.2015 + * + */ + +#include + +#include +#include + +#include + +#define USE_SERIAL Serial + +WiFiMulti wifiMulti; + +/* +const char* ca = \ +"-----BEGIN CERTIFICATE-----\n" \ +"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ +"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ +"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ +"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ +"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ +"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ +"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ +"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ +"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ +"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ +"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ +"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ +"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ +"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ +"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ +"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ +"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ +"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ +"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ +"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ +"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ +"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ +"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ +"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ +"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ +"-----END CERTIFICATE-----\n"; +*/ + +void setup() { + + USE_SERIAL.begin(115200); + + USE_SERIAL.println(); + USE_SERIAL.println(); + USE_SERIAL.println(); + + for (uint8_t t = 4; t > 0; t--) { + USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); + USE_SERIAL.flush(); + delay(1000); + } + + wifiMulti.addAP("SSID", "PASSWORD"); +} + +void loop() { + // wait for WiFi connection + if ((wifiMulti.run() == WL_CONNECTED)) { + + HTTPClient http; + + USE_SERIAL.print("[HTTP] begin...\n"); + // configure traged server and url + //http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS + http.begin("http://example.com/index.html"); //HTTP + + USE_SERIAL.print("[HTTP] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + USE_SERIAL.println(payload); + } + } else { + USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } + + http.end(); + } + + delay(5000); +} diff --git a/lib/HTTPClient/examples/BasicHttpClient/ci.json b/lib/HTTPClient/examples/BasicHttpClient/ci.json new file mode 100644 index 0000000..d8b3664 --- /dev/null +++ b/lib/HTTPClient/examples/BasicHttpClient/ci.json @@ -0,0 +1,5 @@ +{ + "targets": { + "esp32h2": false + } +} diff --git a/lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino new file mode 100644 index 0000000..138e68d --- /dev/null +++ b/lib/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -0,0 +1,145 @@ +/** + BasicHTTPSClient.ino + + Created on: 14.10.2018 + +*/ + +#include + +#include +#include + +#include + +#include + +// This is GandiStandardSSLCA2.pem, 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 Sep 11 23:59:59 2024 GMT +const char *rootCACertificate = "-----BEGIN CERTIFICATE-----\n" + "MIIF6TCCA9GgAwIBAgIQBeTcO5Q4qzuFl8umoZhQ4zANBgkqhkiG9w0BAQwFADCB\n" + "iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n" + "cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n" + "BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTQw\n" + "OTEyMDAwMDAwWhcNMjQwOTExMjM1OTU5WjBfMQswCQYDVQQGEwJGUjEOMAwGA1UE\n" + "CBMFUGFyaXMxDjAMBgNVBAcTBVBhcmlzMQ4wDAYDVQQKEwVHYW5kaTEgMB4GA1UE\n" + "AxMXR2FuZGkgU3RhbmRhcmQgU1NMIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IB\n" + "DwAwggEKAoIBAQCUBC2meZV0/9UAPPWu2JSxKXzAjwsLibmCg5duNyj1ohrP0pIL\n" + "m6jTh5RzhBCf3DXLwi2SrCG5yzv8QMHBgyHwv/j2nPqcghDA0I5O5Q1MsJFckLSk\n" + "QFEW2uSEEi0FXKEfFxkkUap66uEHG4aNAXLy59SDIzme4OFMH2sio7QQZrDtgpbX\n" + "bmq08j+1QvzdirWrui0dOnWbMdw+naxb00ENbLAb9Tr1eeohovj0M1JLJC0epJmx\n" + "bUi8uBL+cnB89/sCdfSN3tbawKAyGlLfOGsuRTg/PwSWAP2h9KK71RfWJ3wbWFmV\n" + "XooS/ZyrgT5SKEhRhWvzkbKGPym1bgNi7tYFAgMBAAGjggF1MIIBcTAfBgNVHSME\n" + "GDAWgBRTeb9aqitKz1SA4dibwJ3ysgNmyzAdBgNVHQ4EFgQUs5Cn2MmvTs1hPJ98\n" + "rV1/Qf1pMOowDgYDVR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYD\n" + "VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMCIGA1UdIAQbMBkwDQYLKwYBBAGy\n" + "MQECAhowCAYGZ4EMAQIBMFAGA1UdHwRJMEcwRaBDoEGGP2h0dHA6Ly9jcmwudXNl\n" + "cnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FDZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNy\n" + "bDB2BggrBgEFBQcBAQRqMGgwPwYIKwYBBQUHMAKGM2h0dHA6Ly9jcnQudXNlcnRy\n" + "dXN0LmNvbS9VU0VSVHJ1c3RSU0FBZGRUcnVzdENBLmNydDAlBggrBgEFBQcwAYYZ\n" + "aHR0cDovL29jc3AudXNlcnRydXN0LmNvbTANBgkqhkiG9w0BAQwFAAOCAgEAWGf9\n" + "crJq13xhlhl+2UNG0SZ9yFP6ZrBrLafTqlb3OojQO3LJUP33WbKqaPWMcwO7lWUX\n" + "zi8c3ZgTopHJ7qFAbjyY1lzzsiI8Le4bpOHeICQW8owRc5E69vrOJAKHypPstLbI\n" + "FhfFcvwnQPYT/pOmnVHvPCvYd1ebjGU6NSU2t7WKY28HJ5OxYI2A25bUeo8tqxyI\n" + "yW5+1mUfr13KFj8oRtygNeX56eXVlogMT8a3d2dIhCe2H7Bo26y/d7CQuKLJHDJd\n" + "ArolQ4FCR7vY4Y8MDEZf7kYzawMUgtN+zY+vkNaOJH1AQrRqahfGlZfh8jjNp+20\n" + "J0CT33KpuMZmYzc4ZCIwojvxuch7yPspOqsactIGEk72gtQjbz7Dk+XYtsDe3CMW\n" + "1hMwt6CaDixVBgBwAc/qOR2A24j3pSC4W/0xJmmPLQphgzpHphNULB7j7UTKvGof\n" + "KA5R2d4On3XNDgOVyvnFqSot/kGkoUeuDcL5OWYzSlvhhChZbH2UF3bkRYKtcCD9\n" + "0m9jqNf6oDP6N8v3smWe2lBvP+Sn845dWDKXcCMu5/3EFZucJ48y7RetWIExKREa\n" + "m9T8bJUox04FB6b9HbwZ4ui3uRGKLXASUoWNjDNKD/yZkuBjcNqllEdjB+dYxzFf\n" + "BT02Vf6Dsuimrdfp5gJ0iHRc2jTbkNJtUQoj1iM=\n" + "-----END CERTIFICATE-----\n"; + +// Not sure if NetworkClientSecure checks the validity date of the certificate. +// Setting clock just to be sure... +void setClock() { + configTime(0, 0, "pool.ntp.org"); + + Serial.print(F("Waiting for NTP time sync: ")); + time_t nowSecs = time(nullptr); + while (nowSecs < 8 * 3600 * 2) { + delay(500); + Serial.print(F(".")); + yield(); + nowSecs = time(nullptr); + } + + Serial.println(); + struct tm timeinfo; + gmtime_r(&nowSecs, &timeinfo); + Serial.print(F("Current time: ")); + Serial.print(asctime(&timeinfo)); +} + +WiFiMulti WiFiMulti; + +void setup() { + + Serial.begin(115200); + // Serial.setDebugOutput(true); + + Serial.println(); + Serial.println(); + Serial.println(); + + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); + + // wait for WiFi connection + Serial.print("Waiting for WiFi to connect..."); + while ((WiFiMulti.run() != WL_CONNECTED)) { + Serial.print("."); + } + Serial.println(" connected"); + + setClock(); +} + +void loop() { + NetworkClientSecure *client = new NetworkClientSecure; + if (client) { + client->setCACert(rootCACertificate); + + { + // Add a scoping block for HTTPClient https to make sure it is destroyed before NetworkClientSecure *client is + HTTPClient https; + + Serial.print("[HTTPS] begin...\n"); + if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS + Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = https.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + Serial.printf("[HTTPS] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + String payload = https.getString(); + Serial.println(payload); + } + } else { + Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); + } + + https.end(); + } else { + Serial.printf("[HTTPS] Unable to connect\n"); + } + + // End extra scoping block + } + + delete client; + } else { + Serial.println("Unable to create client"); + } + + Serial.println(); + Serial.println("Waiting 10s before the next round..."); + delay(10000); +} diff --git a/lib/HTTPClient/examples/BasicHttpsClient/ci.json b/lib/HTTPClient/examples/BasicHttpsClient/ci.json new file mode 100644 index 0000000..d8b3664 --- /dev/null +++ b/lib/HTTPClient/examples/BasicHttpsClient/ci.json @@ -0,0 +1,5 @@ +{ + "targets": { + "esp32h2": false + } +} diff --git a/lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino b/lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino new file mode 100644 index 0000000..7f1d1dd --- /dev/null +++ b/lib/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino @@ -0,0 +1,107 @@ +/*|----------------------------------------------------------|*/ +/*|WORKING EXAMPLE FOR HTTP/HTTPS CONNECTION |*/ +/*|TESTED BOARDS: Devkit v1 DOIT, Devkitc v4 |*/ +/*|CORE: June 2018 |*/ +/*|----------------------------------------------------------|*/ +#include +#include +#if __has_include("esp_eap_client.h") +#include "esp_eap_client.h" +#else +#include "esp_wpa2.h" +#endif +#include +#define EAP_IDENTITY "identity" //if connecting from another corporation, use identity@organization.domain in Eduroam +#define EAP_PASSWORD "password" //your Eduroam password +const char *ssid = "eduroam"; // Eduroam SSID +int counter = 0; +const char *test_root_ca = "-----BEGIN CERTIFICATE-----\n" + "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" + "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" + "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" + "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" + "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" + "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" + "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" + "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" + "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" + "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" + "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" + "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" + "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" + "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" + "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" + "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" + "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" + "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" + "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" + "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" + "-----END CERTIFICATE-----\n"; +void setup() { + Serial.begin(115200); + delay(10); + Serial.println(); + Serial.print("Connecting to network: "); + Serial.println(ssid); + WiFi.disconnect(true); //disconnect form wifi to set new wifi connection + WiFi.mode(WIFI_STA); //init wifi mode +#if __has_include("esp_eap_client.h") + esp_eap_client_set_identity((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide identity + esp_eap_client_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username + esp_eap_client_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password + esp_wifi_sta_enterprise_enable(); +#else + esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide identity + esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username --> identity and username is same + esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password + esp_wifi_sta_wpa2_ent_enable(); +#endif + WiFi.begin(ssid); //connect to wifi + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + counter++; + if (counter >= 60) { //after 30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address set: "); + Serial.println(WiFi.localIP()); //print LAN IP +} +void loop() { + if (WiFi.status() == WL_CONNECTED) { //if we are connected to Eduroam network + counter = 0; //reset counter + Serial.println("Wifi is still connected with IP: "); + Serial.println(WiFi.localIP()); //inform user about his IP address + } else if (WiFi.status() != WL_CONNECTED) { //if we lost connection, retry + WiFi.begin(ssid); + } + while (WiFi.status() != WL_CONNECTED) { //during lost connection, print dots + delay(500); + Serial.print("."); + counter++; + if (counter >= 60) { //30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.print("Connecting to website: "); + HTTPClient http; + http.begin("https://arduino.php5.sk/rele/rele1.txt", test_root_ca); //HTTPS example connection + //http.begin("http://www.arduino.php5.sk/rele/rele1.txt"); //HTTP example connection + //if uncomment HTTP example, you can comment root CA certificate too! + int httpCode = http.GET(); + if (httpCode > 0) { + Serial.printf("[HTTP] GET... code: %d\n", httpCode); + //file found at server --> on unsuccessful connection code will be -1 + if (httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + Serial.println(payload); + } + } else { + Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } + http.end(); + delay(2000); +} diff --git a/lib/HTTPClient/examples/HTTPClientEnterprise/ci.json b/lib/HTTPClient/examples/HTTPClientEnterprise/ci.json new file mode 100644 index 0000000..d8b3664 --- /dev/null +++ b/lib/HTTPClient/examples/HTTPClientEnterprise/ci.json @@ -0,0 +1,5 @@ +{ + "targets": { + "esp32h2": false + } +} diff --git a/lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino b/lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino new file mode 100644 index 0000000..5b3137a --- /dev/null +++ b/lib/HTTPClient/examples/ReuseConnection/ReuseConnection.ino @@ -0,0 +1,64 @@ +/** + * reuseConnection.ino + * + * Created on: 22.11.2015 + * + */ + +#include + +#include +#include + +#include + +#define USE_SERIAL Serial + +WiFiMulti wifiMulti; + +HTTPClient http; + +void setup() { + + USE_SERIAL.begin(115200); + + USE_SERIAL.println(); + USE_SERIAL.println(); + USE_SERIAL.println(); + + for (uint8_t t = 4; t > 0; t--) { + USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); + USE_SERIAL.flush(); + delay(1000); + } + + wifiMulti.addAP("SSID", "PASSWORD"); + + // allow reuse (if server supports it) + http.setReuse(true); +} + +void loop() { + // wait for WiFi connection + if ((wifiMulti.run() == WL_CONNECTED)) { + + http.begin("http://192.168.1.12/test.html"); + //http.begin("192.168.1.12", 80, "/test.html"); + + int httpCode = http.GET(); + if (httpCode > 0) { + USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + http.writeToStream(&USE_SERIAL); + } + } else { + USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } + + http.end(); + } + + delay(1000); +} diff --git a/lib/HTTPClient/examples/ReuseConnection/ci.json b/lib/HTTPClient/examples/ReuseConnection/ci.json new file mode 100644 index 0000000..d8b3664 --- /dev/null +++ b/lib/HTTPClient/examples/ReuseConnection/ci.json @@ -0,0 +1,5 @@ +{ + "targets": { + "esp32h2": false + } +} diff --git a/lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino b/lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino new file mode 100644 index 0000000..187526f --- /dev/null +++ b/lib/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino @@ -0,0 +1,97 @@ +/** + * StreamHTTPClient.ino + * + * Created on: 24.05.2015 + * + */ + +#include + +#include +#include + +#include + +#define USE_SERIAL Serial + +WiFiMulti wifiMulti; + +void setup() { + + USE_SERIAL.begin(115200); + + USE_SERIAL.println(); + USE_SERIAL.println(); + USE_SERIAL.println(); + + for (uint8_t t = 4; t > 0; t--) { + USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); + USE_SERIAL.flush(); + delay(1000); + } + + wifiMulti.addAP("SSID", "PASSWORD"); +} + +void loop() { + // wait for WiFi connection + if ((wifiMulti.run() == WL_CONNECTED)) { + + HTTPClient http; + + USE_SERIAL.print("[HTTP] begin...\n"); + + // configure server and url + http.begin("http://192.168.1.12/test.html"); + //http.begin("192.168.1.12", 80, "/test.html"); + + USE_SERIAL.print("[HTTP] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + + // get length of document (is -1 when Server sends no Content-Length header) + int len = http.getSize(); + + // create buffer for read + uint8_t buff[128] = {0}; + + // get tcp stream + NetworkClient *stream = http.getStreamPtr(); + + // read all data from server + while (http.connected() && (len > 0 || len == -1)) { + // get available data size + size_t size = stream->available(); + + if (size) { + // read up to 128 byte + int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); + + // write it to Serial + USE_SERIAL.write(buff, c); + + if (len > 0) { + len -= c; + } + } + delay(1); + } + + USE_SERIAL.println(); + USE_SERIAL.print("[HTTP] connection closed or file end.\n"); + } + } else { + USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } + + http.end(); + } + + delay(10000); +} diff --git a/lib/HTTPClient/examples/StreamHttpClient/ci.json b/lib/HTTPClient/examples/StreamHttpClient/ci.json new file mode 100644 index 0000000..d8b3664 --- /dev/null +++ b/lib/HTTPClient/examples/StreamHttpClient/ci.json @@ -0,0 +1,5 @@ +{ + "targets": { + "esp32h2": false + } +} diff --git a/lib/HTTPClient/library.properties b/lib/HTTPClient/library.properties new file mode 100644 index 0000000..56af94c --- /dev/null +++ b/lib/HTTPClient/library.properties @@ -0,0 +1,9 @@ +name=HTTPClient +version=2.0.0 +author=Markus Sattler +maintainer=Markus Sattler +sentence=HTTP Client for ESP32 +paragraph= +category=Communication +url=https://github.com/espressif/arduino-esp32/tree/master/libraries/HTTPClient +architectures=esp32 diff --git a/lib/HTTPClient/src/HTTPClient.cpp b/lib/HTTPClient/src/HTTPClient.cpp new file mode 100644 index 0000000..9a14c82 --- /dev/null +++ b/lib/HTTPClient/src/HTTPClient.cpp @@ -0,0 +1,1720 @@ +#include +/** + * HTTPClient.cpp + * + * Created on: 02.11.2015 + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the HTTPClient for Arduino. + * Port to ESP32 by Evandro Luis Copercini (2017), + * changed fingerprints to CA verification. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Adapted in October 2018 + */ + +#include +#include + +#ifdef HTTPCLIENT_1_1_COMPATIBLE +#include +#if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) +#include +#else +#include +#endif +#endif + +#include +#include + +#include "HTTPClient.h" + +/// Cookie jar support +#include + +#ifdef HTTPCLIENT_1_1_COMPATIBLE +class TransportTraits +{ +public: + virtual ~TransportTraits() + { + } + + virtual std::unique_ptr create() + { + return std::unique_ptr(new WiFiClient()); + } + + virtual bool verify(WiFiClient& client, const char* host) + { + return true; + } +}; + +class TLSTraits : public TransportTraits +{ +public: + TLSTraits(const char* CAcert, const char* clicert = nullptr, const char* clikey = nullptr) : + _cacert(CAcert), _clicert(clicert), _clikey(clikey) + { + } + + std::unique_ptr create() override + { + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) + return std::unique_ptr(new WiFiClientSecure()); + #else + return std::unique_ptr(new NetworkClientSecure()); + #endif + } + + bool verify(WiFiClient& client, const char* host) override + { + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) + WiFiClientSecure& wcs = static_cast(client); + #else + NetworkClientSecure& wcs = static_cast(client); + #endif + if (_cacert == nullptr) { + wcs.setInsecure(); + } else { + wcs.setCACert(_cacert); + wcs.setCertificate(_clicert); + wcs.setPrivateKey(_clikey); + } + return true; + } + +protected: + const char* _cacert; + const char* _clicert; + const char* _clikey; +}; +#endif // HTTPCLIENT_1_1_COMPATIBLE + +/** + * constructor + */ +HTTPClient::HTTPClient() +{ +} + +/** + * destructor + */ +HTTPClient::~HTTPClient() +{ + if(_client) { + _client->stop(); + } + if(_currentHeaders) { + delete[] _currentHeaders; + } + if(_tcpDeprecated) { + _tcpDeprecated.reset(nullptr); + } + if(_transportTraits) { + _transportTraits.reset(nullptr); + } +} + +void HTTPClient::clear() +{ + _returnCode = 0; + _size = -1; + _headers = ""; +} + + +/** + * parsing the url for all needed parameters + * @param client Client& + * @param url String + * @param https bool + * @return success bool + */ +bool HTTPClient::begin(WiFiClient &client, String url) { +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } +#endif + + _client = &client; + + // check for : (http: or https:) + int index = url.indexOf(':'); + if(index < 0) { + log_d("failed to parse protocol"); + return false; + } + + String protocol = url.substring(0, index); + if(protocol != "http" && protocol != "https") { + log_d("unknown protocol '%s'", protocol.c_str()); + return false; + } + + _port = (protocol == "https" ? 443 : 80); + _secure = (protocol == "https"); + return beginInternal(url, protocol.c_str()); +} + + +/** + * directly supply all needed parameters + * @param client Client& + * @param host String + * @param port uint16_t + * @param uri String + * @param https bool + * @return success bool + */ +bool HTTPClient::begin(WiFiClient &client, String host, uint16_t port, String uri, bool https) +{ +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } +#endif + + _client = &client; + + clear(); + _host = host; + _port = port; + _uri = uri; + _protocol = (https ? "https" : "http"); + _secure = https; + return true; +} + + +#ifdef HTTPCLIENT_1_1_COMPATIBLE +bool HTTPClient::begin(String url, const char* CAcert) +{ + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + + clear(); + _port = 443; + if (!beginInternal(url, "https")) { + return false; + } + _secure = true; + _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert)); + if(!_transportTraits) { + log_e("could not create transport traits"); + return false; + } + + return true; +} + +/** + * parsing the url for all needed parameters + * @param url String + */ +bool HTTPClient::begin(String url) +{ + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + + clear(); + _port = 80; + if (!beginInternal(url, "http")) { + return begin(url, (const char*)NULL); + } + _transportTraits = TransportTraitsPtr(new TransportTraits()); + if(!_transportTraits) { + log_e("could not create transport traits"); + return false; + } + + return true; +} +#endif // HTTPCLIENT_1_1_COMPATIBLE + +bool HTTPClient::beginInternal(String url, const char* expectedProtocol) +{ + log_v("url: %s", url.c_str()); + + // check for : (http: or https: + int index = url.indexOf(':'); + if(index < 0) { + log_e("failed to parse protocol"); + return false; + } + + _protocol = url.substring(0, index); + if (_protocol != expectedProtocol) { + log_d("unexpected protocol: %s, expected %s", _protocol.c_str(), expectedProtocol); + return false; + } + + url.remove(0, (index + 3)); // remove http:// or https:// + + index = url.indexOf('/'); + if (index == -1) { + index = url.length(); + url += '/'; + } + String host = url.substring(0, index); + url.remove(0, index); // remove host part + + // get Authorization + index = host.indexOf('@'); + if(index >= 0) { + // auth info + String auth = host.substring(0, index); + host.remove(0, index + 1); // remove auth part including @ + _base64Authorization = base64::encode(auth); + } + + // get port + index = host.indexOf(':'); + String the_host; + if(index >= 0) { + the_host = host.substring(0, index); // hostname + host.remove(0, (index + 1)); // remove hostname + : + _port = host.toInt(); // get port + } else { + the_host = host; + } + if(_host != the_host && connected()){ + log_d("switching host from '%s' to '%s'. disconnecting first", _host.c_str(), the_host.c_str()); + _canReuse = false; + disconnect(true); + } + _host = the_host; + _uri = url; + log_d("protocol: %s, host: %s port: %d url: %s", _protocol.c_str(), _host.c_str(), _port, _uri.c_str()); + return true; +} + +#ifdef HTTPCLIENT_1_1_COMPATIBLE +bool HTTPClient::begin(String host, uint16_t port, String uri) +{ + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + + clear(); + _host = host; + _port = port; + _uri = uri; + _transportTraits = TransportTraitsPtr(new TransportTraits()); + log_d("host: %s port: %d uri: %s", host.c_str(), port, uri.c_str()); + return true; +} + +bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcert) +{ + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + + clear(); + _host = host; + _port = port; + _uri = uri; + + if (strlen(CAcert) == 0) { + return false; + } + _secure = true; + _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert)); + return true; +} + +bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key) +{ + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + + clear(); + _host = host; + _port = port; + _uri = uri; + + if (strlen(CAcert) == 0) { + return false; + } + _secure = true; + _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key)); + return true; +} +#endif // HTTPCLIENT_1_1_COMPATIBLE + +/** + * end + * called after the payload is handled + */ +void HTTPClient::end(void) +{ + disconnect(false); + clear(); +} + + + +/** + * disconnect + * close the TCP socket + */ +void HTTPClient::disconnect(bool preserveClient) +{ + if(connected()) { + if(_client->available() > 0) { + log_d("still data in buffer (%d), clean up.\n", _client->available()); + _client->flush(); + } + + if(_reuse && _canReuse) { + log_d("tcp keep open for reuse"); + } else { + log_d("tcp stop"); + _client->stop(); + if(!preserveClient) { + _client = nullptr; +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_tcpDeprecated) { + _transportTraits.reset(nullptr); + _tcpDeprecated.reset(nullptr); + } +#endif + } + } + } else { + log_d("tcp is closed\n"); + } +} + + +/** + * connected + * @return connected status + */ +bool HTTPClient::connected() +{ + if(_client) { + return ((_client->available() > 0) || _client->connected()); + } + return false; +} + +/** + * try to reuse the connection to the server + * keep-alive + * @param reuse bool + */ +void HTTPClient::setReuse(bool reuse) +{ + _reuse = reuse; +} + +/** + * set User Agent + * @param userAgent const char * + */ +void HTTPClient::setUserAgent(const String& userAgent) +{ + _userAgent = userAgent; +} + +/** + * set the Authorizatio for the http request + * @param user const char * + * @param password const char * + */ +void HTTPClient::setAuthorization(const char * user, const char * password) +{ + if(user && password) { + String auth = user; + auth += ":"; + auth += password; + _base64Authorization = base64::encode(auth); + } +} + +/** + * set the Authorizatio for the http request + * @param auth const char * base64 + */ +void HTTPClient::setAuthorization(const char * auth) +{ + if(auth) { + _base64Authorization = auth; + } +} + +/** + * set the Authorization type for the http request + * @param authType const char * + */ +void HTTPClient::setAuthorizationType(const char * authType) +{ + if(authType) { + _authorizationType = authType; + } +} + +/** + * set the timeout (ms) for establishing a connection to the server + * @param connectTimeout int32_t + */ +void HTTPClient::setConnectTimeout(int32_t connectTimeout) +{ + _connectTimeout = connectTimeout; +} + +/** + * set the timeout for the TCP connection + * @param timeout unsigned int + */ +void HTTPClient::setTimeout(uint16_t timeout) +{ + _tcpTimeout = timeout; + if(connected()) { + _client->setTimeout((timeout + 500) / 1000); + } +} + +/** + * use HTTP1.0 + * @param use + */ +void HTTPClient::useHTTP10(bool useHTTP10) +{ + _useHTTP10 = useHTTP10; + _reuse = !useHTTP10; +} + +/** + * send a GET request + * @return http code + */ +int HTTPClient::GET() +{ + return sendRequest("GET"); +} + +/** + * sends a post request to the server + * @param payload uint8_t * + * @param size size_t + * @return http code + */ +int HTTPClient::POST(uint8_t * payload, size_t size) +{ + return sendRequest("POST", payload, size); +} + +int HTTPClient::POST(String payload) +{ + return POST((uint8_t *) payload.c_str(), payload.length()); +} + +/** + * sends a patch request to the server + * @param payload uint8_t * + * @param size size_t + * @return http code + */ +int HTTPClient::PATCH(uint8_t * payload, size_t size) +{ + return sendRequest("PATCH", payload, size); +} + +int HTTPClient::PATCH(String payload) +{ + return PATCH((uint8_t *) payload.c_str(), payload.length()); +} + +/** + * sends a put request to the server + * @param payload uint8_t * + * @param size size_t + * @return http code + */ +int HTTPClient::PUT(uint8_t * payload, size_t size) { + return sendRequest("PUT", payload, size); +} + +int HTTPClient::PUT(String payload) { + return PUT((uint8_t *) payload.c_str(), payload.length()); +} + +/** + * sendRequest + * @param type const char * "GET", "POST", .... + * @param payload String data for the message body + * @return + */ +int HTTPClient::sendRequest(const char * type, String payload) +{ + return sendRequest(type, (uint8_t *) payload.c_str(), payload.length()); +} + +/** + * sendRequest + * @param type const char * "GET", "POST", .... + * @param payload uint8_t * data for the message body if null not send + * @param size size_t size for the message body if 0 not send + * @return -1 if no info or > 0 when Content-Length is set by server + */ +int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) +{ + int code; + bool redirect = false; + uint16_t redirectCount = 0; + do { + // wipe out any existing headers from previous request + for(size_t i = 0; i < _headerKeysCount; i++) { + if (_currentHeaders[i].value.length() > 0) { + _currentHeaders[i].value.clear(); + } + } + + log_d("request type: '%s' redirCount: %d\n", type, redirectCount); + + // connect to server + if(!connect()) { + return returnError(HTTPC_ERROR_CONNECTION_REFUSED); + } + + if(payload && size > 0) { + addHeader(F("Content-Length"), String(size)); + } + + // add cookies to header, if present + String cookie_string; + if(generateCookieString(&cookie_string)) { + addHeader("Cookie", cookie_string); + } + + // send Header + if(!sendHeader(type)) { + return returnError(HTTPC_ERROR_SEND_HEADER_FAILED); + } + + // send Payload if needed + if(payload && size > 0) { + size_t sent_bytes = 0; + while(sent_bytes < size){ + size_t sent = _client->write(&payload[sent_bytes], size - sent_bytes); + if (sent == 0){ + log_w("Failed to send chunk! Lets wait a bit"); + delay(100); + sent = _client->write(&payload[sent_bytes], size - sent_bytes); + if (sent == 0){ + log_e("Failed to send chunk!"); + break; + } + } + sent_bytes += sent; + } + if(sent_bytes != size){ + return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); + } + } + + code = handleHeaderResponse(); + log_d("sendRequest code=%d\n", code); + + // Handle redirections as stated in RFC document: + // https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + // + // Implementing HTTP_CODE_FOUND as redirection with GET method, + // to follow most of existing user agent implementations. + // + redirect = false; + if ( + _followRedirects != HTTPC_DISABLE_FOLLOW_REDIRECTS && + redirectCount < _redirectLimit && + _location.length() > 0 + ) { + switch (code) { + // redirecting using the same method + case HTTP_CODE_MOVED_PERMANENTLY: + case HTTP_CODE_TEMPORARY_REDIRECT: { + if ( + // allow to force redirections on other methods + // (the RFC require user to accept the redirection) + _followRedirects == HTTPC_FORCE_FOLLOW_REDIRECTS || + // allow GET and HEAD methods without force + !strcmp(type, "GET") || + !strcmp(type, "HEAD") + ) { + redirectCount += 1; + log_d("following redirect (the same method): '%s' redirCount: %d\n", _location.c_str(), redirectCount); + if (!setURL(_location)) { + log_d("failed setting URL for redirection\n"); + // no redirection + break; + } + // redirect using the same request method and payload, diffrent URL + redirect = true; + } + break; + } + // redirecting with method dropped to GET or HEAD + // note: it does not need `HTTPC_FORCE_FOLLOW_REDIRECTS` for any method + case HTTP_CODE_FOUND: + case HTTP_CODE_SEE_OTHER: { + redirectCount += 1; + log_d("following redirect (dropped to GET/HEAD): '%s' redirCount: %d\n", _location.c_str(), redirectCount); + if (!setURL(_location)) { + log_d("failed setting URL for redirection\n"); + // no redirection + break; + } + // redirect after changing method to GET/HEAD and dropping payload + type = "GET"; + payload = nullptr; + size = 0; + redirect = true; + break; + } + + default: + break; + } + } + + } while (redirect); + // handle Server Response (Header) + return returnError(code); +} + +/** + * sendRequest + * @param type const char * "GET", "POST", .... + * @param stream Stream * data stream for the message body + * @param size size_t size for the message body if 0 not Content-Length is send + * @return -1 if no info or > 0 when Content-Length is set by server + */ +int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) +{ + + if(!stream) { + return returnError(HTTPC_ERROR_NO_STREAM); + } + + // connect to server + if(!connect()) { + return returnError(HTTPC_ERROR_CONNECTION_REFUSED); + } + + if(size > 0) { + addHeader("Content-Length", String(size)); + } + + // add cookies to header, if present + String cookie_string; + if(generateCookieString(&cookie_string)) { + addHeader("Cookie", cookie_string); + } + + // send Header + if(!sendHeader(type)) { + return returnError(HTTPC_ERROR_SEND_HEADER_FAILED); + } + + int buff_size = HTTP_TCP_BUFFER_SIZE; + + int len = size; + int bytesWritten = 0; + + if(len == 0) { + len = -1; + } + + // if possible create smaller buffer then HTTP_TCP_BUFFER_SIZE + if((len > 0) && (len < HTTP_TCP_BUFFER_SIZE)) { + buff_size = len; + } + + // create buffer for read + uint8_t * buff = (uint8_t *) malloc(buff_size); + + if(buff) { + // read all data from stream and send it to server + while(connected() && (stream->available() > -1) && (len > 0 || len == -1)) { + + // get available data size + int sizeAvailable = stream->available(); + + if(sizeAvailable) { + + int readBytes = sizeAvailable; + + // read only the asked bytes + if(len > 0 && readBytes > len) { + readBytes = len; + } + + // not read more the buffer can handle + if(readBytes > buff_size) { + readBytes = buff_size; + } + + // read data + int bytesRead = stream->readBytes(buff, readBytes); + + // write it to Stream + int bytesWrite = _client->write((const uint8_t *) buff, bytesRead); + bytesWritten += bytesWrite; + + // are all Bytes a writen to stream ? + if(bytesWrite != bytesRead) { + log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite); + + // check for write error + if(_client->getWriteError()) { + log_d("stream write error %d", _client->getWriteError()); + + //reset write error for retry + _client->clearWriteError(); + } + + // some time for the stream + delay(1); + + int leftBytes = (readBytes - bytesWrite); + + // retry to send the missed bytes + bytesWrite = _client->write((const uint8_t *) (buff + bytesWrite), leftBytes); + bytesWritten += bytesWrite; + + if(bytesWrite != leftBytes) { + // failed again + log_d("short write, asked for %d but got %d failed.", leftBytes, bytesWrite); + free(buff); + return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); + } + } + + // check for write error + if(_client->getWriteError()) { + log_d("stream write error %d", _client->getWriteError()); + free(buff); + return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); + } + + // count bytes to read left + if(len > 0) { + len -= readBytes; + } + + delay(0); + } else { + delay(1); + } + } + + free(buff); + + if(size && (int) size != bytesWritten) { + log_d("Stream payload bytesWritten %d and size %d mismatch!.", bytesWritten, size); + log_d("ERROR SEND PAYLOAD FAILED!"); + return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); + } else { + log_d("Stream payload written: %d", bytesWritten); + } + + } else { + log_d("too less ram! need %d", HTTP_TCP_BUFFER_SIZE); + return returnError(HTTPC_ERROR_TOO_LESS_RAM); + } + + // handle Server Response (Header) + return returnError(handleHeaderResponse()); +} + +/** + * size of message body / payload + * @return -1 if no info or > 0 when Content-Length is set by server + */ +int HTTPClient::getSize(void) +{ + return _size; +} + +/** + * returns the stream of the tcp connection + * @return WiFiClient + */ +WiFiClient& HTTPClient::getStream(void) +{ + if (connected()) { + return *_client; + } + + log_w("getStream: not connected"); + static WiFiClient empty; + return empty; +} + +/** + * returns a pointer to the stream of the tcp connection + * @return WiFiClient* + */ +WiFiClient* HTTPClient::getStreamPtr(void) +{ + if(connected()) { + return _client; + } + + log_w("getStreamPtr: not connected"); + return nullptr; +} + +/** + * write all message body / payload to Stream + * @param stream Stream * + * @return bytes written ( negative values are error codes ) + */ +int HTTPClient::writeToStream(Stream * stream) +{ + + if(!stream) { + return returnError(HTTPC_ERROR_NO_STREAM); + } + + if(!connected()) { + return returnError(HTTPC_ERROR_NOT_CONNECTED); + } + + // get length of document (is -1 when Server sends no Content-Length header) + int len = _size; + int ret = 0; + + if(_transferEncoding == HTTPC_TE_IDENTITY) { + ret = writeToStreamDataBlock(stream, len); + + // have we an error? + if(ret < 0) { + return returnError(ret); + } + } else if(_transferEncoding == HTTPC_TE_CHUNKED) { + int size = 0; + while(1) { + if(!connected()) { + return returnError(HTTPC_ERROR_CONNECTION_LOST); + } + String chunkHeader = _client->readStringUntil('\n'); + + if(chunkHeader.length() <= 0) { + return returnError(HTTPC_ERROR_READ_TIMEOUT); + } + + chunkHeader.trim(); // remove \r + + // read size of chunk + len = (uint32_t) strtol((const char *) chunkHeader.c_str(), NULL, 16); + size += len; + log_d(" read chunk len: %d", len); + + // data left? + if(len > 0) { + int r = writeToStreamDataBlock(stream, len); + if(r < 0) { + // error in writeToStreamDataBlock + return returnError(r); + } + ret += r; + } else { + + // if no length Header use global chunk size + if(_size <= 0) { + _size = size; + } + + // check if we have write all data out + if(ret != _size) { + return returnError(HTTPC_ERROR_STREAM_WRITE); + } + break; + } + + // read trailing \r\n at the end of the chunk + char buf[2]; + auto trailing_seq_len = _client->readBytes((uint8_t*)buf, 2); + if (trailing_seq_len != 2 || buf[0] != '\r' || buf[1] != '\n') { + return returnError(HTTPC_ERROR_READ_TIMEOUT); + } + + delay(0); + } + } else { + return returnError(HTTPC_ERROR_ENCODING); + } + +// end(); + disconnect(true); + return ret; +} + +/** + * return all payload as String (may need lot of ram or trigger out of memory!) + * @return String + */ +String HTTPClient::getString(void) +{ + // _size can be -1 when Server sends no Content-Length header + if(_size > 0 || _size == -1) { + StreamString sstring; + // try to reserve needed memory (noop if _size == -1) + if(sstring.reserve((_size + 1))) { + writeToStream(&sstring); + return sstring; + } else { + log_d("not enough memory to reserve a string! need: %d", (_size + 1)); + } + } + + return ""; +} + +/** + * converts error code to String + * @param error int + * @return String + */ +String HTTPClient::errorToString(int error) +{ + switch(error) { + case HTTPC_ERROR_CONNECTION_REFUSED: + return F("connection refused"); + case HTTPC_ERROR_SEND_HEADER_FAILED: + return F("send header failed"); + case HTTPC_ERROR_SEND_PAYLOAD_FAILED: + return F("send payload failed"); + case HTTPC_ERROR_NOT_CONNECTED: + return F("not connected"); + case HTTPC_ERROR_CONNECTION_LOST: + return F("connection lost"); + case HTTPC_ERROR_NO_STREAM: + return F("no stream"); + case HTTPC_ERROR_NO_HTTP_SERVER: + return F("no HTTP server"); + case HTTPC_ERROR_TOO_LESS_RAM: + return F("too less ram"); + case HTTPC_ERROR_ENCODING: + return F("Transfer-Encoding not supported"); + case HTTPC_ERROR_STREAM_WRITE: + return F("Stream write error"); + case HTTPC_ERROR_READ_TIMEOUT: + return F("read Timeout"); + default: + return String(); + } +} + +/** + * adds Header to the request + * @param name + * @param value + * @param first + */ +void HTTPClient::addHeader(const String& name, const String& value, bool first, bool replace) +{ + // not allow set of Header handled by code + if(!name.equalsIgnoreCase(F("Connection")) && + !name.equalsIgnoreCase(F("User-Agent")) && + !name.equalsIgnoreCase(F("Host")) && + !(name.equalsIgnoreCase(F("Authorization")) && _base64Authorization.length())){ + + String headerLine = name; + headerLine += ": "; + + if (replace) { + int headerStart = _headers.indexOf(headerLine); + if (headerStart != -1 && (headerStart == 0 || _headers[headerStart - 1] == '\n')) { + int headerEnd = _headers.indexOf('\n', headerStart); + _headers = _headers.substring(0, headerStart) + _headers.substring(headerEnd + 1); + } + } + + headerLine += value; + headerLine += "\r\n"; + if(first) { + _headers = headerLine + _headers; + } else { + _headers += headerLine; + } + } +} + +void HTTPClient::collectHeaders(const char* headerKeys[], const size_t headerKeysCount) +{ + _headerKeysCount = headerKeysCount; + if(_currentHeaders) { + delete[] _currentHeaders; + } + _currentHeaders = new RequestArgument[_headerKeysCount]; + for(size_t i = 0; i < _headerKeysCount; i++) { + _currentHeaders[i].key = headerKeys[i]; + } +} + +String HTTPClient::header(const char* name) +{ + for(size_t i = 0; i < _headerKeysCount; ++i) { + if(_currentHeaders[i].key.equalsIgnoreCase(name)) { + return _currentHeaders[i].value; + } + } + return String(); +} + +String HTTPClient::header(size_t i) +{ + if(i < _headerKeysCount) { + return _currentHeaders[i].value; + } + return String(); +} + +String HTTPClient::headerName(size_t i) +{ + if(i < _headerKeysCount) { + return _currentHeaders[i].key; + } + return String(); +} + +int HTTPClient::headers() +{ + return _headerKeysCount; +} + +bool HTTPClient::hasHeader(const char* name) +{ + for(size_t i = 0; i < _headerKeysCount; ++i) { + if((_currentHeaders[i].key.equalsIgnoreCase(name)) && (_currentHeaders[i].value.length() > 0)) { + return true; + } + } + return false; +} + +/** + * init TCP connection and handle ssl verify if needed + * @return true if connection is ok + */ +bool HTTPClient::connect(void) +{ + if(connected()) { + if(_reuse) { + log_d("already connected, reusing connection"); + } else { + log_d("already connected, try reuse!"); + } + while(_client->available() > 0) { + _client->read(); + } + return true; + } + +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_transportTraits && !_client) { + _tcpDeprecated = _transportTraits->create(); + if(!_tcpDeprecated) { + log_e("failed to create client"); + return false; + } + _client = _tcpDeprecated.get(); + } +#endif + + if (!_client) { + log_d("HTTPClient::begin was not called or returned error"); + return false; + } +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if (_tcpDeprecated && !_transportTraits->verify(*_client, _host.c_str())) { + log_d("transport level verify failed"); + _client->stop(); + return false; + } +#endif + if(!_client->connect(_host.c_str(), _port, _connectTimeout)) { + log_d("failed connect to %s:%u", _host.c_str(), _port); + return false; + } + + // set Timeout for WiFiClient and for Stream::readBytesUntil() and Stream::readStringUntil() + _client->setTimeout((_tcpTimeout + 500) / 1000); + + log_d(" connected to %s:%u", _host.c_str(), _port); + + +/* +#ifdef ESP8266 + _client->setNoDelay(true); +#endif + */ + return connected(); +} + +/** + * sends HTTP request header + * @param type (GET, POST, ...) + * @return status + */ +bool HTTPClient::sendHeader(const char * type) +{ + if(!connected()) { + return false; + } + + String header = String(type) + " " + _uri + F(" HTTP/1."); + + if(_useHTTP10) { + header += "0"; + } else { + header += "1"; + } + + header += String(F("\r\nHost: ")) + _host; + if (_port != 80 && _port != 443) + { + header += ':'; + header += String(_port); + } + header += String(F("\r\nUser-Agent: ")) + _userAgent + + F("\r\nConnection: "); + + if(_reuse) { + header += F("keep-alive"); + } else { + header += F("close"); + } + header += "\r\n"; + + if(!_useHTTP10) { + header += F("Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0\r\n"); + } + + if(_base64Authorization.length()) { + _base64Authorization.replace("\n", ""); + header += F("Authorization: "); + header += _authorizationType; + header += " "; + header += _base64Authorization; + header += "\r\n"; + } + + header += _headers + "\r\n"; + + return (_client->write((const uint8_t *) header.c_str(), header.length()) == header.length()); +} + +/** + * reads the response from the server + * @return int http code + */ +int HTTPClient::handleHeaderResponse() +{ + + if(!connected()) { + return HTTPC_ERROR_NOT_CONNECTED; + } + + _returnCode = 0; + _size = -1; + _canReuse = _reuse; + + String transferEncoding; + + _transferEncoding = HTTPC_TE_IDENTITY; + unsigned long lastDataTime = millis(); + bool firstLine = true; + String date; + + while(connected()) { + size_t len = _client->available(); + if(len > 0) { + String headerLine = _client->readStringUntil('\n'); + headerLine.trim(); // remove \r + + lastDataTime = millis(); + + log_v("RX: '%s'", headerLine.c_str()); + + if(firstLine) { + firstLine = false; + if(_canReuse && headerLine.startsWith("HTTP/1.")) { + _canReuse = (headerLine[sizeof "HTTP/1." - 1] != '0'); + } + int codePos = headerLine.indexOf(' ') + 1; + _returnCode = headerLine.substring(codePos, headerLine.indexOf(' ', codePos)).toInt(); + } else if(headerLine.indexOf(':')) { + String headerName = headerLine.substring(0, headerLine.indexOf(':')); + String headerValue = headerLine.substring(headerLine.indexOf(':') + 1); + headerValue.trim(); + + if(headerName.equalsIgnoreCase("Date")) { + date = headerValue; + } + + if(headerName.equalsIgnoreCase("Content-Length")) { + _size = headerValue.toInt(); + } + + if(_canReuse && headerName.equalsIgnoreCase("Connection")) { + if(headerValue.indexOf("close") >= 0 && headerValue.indexOf("keep-alive") < 0) { + _canReuse = false; + } + } + + if(headerName.equalsIgnoreCase("Transfer-Encoding")) { + transferEncoding = headerValue; + } + + if (headerName.equalsIgnoreCase("Location")) { + _location = headerValue; + } + + if (headerName.equalsIgnoreCase("Set-Cookie")) { + setCookie(date, headerValue); + } + + for (size_t i = 0; i < _headerKeysCount; i++) { + if (_currentHeaders[i].key.equalsIgnoreCase(headerName)) { + // Uncomment the following lines if you need to add support for multiple headers with the same key: + // if (!_currentHeaders[i].value.isEmpty()) { + // // Existing value, append this one with a comma + // _currentHeaders[i].value += ','; + // _currentHeaders[i].value += headerValue; + // } else { + _currentHeaders[i].value = headerValue; + // } + break; // We found a match, stop looking + } + } + + } + + if(headerLine == "") { + log_d("code: %d", _returnCode); + + if(_size > 0) { + log_d("size: %d", _size); + } + + if(transferEncoding.length() > 0) { + log_d("Transfer-Encoding: %s", transferEncoding.c_str()); + if(transferEncoding.equalsIgnoreCase("chunked")) { + _transferEncoding = HTTPC_TE_CHUNKED; + } else if(transferEncoding.equalsIgnoreCase("identity")) { + _transferEncoding = HTTPC_TE_IDENTITY; + } else { + return HTTPC_ERROR_ENCODING; + } + } else { + _transferEncoding = HTTPC_TE_IDENTITY; + } + + if(_returnCode) { + return _returnCode; + } else { + log_d("Remote host is not an HTTP Server!"); + return HTTPC_ERROR_NO_HTTP_SERVER; + } + } + + } else { + if((millis() - lastDataTime) > _tcpTimeout) { + return HTTPC_ERROR_READ_TIMEOUT; + } + delay(10); + } + } + + return HTTPC_ERROR_CONNECTION_LOST; +} + +/** + * write one Data Block to Stream + * @param stream Stream * + * @param size int + * @return < 0 = error >= 0 = size written + */ +int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) +{ + int buff_size = HTTP_TCP_BUFFER_SIZE; + int len = size; + int bytesWritten = 0; + + // if possible create smaller buffer then HTTP_TCP_BUFFER_SIZE + if((len > 0) && (len < HTTP_TCP_BUFFER_SIZE)) { + buff_size = len; + } + + // create buffer for read + uint8_t * buff = (uint8_t *) malloc(buff_size); + + if(buff) { + // read all data from server + while(connected() && (len > 0 || len == -1)) { + + // get available data size + size_t sizeAvailable = _client->available(); + + if(sizeAvailable) { + + int readBytes = sizeAvailable; + + // read only the asked bytes + if(len > 0 && readBytes > len) { + readBytes = len; + } + + // not read more the buffer can handle + if(readBytes > buff_size) { + readBytes = buff_size; + } + + // stop if no more reading + if (readBytes == 0) + break; + + // read data + int bytesRead = _client->readBytes(buff, readBytes); + + // write it to Stream + int bytesWrite = stream->write(buff, bytesRead); + bytesWritten += bytesWrite; + + // are all Bytes a writen to stream ? + if(bytesWrite != bytesRead) { + log_d("short write asked for %d but got %d retry...", bytesRead, bytesWrite); + + // check for write error + if(stream->getWriteError()) { + log_d("stream write error %d", stream->getWriteError()); + + //reset write error for retry + stream->clearWriteError(); + } + + // some time for the stream + delay(1); + + int leftBytes = (readBytes - bytesWrite); + + // retry to send the missed bytes + bytesWrite = stream->write((buff + bytesWrite), leftBytes); + bytesWritten += bytesWrite; + + if(bytesWrite != leftBytes) { + // failed again + log_w("short write asked for %d but got %d failed.", leftBytes, bytesWrite); + free(buff); + return HTTPC_ERROR_STREAM_WRITE; + } + } + + // check for write error + if(stream->getWriteError()) { + log_w("stream write error %d", stream->getWriteError()); + free(buff); + return HTTPC_ERROR_STREAM_WRITE; + } + + // count bytes to read left + if(len > 0) { + len -= readBytes; + } + + delay(0); + } else { + delay(1); + } + } + + free(buff); + + log_d("connection closed or file end (written: %d).", bytesWritten); + + if((size > 0) && (size != bytesWritten)) { + log_d("bytesWritten %d and size %d mismatch!.", bytesWritten, size); + return HTTPC_ERROR_STREAM_WRITE; + } + + } else { + log_w("too less ram! need %d", HTTP_TCP_BUFFER_SIZE); + return HTTPC_ERROR_TOO_LESS_RAM; + } + + return bytesWritten; +} + +/** + * called to handle error return, may disconnect the connection if still exists + * @param error + * @return error + */ +int HTTPClient::returnError(int error) +{ + if(error < 0) { + log_w("error(%d): %s", error, errorToString(error).c_str()); + if(connected()) { + log_d("tcp stop"); + _client->stop(); + } + } + return error; +} + +void HTTPClient::setFollowRedirects(followRedirects_t follow) +{ + _followRedirects = follow; +} + +void HTTPClient::setRedirectLimit(uint16_t limit) +{ + _redirectLimit = limit; +} + +/** + * set the URL to a new value. Handy for following redirects. + * @param url + */ +bool HTTPClient::setURL(const String& url) +{ + // if the new location is only a path then only update the URI + if (url && url[0] == '/') { + _uri = url; + clear(); + return true; + } + + if (!url.startsWith(_protocol + ':')) { + log_d("new URL not the same protocol, expected '%s', URL: '%s'\n", _protocol.c_str(), url.c_str()); + return false; + } + + // check if the port is specified + int indexPort = url.indexOf(':', 6); // find the first ':' excluding the one from the protocol + int indexURI = url.indexOf('/', 7); // find where the URI starts to make sure the ':' is not part of it + if (indexPort == -1 || indexPort > indexURI) { + // the port is not specified + _port = (_protocol == "https" ? 443 : 80); + } + + // disconnect but preserve _client. + // Also have to keep the connection otherwise it will free some of the memory used by _client + // and will blow up later when trying to do _client->available() or similar + _canReuse = true; + disconnect(true); + return beginInternal(url, _protocol.c_str()); +} + +const String &HTTPClient::getLocation(void) +{ + return _location; +} + +void HTTPClient::setCookieJar(CookieJar* cookieJar) +{ + _cookieJar = cookieJar; +} + +void HTTPClient::resetCookieJar() +{ + _cookieJar = nullptr; +} + +void HTTPClient::clearAllCookies() +{ + if (_cookieJar) _cookieJar->clear(); +} + +void HTTPClient::setCookie(String date, String headerValue) +{ + if (!_cookieJar) + { + return; + } + #define HTTP_TIME_PATTERN "%a, %d %b %Y %H:%M:%S" + + Cookie cookie; + String value; + int pos1, pos2; + + struct tm tm; + strptime(date.c_str(), HTTP_TIME_PATTERN, &tm); + cookie.date = mktime(&tm); + + pos1 = headerValue.indexOf('='); + pos2 = headerValue.indexOf(';'); + + if (pos1 >= 0 && pos2 > pos1){ + cookie.name = headerValue.substring(0, pos1); + cookie.value = headerValue.substring(pos1 + 1, pos2); + } else { + return; // invalid cookie header + } + + // only Cookie Attributes are case insensitive from this point on + headerValue.toLowerCase(); + + // expires + if (headerValue.indexOf("expires=") >= 0){ + pos1 = headerValue.indexOf("expires=") + strlen("expires="); + pos2 = headerValue.indexOf(';', pos1); + + if (pos2 > pos1) + value = headerValue.substring(pos1, pos2); + else + value = headerValue.substring(pos1); + + strptime(value.c_str(), HTTP_TIME_PATTERN, &tm); + cookie.expires.date = mktime(&tm); + cookie.expires.valid = true; + } + + // max-age + if (headerValue.indexOf("max-age=") >= 0){ + pos1 = headerValue.indexOf("max-age=") + strlen("max-age="); + pos2 = headerValue.indexOf(';', pos1); + + if (pos2 > pos1) + value = headerValue.substring(pos1, pos2); + else + value = headerValue.substring(pos1); + + cookie.max_age.duration = value.toInt(); + cookie.max_age.valid = true; + } + + // domain + if (headerValue.indexOf("domain=") >= 0){ + pos1 = headerValue.indexOf("domain=") + strlen("domain="); + pos2 = headerValue.indexOf(';', pos1); + + if (pos2 > pos1) + value = headerValue.substring(pos1, pos2); + else + value = headerValue.substring(pos1); + + if (value.startsWith(".")) value.remove(0, 1); + + if (_host.indexOf(value) >= 0) { + cookie.domain = value; + } else { + return; // server tries to set a cookie on a different domain; ignore it + } + } else { + pos1 = _host.lastIndexOf('.', _host.lastIndexOf('.') - 1); + if (pos1 >= 0) + cookie.domain = _host.substring(pos1 + 1); + else + cookie.domain = _host; + } + + // path + if (headerValue.indexOf("path=") >= 0){ + pos1 = headerValue.indexOf("path=") + strlen("path="); + pos2 = headerValue.indexOf(';', pos1); + + if (pos2 > pos1) + cookie.path = headerValue.substring(pos1, pos2); + else + cookie.path = headerValue.substring(pos1); + } + + // HttpOnly + cookie.http_only = (headerValue.indexOf("httponly") >= 0); + + // secure + cookie.secure = (headerValue.indexOf("secure") >= 0); + + // overwrite or delete cookie in/from cookie jar + time_t now_local = time(NULL); + time_t now_gmt = mktime(gmtime(&now_local)); + + bool found = false; + + for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) { + if (c->domain == cookie.domain && c->name == cookie.name) { + // when evaluating, max-age takes precedence over expires if both are defined + if ((cookie.max_age.valid && ((cookie.date + cookie.max_age.duration) < now_gmt)) || cookie.max_age.duration <= 0 + || (!cookie.max_age.valid && cookie.expires.valid && cookie.expires.date < now_gmt)) { + _cookieJar->erase(c); + c--; + } else { + *c = cookie; + } + found = true; + } + } + + // add cookie to jar + if (!found && !(cookie.max_age.valid && cookie.max_age.duration <= 0)) + _cookieJar->push_back(cookie); + +} + +bool HTTPClient::generateCookieString(String *cookieString) +{ + time_t now_local = time(NULL); + time_t now_gmt = mktime(gmtime(&now_local)); + + *cookieString = ""; + bool found = false; + + if (!_cookieJar) + { + return false; + } + for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) { + if ((c->max_age.valid && ((c->date + c->max_age.duration) < now_gmt)) || (!c->max_age.valid && c->expires.valid && c->expires.date < now_gmt)) { + _cookieJar->erase(c); + c--; + } else if (_host.indexOf(c->domain) >= 0 && (!c->secure || _secure) ) { + if (*cookieString == "") + *cookieString = c->name + "=" + c->value; + else + *cookieString += " ;" + c->name + "=" + c->value; + found = true; + } + } + + return found; +} \ No newline at end of file diff --git a/lib/HTTPClient/src/HTTPClient.h b/lib/HTTPClient/src/HTTPClient.h new file mode 100644 index 0000000..b1527ad --- /dev/null +++ b/lib/HTTPClient/src/HTTPClient.h @@ -0,0 +1,315 @@ +/** + * HTTPClient.h + * + * Created on: 02.11.2015 + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the HTTPClient for Arduino. + * Port to ESP32 by Evandro Luis Copercini (2017), + * changed fingerprints to CA verification. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef HTTPClient_H_ +#define HTTPClient_H_ + +#ifndef HTTPCLIENT_1_1_COMPATIBLE +#define HTTPCLIENT_1_1_COMPATIBLE +#endif + +#include +#include +#include +#if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) +#include +#else +#include +#endif + +/// Cookie jar support +#include + +#define HTTPCLIENT_DEFAULT_TCP_TIMEOUT (5000) + +/// HTTP client errors +#define HTTPC_ERROR_CONNECTION_REFUSED (-1) +#define HTTPC_ERROR_SEND_HEADER_FAILED (-2) +#define HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3) +#define HTTPC_ERROR_NOT_CONNECTED (-4) +#define HTTPC_ERROR_CONNECTION_LOST (-5) +#define HTTPC_ERROR_NO_STREAM (-6) +#define HTTPC_ERROR_NO_HTTP_SERVER (-7) +#define HTTPC_ERROR_TOO_LESS_RAM (-8) +#define HTTPC_ERROR_ENCODING (-9) +#define HTTPC_ERROR_STREAM_WRITE (-10) +#define HTTPC_ERROR_READ_TIMEOUT (-11) + +/// size for the stream handling +#define HTTP_TCP_BUFFER_SIZE (1460) + +/// HTTP codes see RFC7231 +typedef enum { + HTTP_CODE_CONTINUE = 100, + HTTP_CODE_SWITCHING_PROTOCOLS = 101, + HTTP_CODE_PROCESSING = 102, + HTTP_CODE_OK = 200, + HTTP_CODE_CREATED = 201, + HTTP_CODE_ACCEPTED = 202, + HTTP_CODE_NON_AUTHORITATIVE_INFORMATION = 203, + HTTP_CODE_NO_CONTENT = 204, + HTTP_CODE_RESET_CONTENT = 205, + HTTP_CODE_PARTIAL_CONTENT = 206, + HTTP_CODE_MULTI_STATUS = 207, + HTTP_CODE_ALREADY_REPORTED = 208, + HTTP_CODE_IM_USED = 226, + HTTP_CODE_MULTIPLE_CHOICES = 300, + HTTP_CODE_MOVED_PERMANENTLY = 301, + HTTP_CODE_FOUND = 302, + HTTP_CODE_SEE_OTHER = 303, + HTTP_CODE_NOT_MODIFIED = 304, + HTTP_CODE_USE_PROXY = 305, + HTTP_CODE_TEMPORARY_REDIRECT = 307, + HTTP_CODE_PERMANENT_REDIRECT = 308, + HTTP_CODE_BAD_REQUEST = 400, + HTTP_CODE_UNAUTHORIZED = 401, + HTTP_CODE_PAYMENT_REQUIRED = 402, + HTTP_CODE_FORBIDDEN = 403, + HTTP_CODE_NOT_FOUND = 404, + HTTP_CODE_METHOD_NOT_ALLOWED = 405, + HTTP_CODE_NOT_ACCEPTABLE = 406, + HTTP_CODE_PROXY_AUTHENTICATION_REQUIRED = 407, + HTTP_CODE_REQUEST_TIMEOUT = 408, + HTTP_CODE_CONFLICT = 409, + HTTP_CODE_GONE = 410, + HTTP_CODE_LENGTH_REQUIRED = 411, + HTTP_CODE_PRECONDITION_FAILED = 412, + HTTP_CODE_PAYLOAD_TOO_LARGE = 413, + HTTP_CODE_URI_TOO_LONG = 414, + HTTP_CODE_UNSUPPORTED_MEDIA_TYPE = 415, + HTTP_CODE_RANGE_NOT_SATISFIABLE = 416, + HTTP_CODE_EXPECTATION_FAILED = 417, + HTTP_CODE_MISDIRECTED_REQUEST = 421, + HTTP_CODE_UNPROCESSABLE_ENTITY = 422, + HTTP_CODE_LOCKED = 423, + HTTP_CODE_FAILED_DEPENDENCY = 424, + HTTP_CODE_UPGRADE_REQUIRED = 426, + HTTP_CODE_PRECONDITION_REQUIRED = 428, + HTTP_CODE_TOO_MANY_REQUESTS = 429, + HTTP_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431, + HTTP_CODE_INTERNAL_SERVER_ERROR = 500, + HTTP_CODE_NOT_IMPLEMENTED = 501, + HTTP_CODE_BAD_GATEWAY = 502, + HTTP_CODE_SERVICE_UNAVAILABLE = 503, + HTTP_CODE_GATEWAY_TIMEOUT = 504, + HTTP_CODE_HTTP_VERSION_NOT_SUPPORTED = 505, + HTTP_CODE_VARIANT_ALSO_NEGOTIATES = 506, + HTTP_CODE_INSUFFICIENT_STORAGE = 507, + HTTP_CODE_LOOP_DETECTED = 508, + HTTP_CODE_NOT_EXTENDED = 510, + HTTP_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511 +} t_http_codes; + +typedef enum { + HTTPC_TE_IDENTITY, + HTTPC_TE_CHUNKED +} transferEncoding_t; + +/** + * redirection follow mode. + * + `HTTPC_DISABLE_FOLLOW_REDIRECTS` - no redirection will be followed. + * + `HTTPC_STRICT_FOLLOW_REDIRECTS` - strict RFC2616, only requests using + * GET or HEAD methods will be redirected (using the same method), + * since the RFC requires end-user confirmation in other cases. + * + `HTTPC_FORCE_FOLLOW_REDIRECTS` - all redirections will be followed, + * regardless of a used method. New request will use the same method, + * and they will include the same body data and the same headers. + * In the sense of the RFC, it's just like every redirection is confirmed. + */ +typedef enum { + HTTPC_DISABLE_FOLLOW_REDIRECTS, + HTTPC_STRICT_FOLLOW_REDIRECTS, + HTTPC_FORCE_FOLLOW_REDIRECTS +} followRedirects_t; + + +#ifdef HTTPCLIENT_1_1_COMPATIBLE +class TransportTraits; +typedef std::unique_ptr TransportTraitsPtr; +#endif + +// cookie jar support +typedef struct { + String host; // host which tries to set the cookie + time_t date; // timestamp of the response that set the cookie + String name; + String value; + String domain; + String path = ""; + struct { + time_t date = 0; + bool valid = false; + } expires; + struct { + time_t duration = 0; + bool valid = false; + } max_age; + bool http_only = false; + bool secure = false; +} Cookie; +typedef std::vector CookieJar; + + +class HTTPClient +{ +public: + HTTPClient(); + ~HTTPClient(); + +/* + * Since both begin() functions take a reference to client as a parameter, you need to + * ensure the client object lives the entire time of the HTTPClient + */ + bool begin(WiFiClient &client, String url); + bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false); + +#ifdef HTTPCLIENT_1_1_COMPATIBLE + bool begin(String url); + bool begin(String url, const char* CAcert); + bool begin(String host, uint16_t port, String uri = "/"); + bool begin(String host, uint16_t port, String uri, const char* CAcert); + bool begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key); +#endif + + void end(void); + + bool connected(void); + + void setReuse(bool reuse); /// keep-alive + void setUserAgent(const String& userAgent); + 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); + + WiFiClient& getStream(void); + WiFiClient* getStreamPtr(void); + int writeToStream(Stream* stream); + String getString(void); + + static String errorToString(int error); + + /// Cookie jar support + void setCookieJar(CookieJar* cookieJar); + void resetCookieJar(); + void clearAllCookies(); + +protected: + struct RequestArgument { + String key; + String value; + }; + + bool beginInternal(String url, const char* expectedProtocol); + void disconnect(bool preserveClient = false); + void clear(); + int returnError(int error); + bool connect(void); + bool sendHeader(const char * type); + int handleHeaderResponse(); + int writeToStreamDataBlock(Stream * stream, int len); + + /// Cookie jar support + void setCookie(String date, String headerValue); + bool generateCookieString(String *cookieString); + +#ifdef HTTPCLIENT_1_1_COMPATIBLE + TransportTraitsPtr _transportTraits; + std::unique_ptr _tcpDeprecated; +#endif + + WiFiClient* _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"; + + /// 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_ */ \ No newline at end of file diff --git a/lib/WebSerialLite/.clang-format b/lib/WebSerialLite/.clang-format new file mode 100644 index 0000000..bf2fc01 --- /dev/null +++ b/lib/WebSerialLite/.clang-format @@ -0,0 +1,21 @@ +Language: Cpp +BasedOnStyle: LLVM + +AccessModifierOffset: -2 +BinPackArguments: false +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortIfStatementsOnASingleLine: false +AllowShortLambdasOnASingleLine: Inline +ColumnLimit: 0 +ContinuationIndentWidth: 2 +FixNamespaceComments: false +IndentAccessModifiers: true +IndentCaseLabels: true +IndentWidth: 2 +NamespaceIndentation: All +PointerAlignment: Left +ReferenceAlignment: Left +TabWidth: 2 +UseTab: Never +AlignConsecutiveMacros: true diff --git a/lib/WebSerialLite/.github/FUNDING.yml b/lib/WebSerialLite/.github/FUNDING.yml new file mode 100644 index 0000000..e411f9b --- /dev/null +++ b/lib/WebSerialLite/.github/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: mathieucarbou +# patreon: # Replace with a single Patreon username +# open_collective: # Replace with a single Open Collective username +# ko_fi: # Replace with a single Ko-fi username +# tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +# community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +# liberapay: # Replace with a single Liberapay username +# issuehunt: # Replace with a single IssueHunt username +# otechie: # Replace with a single Otechie username +# lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: https://paypal.me/mathieucarboufr diff --git a/lib/WebSerialLite/.github/dependabot.yml b/lib/WebSerialLite/.github/dependabot.yml new file mode 100644 index 0000000..dfd0e30 --- /dev/null +++ b/lib/WebSerialLite/.github/dependabot.yml @@ -0,0 +1,10 @@ +# Set update schedule for GitHub Actions + +version: 2 +updates: + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every week + interval: "weekly" diff --git a/lib/WebSerialLite/.github/workflows/ci.yml b/lib/WebSerialLite/.github/workflows/ci.yml new file mode 100644 index 0000000..2fa647d --- /dev/null +++ b/lib/WebSerialLite/.github/workflows/ci.yml @@ -0,0 +1,129 @@ +# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json + +name: Continuous Integration + +on: + workflow_dispatch: + push: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + arduino: + name: arduino ${{ matrix.name }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - name: package_esp32_index.json + core: esp32:esp32 + board: esp32:esp32:esp32 + index_url: https://espressif.github.io/arduino-esp32/package_esp32_index.json + - name: package_esp32_dev_index.json + core: esp32:esp32 + board: esp32:esp32:esp32 + index_url: https://espressif.github.io/arduino-esp32/package_esp32_dev_index.json + - name: package_esp8266com_index.json + core: esp8266:esp8266 + board: esp8266:esp8266:huzzah + index_url: https://arduino.esp8266.com/stable/package_esp8266com_index.json + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Arduino Lint + uses: arduino/arduino-lint-action@v1 + with: + library-manager: update + + - name: Install arduino-cli + run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh + + - name: Update core index + run: arduino-cli core update-index --additional-urls "${{ matrix.index_url }}" + + - name: Install core + run: arduino-cli core install --additional-urls "${{ matrix.index_url }}" ${{ matrix.core }} + + - name: Install Async TCP + run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/mathieucarbou/AsyncTCP#v3.1.4 + + - name: Install ESPAsyncTCP + run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/mathieucarbou/esphome-ESPAsyncTCP#v2.0.0 + + - name: Install ESP Async WebServer + run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/mathieucarbou/ESPAsyncWebServer#v3.0.6 + + - name: Build Demo + run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/Demo/Demo.ino" + + - name: Build Demo_AP + run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/Demo_AP/Demo_AP.ino" + + - name: Build Logging + run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/Logging/Logging.ino" + + - name: Build HighPerf + run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/HighPerf/HighPerf.ino" + + platformio: + name: pio ${{ matrix.name }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - name: esp32dev|arduino + board: esp32dev + platform: espressif32 + opts: "--project-option 'lib_compat_mode = strict'" + - name: esp32dev|arduino-2 + board: esp32dev + platform: espressif32@6.7.0 + opts: "--project-option 'lib_compat_mode = strict'" + - name: esp32dev|arduino-3 + board: esp32dev + platform: espressif32 + opts: "--project-option 'lib_compat_mode = strict' --project-option 'platform_packages=platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.2, platform_packages=platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.2/esp32-arduino-libs-3.0.2.zip'" + + - name: esp32-s3-devkitc-1|arduino + board: esp32-s3-devkitc-1 + platform: espressif32 + opts: "--project-option 'lib_compat_mode = strict'" + - name: esp32-s3-devkitc-1|arduino-2 + board: esp32-s3-devkitc-1 + platform: espressif32@6.7.0 + opts: "--project-option 'lib_compat_mode = strict'" + - name: esp32-s3-devkitc-1|arduino-3 + board: esp32-s3-devkitc-1 + platform: espressif32 + opts: "--project-option 'lib_compat_mode = strict' --project-option 'platform_packages=platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.2, platform_packages=platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.2/esp32-arduino-libs-3.0.2.zip'" + + - name: huzzah|espressif8266 + board: huzzah + platform: espressif8266 + opts: "--project-option 'lib_compat_mode = strict'" + steps: + - uses: actions/checkout@v4 + - name: Set up cache + uses: actions/cache@v4 + with: + path: | + ~/.platformio + ~/.cache/pip + key: ${{ matrix.name }} + - uses: actions/setup-python@v5 + with: + python-version: "3.x" + - run: pip install platformio + - run: platformio platform install ${{ matrix.platform }} + + - run: platformio ci "examples/Demo/Demo.ino" -l '.' -b ${{ matrix.board }} ${{ matrix.opts }} + - run: platformio ci "examples/Demo_AP/Demo_AP.ino" -l '.' -b ${{ matrix.board }} ${{ matrix.opts }} + - run: platformio ci "examples/Logging/Logging.ino" -l '.' -b ${{ matrix.board }} ${{ matrix.opts }} + - run: platformio ci "examples/HighPerf/HighPerf.ino" -l '.' -b ${{ matrix.board }} ${{ matrix.opts }} diff --git a/lib/WebSerialLite/.github/workflows/dependabot.yml b/lib/WebSerialLite/.github/workflows/dependabot.yml new file mode 100644 index 0000000..da098fd --- /dev/null +++ b/lib/WebSerialLite/.github/workflows/dependabot.yml @@ -0,0 +1,19 @@ +name: PlatformIO Dependabot + +on: + workflow_dispatch: + schedule: + # Runs every day at 01:00 + - cron: "0 1 * * *" + +jobs: + dependabot: + runs-on: ubuntu-latest + name: PlatformIO Dependabot + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: run PlatformIO Dependabot + uses: peterus/platformio_dependabot@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/lib/WebSerialLite/.github/workflows/stale.yaml b/lib/WebSerialLite/.github/workflows/stale.yaml new file mode 100644 index 0000000..14ceb43 --- /dev/null +++ b/lib/WebSerialLite/.github/workflows/stale.yaml @@ -0,0 +1,24 @@ +name: "Close stale issues and PRs" +on: + schedule: + - cron: "30 1 * * *" + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + stale-issue-message: "This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days." + stale-pr-message: "This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days." + close-issue-message: "This issue was closed because it has been stalled for 7 days with no activity." + close-pr-message: "This PR was closed because it has been stalled for 7 days with no activity." + days-before-issue-stale: 30 + days-before-pr-stale: 30 + days-before-issue-close: 7 + days-before-pr-close: 7 + +permissions: + # contents: write # only for delete-branch option + issues: write + pull-requests: write diff --git a/lib/WebSerialLite/.gitignore b/lib/WebSerialLite/.gitignore new file mode 100644 index 0000000..68d1489 --- /dev/null +++ b/lib/WebSerialLite/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +.lh +/.pio +/.vscode/* +!/.vscode/settings.json +/logs +/frontend/node_modules diff --git a/lib/WebSerialLite/LICENSE b/lib/WebSerialLite/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/lib/WebSerialLite/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/lib/WebSerialLite/README.md b/lib/WebSerialLite/README.md new file mode 100644 index 0000000..e4d42b9 --- /dev/null +++ b/lib/WebSerialLite/README.md @@ -0,0 +1,67 @@ +# WebSerialLite + +[![License: LGPL 3.0](https://img.shields.io/badge/License-GPL%203.0-yellow.svg)](https://opensource.org/license/gpl-3-0/) +[![Continuous Integration](https://github.com/mathieucarbou/WebSerialLite/actions/workflows/ci.yml/badge.svg)](https://github.com/mathieucarbou/WebSerialLite/actions/workflows/ci.yml) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/WebSerialLite.svg)](https://registry.platformio.org/libraries/mathieucarbou/WebSerialLite) + +WebSerial is a Serial Monitor for ESP32 that can be accessed remotely via a web browser. Webpage is stored in program memory of the microcontroller. + +This fork is based on [asjdf/WebSerialLite](https://github.com/asjdf/WebSerialLite). + +## Changes in this fork + +- Simplified callbacks +- Fixed UI +- Fixed Web Socket auto reconnect +- Fixed Web Socket client cleanup (See `WEBSERIAL_MAX_WS_CLIENTS`) +- Command history (up/down arrow keys) saved in local storage +- Support logo and fallback to title if not found. +- Arduino 3 / ESP-IDF 5.1 Compatibility +- Improved performance: can stream up to 20 lines per second is possible + +To add a logo, add a handler for `/logo` to serve your logo in the image format you want, gzipped or not. +You can use the [ESP32 embedding mechanism](https://docs.platformio.org/en/latest/platforms/espressif32.html). + +## Preview + +![Preview](https://s2.loli.net/2022/08/27/U9mnFjI7frNGltO.png) + +[DemoVideo](https://www.bilibili.com/video/BV1Jt4y1E7kj) + +## Features + +- Works on WebSockets +- Realtime logging +- Any number of Serial Monitors can be opened on the browser +- Uses Async Webserver for better performance +- Light weight (<3k) +- Timestamp +- Event driven + +## Dependencies + +- [mathieucarbou/ESPAsyncWebServer](https://github.com/mathieucarbou/ESPAsyncWebServer) + +## Usage + +```c++ + WebSerial.onMessage([](const String& msg) { Serial.println(msg); }); + WebSerial.begin(server); + + WebSerial.print("foo bar baz"); +``` + +If you need line buffering to use print(c), printf, write(c), etc: + +```c++ + WebSerial.onMessage([](const String& msg) { Serial.println(msg); }); + WebSerial.begin(server); + + WebSerial.setBuffer(100); // initial buffer size + + WebSerial.printf("Line 1: %" PRIu32 "\nLine 2: %" PRIu32, count, ESP.getFreeHeap()); + WebSerial.println(); + WebSerial.print("Line "); + WebSerial.print(3); + WebSerial.println(); +``` diff --git a/lib/WebSerialLite/docs/_config.yml b/lib/WebSerialLite/docs/_config.yml new file mode 100644 index 0000000..39d2e02 --- /dev/null +++ b/lib/WebSerialLite/docs/_config.yml @@ -0,0 +1,8 @@ +# bundle exec jekyll serve --host=0.0.0.0 + +title: WebSerialLite +description: "WebSerial is a Serial Monitor for ESP32 that can be accessed remotely via a web browser." +remote_theme: pages-themes/cayman@v0.2.0 +plugins: + - jekyll-remote-theme + \ No newline at end of file diff --git a/lib/WebSerialLite/docs/index.md b/lib/WebSerialLite/docs/index.md new file mode 100644 index 0000000..e4d42b9 --- /dev/null +++ b/lib/WebSerialLite/docs/index.md @@ -0,0 +1,67 @@ +# WebSerialLite + +[![License: LGPL 3.0](https://img.shields.io/badge/License-GPL%203.0-yellow.svg)](https://opensource.org/license/gpl-3-0/) +[![Continuous Integration](https://github.com/mathieucarbou/WebSerialLite/actions/workflows/ci.yml/badge.svg)](https://github.com/mathieucarbou/WebSerialLite/actions/workflows/ci.yml) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/WebSerialLite.svg)](https://registry.platformio.org/libraries/mathieucarbou/WebSerialLite) + +WebSerial is a Serial Monitor for ESP32 that can be accessed remotely via a web browser. Webpage is stored in program memory of the microcontroller. + +This fork is based on [asjdf/WebSerialLite](https://github.com/asjdf/WebSerialLite). + +## Changes in this fork + +- Simplified callbacks +- Fixed UI +- Fixed Web Socket auto reconnect +- Fixed Web Socket client cleanup (See `WEBSERIAL_MAX_WS_CLIENTS`) +- Command history (up/down arrow keys) saved in local storage +- Support logo and fallback to title if not found. +- Arduino 3 / ESP-IDF 5.1 Compatibility +- Improved performance: can stream up to 20 lines per second is possible + +To add a logo, add a handler for `/logo` to serve your logo in the image format you want, gzipped or not. +You can use the [ESP32 embedding mechanism](https://docs.platformio.org/en/latest/platforms/espressif32.html). + +## Preview + +![Preview](https://s2.loli.net/2022/08/27/U9mnFjI7frNGltO.png) + +[DemoVideo](https://www.bilibili.com/video/BV1Jt4y1E7kj) + +## Features + +- Works on WebSockets +- Realtime logging +- Any number of Serial Monitors can be opened on the browser +- Uses Async Webserver for better performance +- Light weight (<3k) +- Timestamp +- Event driven + +## Dependencies + +- [mathieucarbou/ESPAsyncWebServer](https://github.com/mathieucarbou/ESPAsyncWebServer) + +## Usage + +```c++ + WebSerial.onMessage([](const String& msg) { Serial.println(msg); }); + WebSerial.begin(server); + + WebSerial.print("foo bar baz"); +``` + +If you need line buffering to use print(c), printf, write(c), etc: + +```c++ + WebSerial.onMessage([](const String& msg) { Serial.println(msg); }); + WebSerial.begin(server); + + WebSerial.setBuffer(100); // initial buffer size + + WebSerial.printf("Line 1: %" PRIu32 "\nLine 2: %" PRIu32, count, ESP.getFreeHeap()); + WebSerial.println(); + WebSerial.print("Line "); + WebSerial.print(3); + WebSerial.println(); +``` diff --git a/lib/WebSerialLite/examples/Demo/Demo.ino b/lib/WebSerialLite/examples/Demo/Demo.ino new file mode 100644 index 0000000..0d2344f --- /dev/null +++ b/lib/WebSerialLite/examples/Demo/Demo.ino @@ -0,0 +1,87 @@ +/* + -------------- + WebSerial Demo + -------------- + + Skill Level: Beginner + + This example provides with a bare minimal app with WebSerial functionality. + + Github: https://github.com/ayushsharma82/WebSerial + Wiki: https://docs.webserial.pro + + Works with following hardware: + - ESP8266 + - ESP32 + + WebSerial terminal will be accessible at your microcontroller's /webserial URL. + + Checkout WebSerial Pro: https://webserial.pro +*/ + +#include +#if defined(ESP8266) + #include + #include +#elif defined(ESP32) + #include + #include +#endif +#include +#include + +AsyncWebServer server(80); + +const char* ssid = ""; // Your WiFi SSID +const char* password = ""; // Your WiFi Password + +unsigned long last_print_time = millis(); + +void setup() { + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.printf("WiFi Failed!\n"); + return; + } + + // Once connected, print IP + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hi! This is WebSerial demo. You can access webserial interface at http://" + WiFi.localIP().toString() + "/webserial"); + }); + + // WebSerial is accessible at "/webserial" in browser + WebSerial.begin(&server); + + /* Attach Message Callback */ + WebSerial.onMessage([&](uint8_t *data, size_t len) { + Serial.printf("Received %u bytes from WebSerial: ", len); + Serial.write(data, len); + Serial.println(); + WebSerial.println("Received Data..."); + String d = ""; + for(size_t i=0; i < len; i++){ + d += char(data[i]); + } + WebSerial.println(d); + }); + + // Start server + server.begin(); +} + +void loop() { + // Print every 2 seconds (non-blocking) + if ((unsigned long)(millis() - last_print_time) > 2000) { + WebSerial.print(F("IP address: ")); + WebSerial.println(WiFi.localIP()); + WebSerial.printf("Uptime: %lums\n", millis()); + WebSerial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + last_print_time = millis(); + } +} diff --git a/lib/WebSerialLite/examples/Demo_AP/Demo_AP.ino b/lib/WebSerialLite/examples/Demo_AP/Demo_AP.ino new file mode 100644 index 0000000..45153e1 --- /dev/null +++ b/lib/WebSerialLite/examples/Demo_AP/Demo_AP.ino @@ -0,0 +1,80 @@ +/* + -------------- + WebSerial Demo + -------------- + + Skill Level: Beginner + + This example provides with a bare minimal app with WebSerial functionality using softAP mode. + + Github: https://github.com/ayushsharma82/WebSerial + Wiki: https://docs.webserial.pro + + Works with following hardware: + - ESP8266 + - ESP32 + + WebSerial terminal will be accessible at your microcontroller's /webserial URL. + + Checkout WebSerial Pro: https://webserial.pro +*/ + +#include +#if defined(ESP8266) + #include + #include +#elif defined(ESP32) + #include + #include +#endif +#include +#include + +AsyncWebServer server(80); + +const char* ssid = "WSLDemo"; // WiFi AP SSID +const char* password = ""; // WiFi AP Password + +unsigned long last_print_time = millis(); + +void setup() { + Serial.begin(115200); + WiFi.softAP(ssid, password); + // Once connected, print IP + Serial.print("IP Address: "); + Serial.println(WiFi.softAPIP()); + + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hi! This is WebSerial demo. You can access webserial interface at http://" + WiFi.softAPIP().toString() + "/webserial"); + }); + + // WebSerial is accessible at "/webserial" in browser + WebSerial.begin(&server); + + /* Attach Message Callback */ + WebSerial.onMessage([&](uint8_t *data, size_t len) { + Serial.printf("Received %u bytes from WebSerial: ", len); + Serial.write(data, len); + Serial.println(); + WebSerial.println("Received Data..."); + String d = ""; + for(size_t i=0; i < len; i++){ + d += char(data[i]); + } + WebSerial.println(d); + }); + + // Start server + server.begin(); +} + +void loop() { + // Print every 2 seconds (non-blocking) + if ((unsigned long)(millis() - last_print_time) > 2000) { + WebSerial.print(F("IP address: ")); + WebSerial.println(WiFi.softAPIP()); + WebSerial.printf("Uptime: %lums\n", millis()); + WebSerial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + last_print_time = millis(); + } +} diff --git a/lib/WebSerialLite/examples/HighPerf/HighPerf.ino b/lib/WebSerialLite/examples/HighPerf/HighPerf.ino new file mode 100644 index 0000000..72bee90 --- /dev/null +++ b/lib/WebSerialLite/examples/HighPerf/HighPerf.ino @@ -0,0 +1,69 @@ +/* + * This example shows how to use WebSerial variant to send data to the browser when timing, speed and latency are important. + * WebSerial focuses on reducing latency and increasing speed by enqueueing messages and sending them in a single packet. + * + * The responsibility is left to the caller to ensure that the messages sent are not too large or not too small and frequent. + * For example, use of printf(), write(c), print(c), etc are not recommended. + * + * This variant can allow WebSerial to support a high speed of more than 20 messages per second like in this example. + * + * It can be used to log data, debug, or send data to the browser in real-time without any delay. + * + * You might want to look at the Logging variant to see how to better use WebSerial for streaming logging. + * + * You might want to control these flags to control the async library performance: + * -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 + * -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + * -D WS_MAX_QUEUED_MESSAGES=128 + */ +#include +#if defined(ESP8266) +#include +#include +#elif defined(ESP32) +#include +#include +#endif +#include +#include +#include +#include + +AsyncWebServer server(80); + +static const char* dict = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890"; +static uint32_t last = millis(); +static uint32_t count = 0; + +void setup() { + Serial.begin(115200); + + WiFi.softAP("WSLDemo"); + Serial.print("IP Address: "); + Serial.println(WiFi.softAPIP().toString()); + + WebSerial.onMessage([](const String& msg) { Serial.println(msg); }); + WebSerial.begin(&server); + + server.onNotFound([](AsyncWebServerRequest* request) { request->redirect("/webserial"); }); + server.begin(); +} + +void loop() { + if (millis() - last > 50) { + count++; + long r = random(10, 250) + 15; + String buffer; + buffer.reserve(r); + buffer += count; + while (buffer.length() < 10) { + buffer += " "; + } + buffer += ""; + for (int i = 0; i < r; i++) { + buffer += dict[random(0, 62)]; + } + WebSerial.print(buffer); + last = millis(); + } +} diff --git a/lib/WebSerialLite/examples/Logging/Logging.ino b/lib/WebSerialLite/examples/Logging/Logging.ino new file mode 100644 index 0000000..7327193 --- /dev/null +++ b/lib/WebSerialLite/examples/Logging/Logging.ino @@ -0,0 +1,55 @@ +/* + * This example shows how to use WebSerial variant to send logging data to the browser. + * + * Before using this example, make sure to look at the WebSerial example before and its description.\ + * + * You might want to control these flags to control the async library performance: + * -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 + * -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + * -D WS_MAX_QUEUED_MESSAGES=128 + */ +#include +#if defined(ESP8266) +#include +#include +#elif defined(ESP32) +#include +#include +#endif +#include +#include +#include +#include + +AsyncWebServer server(80); + +static uint32_t last = millis(); +static uint32_t count = 0; + +void setup() { + Serial.begin(115200); + + WiFi.softAP("WSLDemo"); + Serial.print("IP Address: "); + Serial.println(WiFi.softAPIP().toString()); + + WebSerial.onMessage([](const String& msg) { Serial.println(msg); }); + WebSerial.begin(&server); + WebSerial.setBuffer(100); + + server.onNotFound([](AsyncWebServerRequest* request) { request->redirect("/webserial"); }); + server.begin(); +} + +void loop() { + if (millis() - last > 1000) { + count++; + + WebSerial.print(F("IP address: ")); + WebSerial.println(WiFi.softAPIP()); + WebSerial.printf("Uptime: %lums\n", millis()); + WebSerial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap()); + + last = millis(); + } +} diff --git a/lib/WebSerialLite/frontend/README.md b/lib/WebSerialLite/frontend/README.md new file mode 100644 index 0000000..dbfee36 --- /dev/null +++ b/lib/WebSerialLite/frontend/README.md @@ -0,0 +1,19 @@ +# Frontend + +The `index.html` is the only page of WebSerialLite and you can modify the page yourself and regenerate it. + +In addition, I am also very happy that you can participate in fixing the bugs of the library or enhancing the functions of the library. + +## Quick Start + +You can modify and regenerate the page in three step. The execution of the following commands is based on the project root directory and you should install NodeJS and pnpm first. + +```shell +cd .\frontend\ +pnpm i +pnpm build +``` + +The `finalize.js` will compress and html and generate a new `WebSerialWebPage.h` in `../src` floder automatically. + +Then you can rebuild your program, the new page ought be embedded in the firmware as expected. diff --git a/lib/WebSerialLite/frontend/finalize.js b/lib/WebSerialLite/frontend/finalize.js new file mode 100644 index 0000000..2eb09a0 --- /dev/null +++ b/lib/WebSerialLite/frontend/finalize.js @@ -0,0 +1,66 @@ +let path = require('path'); +let fs = require('fs'); +const {minify} = require('html-minifier-terser'); +let gzipAsync = require('@gfx/zopfli').gzipAsync; + +const SAVE_PATH = '../src'; + +function chunkArray(myArray, chunk_size) { + let index = 0; + let arrayLength = myArray.length; + let tempArray = []; + for (index = 0; index < arrayLength; index += chunk_size) { + let myChunk = myArray.slice(index, index + chunk_size); + tempArray.push(myChunk); + } + return tempArray; +} + +function addLineBreaks(buffer) { + let data = ''; + let chunks = chunkArray(buffer, 30); + chunks.forEach((chunk, index) => { + data += chunk.join(','); + if (index + 1 !== chunks.length) { + data += ',\n'; + } + }); + return data; +} + +(async function(){ + const indexHtml = fs.readFileSync(path.resolve(__dirname, './index.html')).toString(); + const indexHtmlMinify = await minify(indexHtml, { + collapseWhitespace: true, + removeComments: true, + removeAttributeQuotes: true, + removeRedundantAttributes: true, + removeScriptTypeAttributes: true, + removeStyleLinkTypeAttributes: true, + useShortDoctype: true, + minifyCSS: true, + minifyJS: true, + sortAttributes: true, // 不会改变生成的html长度 但会优化压缩后体积 + sortClassName: true, // 不会改变生成的html长度 但会优化压缩后体积 + }); + console.log(`[finalize.js] Minified index.html | Original Size: ${(indexHtml.length / 1024).toFixed(2) }KB | Minified Size: ${(indexHtmlMinify.length / 1024).toFixed(2) }KB`); + + try{ + const GZIPPED_INDEX = await gzipAsync(indexHtmlMinify, { numiterations: 15 }); + + const FILE = +`#ifndef _webserial_webapge_h +#define _webserial_webpage_h +const uint32_t WEBSERIAL_HTML_SIZE = ${GZIPPED_INDEX.length}; +const uint8_t WEBSERIAL_HTML[] PROGMEM = { +${ addLineBreaks(GZIPPED_INDEX) } +}; +#endif +`; + + fs.writeFileSync(path.resolve(__dirname, SAVE_PATH+'/WebSerialWebPage.h'), FILE); + console.log(`[finalize.js] Compressed Bundle into WebSerialWebPage.h header file | Total Size: ${(GZIPPED_INDEX.length / 1024).toFixed(2) }KB`) + }catch(err){ + return console.error(err); + } + })(); \ No newline at end of file diff --git a/lib/WebSerialLite/frontend/index.html b/lib/WebSerialLite/frontend/index.html new file mode 100644 index 0000000..8bf3da2 --- /dev/null +++ b/lib/WebSerialLite/frontend/index.html @@ -0,0 +1,364 @@ + + + + + + + Web Console + + + + + +
+

Web Console

+ + + + +
+
+ + + +
+ +
+ +
+
+

+

+ + + + \ No newline at end of file diff --git a/lib/WebSerialLite/frontend/package-lock.json b/lib/WebSerialLite/frontend/package-lock.json new file mode 100644 index 0000000..e66710c --- /dev/null +++ b/lib/WebSerialLite/frontend/package-lock.json @@ -0,0 +1,240 @@ +{ + "name": "frontend", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@gfx/zopfli": "^1.0.15", + "html-minifier-terser": "^7.1.0" + } + }, + "node_modules/@gfx/zopfli": { + "version": "1.0.15", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.5", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.19", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/acorn": { + "version": "8.10.0", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "license": "MIT" + }, + "node_modules/camel-case": { + "version": "4.1.2", + "license": "MIT", + "dependencies": { + "pascal-case": "^3.1.2", + "tslib": "^2.0.3" + } + }, + "node_modules/clean-css": { + "version": "5.3.2", + "license": "MIT", + "dependencies": { + "source-map": "~0.6.0" + }, + "engines": { + "node": ">= 10.0" + } + }, + "node_modules/commander": { + "version": "10.0.1", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/dot-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/html-minifier-terser": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "camel-case": "^4.1.2", + "clean-css": "~5.3.2", + "commander": "^10.0.0", + "entities": "^4.4.0", + "param-case": "^3.0.4", + "relateurl": "^0.2.7", + "terser": "^5.15.1" + }, + "bin": { + "html-minifier-terser": "cli.js" + }, + "engines": { + "node": "^14.13.1 || >=16.0.0" + } + }, + "node_modules/lower-case": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.3" + } + }, + "node_modules/no-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "lower-case": "^2.0.2", + "tslib": "^2.0.3" + } + }, + "node_modules/param-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "dot-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/pascal-case": { + "version": "3.1.2", + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/relateurl": { + "version": "0.2.7", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/terser": { + "version": "5.21.0", + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.6.2", + "license": "0BSD" + } + } +} diff --git a/lib/WebSerialLite/frontend/package.json b/lib/WebSerialLite/frontend/package.json new file mode 100644 index 0000000..d6aec35 --- /dev/null +++ b/lib/WebSerialLite/frontend/package.json @@ -0,0 +1,9 @@ +{ + "scripts": { + "build": "node finalize.js" + }, + "dependencies": { + "@gfx/zopfli": "^1.0.15", + "html-minifier-terser": "^7.1.0" + } +} diff --git a/lib/WebSerialLite/frontend/pnpm-lock.yaml b/lib/WebSerialLite/frontend/pnpm-lock.yaml new file mode 100644 index 0000000..cffcb68 --- /dev/null +++ b/lib/WebSerialLite/frontend/pnpm-lock.yaml @@ -0,0 +1,177 @@ +lockfileVersion: 5.3 + +specifiers: + '@gfx/zopfli': ^1.0.15 + html-minifier-terser: ^7.1.0 + +dependencies: + '@gfx/zopfli': 1.0.15 + html-minifier-terser: 7.1.0 + +packages: + + /@gfx/zopfli/1.0.15: + resolution: {integrity: sha512-7mBgpi7UD82fsff5ThQKet0uBTl4BYerQuc+/qA1ELTwWEiIedRTcD3JgiUu9wwZ2kytW8JOb165rSdAt8PfcQ==} + engines: {node: '>= 8'} + dependencies: + base64-js: 1.5.1 + dev: false + + /@jridgewell/gen-mapping/0.3.2: + resolution: {integrity: sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==} + engines: {node: '>=6.0.0'} + dependencies: + '@jridgewell/set-array': 1.1.2 + '@jridgewell/sourcemap-codec': 1.4.14 + '@jridgewell/trace-mapping': 0.3.17 + dev: false + + /@jridgewell/resolve-uri/3.1.0: + resolution: {integrity: sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==} + engines: {node: '>=6.0.0'} + dev: false + + /@jridgewell/set-array/1.1.2: + resolution: {integrity: sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==} + engines: {node: '>=6.0.0'} + dev: false + + /@jridgewell/source-map/0.3.2: + resolution: {integrity: sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw==} + dependencies: + '@jridgewell/gen-mapping': 0.3.2 + '@jridgewell/trace-mapping': 0.3.17 + dev: false + + /@jridgewell/sourcemap-codec/1.4.14: + resolution: {integrity: sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==} + dev: false + + /@jridgewell/trace-mapping/0.3.17: + resolution: {integrity: sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==} + dependencies: + '@jridgewell/resolve-uri': 3.1.0 + '@jridgewell/sourcemap-codec': 1.4.14 + dev: false + + /acorn/8.8.2: + resolution: {integrity: sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==} + engines: {node: '>=0.4.0'} + hasBin: true + dev: false + + /base64-js/1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + dev: false + + /buffer-from/1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + dev: false + + /camel-case/4.1.2: + resolution: {integrity: sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==} + dependencies: + pascal-case: 3.1.2 + tslib: 2.5.0 + dev: false + + /clean-css/5.2.0: + resolution: {integrity: sha512-2639sWGa43EMmG7fn8mdVuBSs6HuWaSor+ZPoFWzenBc6oN+td8YhTfghWXZ25G1NiiSvz8bOFBS7PdSbTiqEA==} + engines: {node: '>= 10.0'} + dependencies: + source-map: 0.6.1 + dev: false + + /commander/2.20.3: + resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + dev: false + + /commander/9.5.0: + resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==} + engines: {node: ^12.20.0 || >=14} + dev: false + + /dot-case/3.0.4: + resolution: {integrity: sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==} + dependencies: + no-case: 3.0.4 + tslib: 2.5.0 + dev: false + + /entities/4.4.0: + resolution: {integrity: sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==} + engines: {node: '>=0.12'} + dev: false + + /html-minifier-terser/7.1.0: + resolution: {integrity: sha512-BvPO2S7Ip0Q5qt+Y8j/27Vclj6uHC6av0TMoDn7/bJPhMWHI2UtR2e/zEgJn3/qYAmxumrGp9q4UHurL6mtW9Q==} + engines: {node: ^14.13.1 || >=16.0.0} + hasBin: true + dependencies: + camel-case: 4.1.2 + clean-css: 5.2.0 + commander: 9.5.0 + entities: 4.4.0 + param-case: 3.0.4 + relateurl: 0.2.7 + terser: 5.16.3 + dev: false + + /lower-case/2.0.2: + resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==} + dependencies: + tslib: 2.5.0 + dev: false + + /no-case/3.0.4: + resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==} + dependencies: + lower-case: 2.0.2 + tslib: 2.5.0 + dev: false + + /param-case/3.0.4: + resolution: {integrity: sha512-RXlj7zCYokReqWpOPH9oYivUzLYZ5vAPIfEmCTNViosC78F8F0H9y7T7gG2M39ymgutxF5gcFEsyZQSph9Bp3A==} + dependencies: + dot-case: 3.0.4 + tslib: 2.5.0 + dev: false + + /pascal-case/3.1.2: + resolution: {integrity: sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==} + dependencies: + no-case: 3.0.4 + tslib: 2.5.0 + dev: false + + /relateurl/0.2.7: + resolution: {integrity: sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=} + engines: {node: '>= 0.10'} + dev: false + + /source-map-support/0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + dev: false + + /source-map/0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + dev: false + + /terser/5.16.3: + resolution: {integrity: sha512-v8wWLaS/xt3nE9dgKEWhNUFP6q4kngO5B8eYFUuebsu7Dw/UNAnpUod6UHo04jSSkv8TzKHjZDSd7EXdDQAl8Q==} + engines: {node: '>=10'} + hasBin: true + dependencies: + '@jridgewell/source-map': 0.3.2 + acorn: 8.8.2 + commander: 2.20.3 + source-map-support: 0.5.21 + dev: false + + /tslib/2.5.0: + resolution: {integrity: sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==} + dev: false diff --git a/lib/WebSerialLite/library.json b/lib/WebSerialLite/library.json new file mode 100644 index 0000000..11a5e02 --- /dev/null +++ b/lib/WebSerialLite/library.json @@ -0,0 +1,44 @@ +{ + "name": "WebSerialLite", + "version": "6.1.0", + "keywords": "WebSerial, serial, monitor, ESP8266, ESP32, webpage, websocket, wireless", + "description": "WebSerial is a webpage based Serial Monitor to log, monitor, or debug your code remotely.", + "homepage": "https://github.com/mathieucarbou/WebSerialLite", + "repository": { + "type": "git", + "url": "https://github.com/mathieucarbou/WebSerial.git" + }, + "authors": [ + { + "name": "HomeboyC", + "email": "homeboyc@foxmail.com" + }, + { + "name": "Mathieu Carbou", + "email": "mathieu.carbou@gmail.com", + "maintainer": true + } + ], + "license": "GPL-3.0-or-later", + "frameworks": "arduino", + "platforms": ["espressif8266", "espressif32"], + "headers": ["WebSerialLite.h", "WebSerial.h"], + "dependencies": [ + { + "owner": "mathieucarbou", + "name": "ESP Async WebServer", + "version": "^3.0.6", + "platforms": ["espressif8266", "espressif32"] + } + ], + "export": { + "include": [ + "examples", + "src", + "library.json", + "library.properties", + "LICENSE", + "README.md" + ] + } +} diff --git a/lib/WebSerialLite/library.properties b/lib/WebSerialLite/library.properties new file mode 100644 index 0000000..e4633a1 --- /dev/null +++ b/lib/WebSerialLite/library.properties @@ -0,0 +1,10 @@ +name=WebSerialLite +version=6.1.0 +author=HomeboyC +category=Communication +maintainer=Mathieu Carbou +sentence=A Web based Serial Monitor for ESP8266 & ESP32 to debug your code remotely. +paragraph=WebSerial is a webpage based Serial Monitor to log, monitor, or debug your code remotely. +url=https://github.com/mathieucarbou/WebSerialLite +architectures=esp8266,esp32 +license=GPL-3.0-or-later diff --git a/lib/WebSerialLite/platformio.ini b/lib/WebSerialLite/platformio.ini new file mode 100644 index 0000000..c563c0e --- /dev/null +++ b/lib/WebSerialLite/platformio.ini @@ -0,0 +1,42 @@ +[env] +framework = arduino +build_flags = + -Wall -Wextra + -D CONFIG_ARDUHAL_LOG_COLORS + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG + -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 + -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 + -D WS_MAX_QUEUED_MESSAGES=128 +lib_deps = + mathieucarbou/ESP Async WebServer @ 3.0.6 +upload_protocol = esptool +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder, log2file + +[platformio] +lib_dir = . +src_dir = examples/Demo +; src_dir = examples/Demo_AP +; src_dir = examples/HighPerf +; src_dir = examples/Logging + +[env:arduino] +platform = espressif32 +board = esp32dev + +[env:arduino-2] +platform = espressif32@6.7.0 +board = esp32dev + +[env:arduino-3] +platform = espressif32 +platform_packages= + platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.2 + platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.2/esp32-arduino-libs-3.0.2.zip +board = esp32dev + +[env:esp8266] +platform = espressif8266 +board = huzzah +lib_deps = + mathieucarbou/ESP Async WebServer @ 3.0.6 diff --git a/lib/WebSerialLite/src/WebSerial.cpp b/lib/WebSerialLite/src/WebSerial.cpp new file mode 100644 index 0000000..331e90d --- /dev/null +++ b/lib/WebSerialLite/src/WebSerial.cpp @@ -0,0 +1,150 @@ +#include "WebSerial.h" + +#include "WebSerialWebPage.h" + +void WebSerialClass::setAuthentication(const String& username, const String& password) { + _username = username; + _password = password; + _authenticate = !_username.isEmpty() && !_password.isEmpty(); + if (_ws) { + _ws->setAuthentication(_username.c_str(), _password.c_str()); + } +} + +void WebSerialClass::begin(AsyncWebServer* server, const char* url) { + _server = server; + + String backendUrl = url; + backendUrl.concat("ws"); + _ws = new AsyncWebSocket(backendUrl); + + if (_authenticate) { + _ws->setAuthentication(_username.c_str(), _password.c_str()); + } + + _server->on(url, HTTP_GET, [&](AsyncWebServerRequest* request) { + if (_authenticate) { + if (!request->authenticate(_username.c_str(), _password.c_str())) + return request->requestAuthentication(); + } + AsyncWebServerResponse* response = request->beginResponse(200, "text/html", WEBSERIAL_HTML, sizeof(WEBSERIAL_HTML)); + response->addHeader("Content-Encoding", "gzip"); + request->send(response); + }); + + _ws->onEvent([&](__unused AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, __unused void* arg, uint8_t* data, __unused size_t len) -> void { + if (type == WS_EVT_CONNECT) { + client->setCloseClientOnQueueFull(false); + return; + } + if (type == WS_EVT_DATA) { + AwsFrameInfo* info = (AwsFrameInfo*)arg; + if (info->final && info->index == 0 && info->len == len) { + if (info->opcode == WS_TEXT) { + data[len] = 0; + } + if (strcmp((char*)data, "ping") == 0) + client->text("pong"); + else if (_recv) + _recv(data, len); + } + } + }); + + _server->addHandler(_ws); +} + +void WebSerialClass::onMessage(WSLMessageHandler recv) { + _recv = recv; +} + +void WebSerialClass::onMessage(WSLStringMessageHandler callback) { + _recv = [&](uint8_t* data, size_t len) { + if (data && len) { +#ifdef ESP8266 + String msg; + msg.reserve(len); + msg.concat((char*)data, len); + callback(msg); +#else + callback(String((char*)data, len)); +#endif + } + }; +} + +size_t WebSerialClass::write(uint8_t m) { + if (!_ws) + return 0; + + // We do not support non-buffered write on webserial for the HIGH_PERF version + // we fail with a stack trace allowing the user to change the code to use write(const uint8_t* buffer, size_t size) instead + if (!_initialBufferCapacity) { +#ifdef ESP8266 + ets_printf("'-D WSL_FAIL_ON_NON_BUFFERED_WRITE' is set: non-buffered write is not supported. Please use write(const uint8_t* buffer, size_t size) instead."); +#else + log_e("'-D WSL_FAIL_ON_NON_BUFFERED_WRITE' is set: non-buffered write is not supported. Please use write(const uint8_t* buffer, size_t size) instead."); +#endif + assert(false); + return 0; + } + + write(&m, 1); + return (1); +} + +size_t WebSerialClass::write(const uint8_t* buffer, size_t size) { + if (!_ws || size == 0) + return 0; + + // No buffer, send directly (i.e. use case for log streaming) + if (!_initialBufferCapacity) { + size = buffer[size - 1] == '\n' ? size - 1 : size; + _send(buffer, size); + return size; + } + + // fill the buffer while sending data for each EOL + size_t start = 0, end = 0; + while (end < size) { + if (buffer[end] == '\n') { + if (end > start) { + _buffer.concat(reinterpret_cast(buffer + start), end - start); + } + _send(reinterpret_cast(_buffer.c_str()), _buffer.length()); + start = end + 1; + } + end++; + } + if (end > start) { + _buffer.concat(reinterpret_cast(buffer + start), end - start); + } + return size; +} + +void WebSerialClass::_send(const uint8_t* buffer, size_t size) { + if (_ws && size > 0) { + _ws->cleanupClients(WSL_MAX_WS_CLIENTS); + if (_ws->count()) { + _ws->textAll((const char*)buffer, size); + } + } + + // if buffer grew too much, free it, otherwise clear it + if (_initialBufferCapacity) { + if (_buffer.length() > _initialBufferCapacity) { + setBuffer(_initialBufferCapacity); + } else { + _buffer.clear(); + } + } +} + +void WebSerialClass::setBuffer(size_t initialCapacity) { + assert(initialCapacity <= UINT16_MAX); + _initialBufferCapacity = initialCapacity; + _buffer = String(); + _buffer.reserve(initialCapacity); +} + +WebSerialClass WebSerial; diff --git a/lib/WebSerialLite/src/WebSerial.h b/lib/WebSerialLite/src/WebSerial.h new file mode 100644 index 0000000..695b8a0 --- /dev/null +++ b/lib/WebSerialLite/src/WebSerial.h @@ -0,0 +1,68 @@ +#ifndef WebSerial_h +#define WebSerial_h + +#if defined(ESP8266) +#include "ESP8266WiFi.h" +#elif defined(ESP32) +#include "WiFi.h" +#endif + +#include +#include +#include + +#define WSL_VERSION "6.1.0" +#define WSL_VERSION_MAJOR 6 +#define WSL_VERSION_MINOR 1 +#define WSL_VERSION_REVISION 0 +#define WSL_FORK_mathieucarbou + +#ifndef WSL_MAX_WS_CLIENTS +#define WSL_MAX_WS_CLIENTS DEFAULT_MAX_WS_CLIENTS +#endif + +// High performance mode: +// - Low memory footprint (no stack allocation, no global buffer by default) +// - Low latency (messages sent immediately to the WebSocket queue) +// - High throughput (up to 20 messages per second, no locking mechanism) +// Also recommended to tweak AsyncTCP and ESPAsyncWebServer settings, for example: +// -D CONFIG_ASYNC_TCP_QUEUE_SIZE=128 // AsyncTCP queue size +// -D CONFIG_ASYNC_TCP_RUNNING_CORE=1 // core for the async_task +// -D WS_MAX_QUEUED_MESSAGES=128 // WS message queue size + +typedef std::function WSLMessageHandler; +typedef std::function WSLStringMessageHandler; + +class WebSerialClass : public Print { + public: + void begin(AsyncWebServer* server, const char* url = "/webserial"); + inline void setAuthentication(const char* username, const char* password) { setAuthentication(String(username), String(password)); } + void setAuthentication(const String& username, const String& password); + void onMessage(WSLMessageHandler recv); + void onMessage(WSLStringMessageHandler recv); + size_t write(uint8_t) override; + size_t write(const uint8_t* buffer, size_t size) override; + + // A buffer (shared across cores) can be initialised with an initial capacity to be able to use any Print functions event those that are not buffered and would + // create a performance impact for WS calls. The goal of this buffer is to be used with lines ending with '\n', like log messages. + // The buffer size will eventually grow until a '\n' is found, then the message will be sent to the WS clients and a new buffer will be created. + // Set initialCapacity to 0 to disable buffering. + // Must be called before begin(): calling it after will erase the buffer and its content will be lost. + // The buffer is not enabled by default. + void setBuffer(size_t initialCapacity); + + private: + // Server + AsyncWebServer* _server; + AsyncWebSocket* _ws; + WSLMessageHandler _recv = nullptr; + bool _authenticate = false; + String _username; + String _password; + size_t _initialBufferCapacity = 0; + String _buffer; + void _send(const uint8_t* buffer, size_t size); +}; + +extern WebSerialClass WebSerial; +#endif diff --git a/lib/WebSerialLite/src/WebSerialLite.h b/lib/WebSerialLite/src/WebSerialLite.h new file mode 100644 index 0000000..426d8aa --- /dev/null +++ b/lib/WebSerialLite/src/WebSerialLite.h @@ -0,0 +1 @@ +#include "./WebSerial.h" diff --git a/lib/WebSerialLite/src/WebSerialWebPage.h b/lib/WebSerialLite/src/WebSerialWebPage.h new file mode 100644 index 0000000..dd40bd5 --- /dev/null +++ b/lib/WebSerialLite/src/WebSerialWebPage.h @@ -0,0 +1,96 @@ +#ifndef _webserial_webapge_h +#define _webserial_webpage_h +const uint32_t WEBSERIAL_HTML_SIZE = 2696; +const uint8_t WEBSERIAL_HTML[] PROGMEM = { +31,139,8,0,0,0,0,0,2,3,116,86,119,151,163,54,16,255,42,10,151,178,206,179,112,185,189,45,20,167, +247,222,243,175,64,131,81,86,72,68,18,46,225,241,221,51,72,176,245,221,22,51,204,155,242,155,238,236,29,174, +75,119,110,129,212,174,145,187,108,250,4,198,119,89,3,142,145,178,102,198,130,203,59,87,209,155,153,167,149,3, +229,242,232,155,47,114,224,123,136,80,217,181,20,254,237,196,33,255,155,254,241,9,253,76,55,45,115,162,144,176, +203,156,112,248,248,11,10,242,153,86,86,75,200,86,158,245,220,216,81,112,87,231,28,14,162,4,234,95,150,66, +9,39,152,164,182,100,18,242,77,68,20,107,32,63,8,56,182,218,184,93,102,221,25,237,112,113,232,185,176,173, +100,231,164,144,186,188,27,88,223,48,179,23,42,137,47,13,52,169,131,147,163,28,74,109,16,147,86,137,210,10, +134,15,151,73,194,42,7,6,159,5,84,218,64,79,143,80,220,9,71,11,125,162,86,252,39,212,62,17,170,6, +35,92,250,146,53,180,179,147,53,89,147,13,250,25,10,205,207,189,62,128,177,165,209,82,210,2,106,118,16,218, +120,135,105,13,98,95,187,100,179,94,191,151,250,240,2,57,27,73,91,198,57,218,71,170,194,148,208,138,53,66, +158,19,202,218,86,2,181,103,235,160,89,134,7,237,196,242,83,41,212,221,15,172,252,205,115,190,68,141,101,244, +27,236,53,144,63,190,137,150,191,234,66,59,189,140,190,6,121,0,39,74,70,126,132,14,162,165,101,202,82,139, +240,171,33,246,89,41,65,57,48,189,167,153,20,123,149,4,206,16,239,13,59,247,165,150,8,255,213,213,213,245, +230,230,118,136,109,205,184,62,246,149,144,40,146,112,163,91,26,88,23,107,114,217,158,200,107,252,55,251,2,223, +198,223,21,137,215,215,139,5,121,42,183,69,153,237,11,185,171,197,98,136,143,180,234,164,236,31,146,51,162,16, +252,190,184,227,11,178,88,75,183,61,126,38,241,155,49,235,113,37,225,116,47,51,190,140,106,8,115,36,233,72, +37,155,33,254,167,179,78,84,103,42,48,91,150,130,226,253,19,78,2,10,77,27,221,41,14,188,47,180,225,96, +168,97,92,116,118,118,99,161,28,187,167,127,212,10,147,28,114,210,130,149,119,123,175,79,167,164,85,55,213,109, +197,134,184,97,66,61,129,151,122,96,92,152,96,48,65,249,174,81,233,140,103,26,8,47,74,173,99,198,165,190, +50,19,208,80,159,71,221,196,15,117,112,66,226,150,41,5,178,111,181,21,222,178,1,201,156,56,64,26,128,34, +166,170,154,104,234,103,39,177,90,10,62,179,124,226,67,184,233,211,20,140,237,253,50,68,111,46,40,149,76,150, +23,99,201,8,245,179,176,8,77,140,121,130,164,1,180,209,76,141,78,157,110,147,109,72,233,132,151,20,157,115, +152,216,178,51,22,173,182,90,248,8,231,121,184,193,102,217,172,241,3,137,151,86,117,231,164,80,16,194,241,131, +54,7,187,78,31,161,124,137,125,189,190,186,174,46,159,97,72,184,176,172,144,192,251,151,10,111,216,213,230,234, +246,94,225,149,129,18,29,245,13,198,52,21,227,117,188,245,185,155,145,135,76,26,240,120,15,96,198,65,148,233, +219,22,196,240,106,172,60,242,105,192,242,80,70,86,88,45,59,7,41,230,110,54,234,29,122,250,185,222,156,206, +183,71,192,36,98,33,22,3,233,59,59,182,2,72,40,221,148,188,123,173,49,113,176,185,228,247,225,108,167,66, +164,79,150,109,122,159,207,53,142,162,214,227,58,153,52,124,219,16,4,249,182,230,25,226,82,183,103,31,203,172, +67,11,141,232,27,84,13,163,173,153,163,18,42,215,123,50,25,201,153,29,244,2,223,211,67,182,10,23,33,91, +133,11,54,46,228,93,198,197,129,148,146,89,155,71,126,76,166,65,38,143,22,96,132,55,111,67,4,207,253,101, +34,222,74,62,135,137,121,121,118,191,234,205,46,99,164,54,80,229,43,178,203,68,179,31,117,165,222,107,130,178, +198,104,147,35,124,44,244,247,200,186,88,16,107,202,124,37,145,70,100,236,9,160,176,22,201,184,217,136,95,108, +36,180,87,20,164,208,234,211,226,238,178,240,156,245,167,141,69,130,157,8,221,151,82,148,119,185,3,131,141,201, +228,103,18,152,186,88,224,169,60,236,9,51,130,209,90,112,14,42,119,166,3,194,153,99,84,160,135,156,131,4, +7,164,18,82,230,101,103,12,40,247,217,88,38,82,233,178,243,35,145,87,76,90,32,161,213,243,13,22,118,188, +195,159,234,83,30,93,93,18,252,187,185,189,26,255,35,18,14,57,74,236,50,252,18,80,19,158,71,255,211,90, +5,173,109,52,49,244,175,232,203,93,66,35,105,52,242,249,131,178,135,228,212,146,123,25,2,14,216,77,105,96, +11,254,245,213,204,218,38,33,45,233,161,97,87,171,213,123,79,187,98,159,48,190,139,20,72,245,165,169,175,24, +220,25,181,146,162,4,53,116,219,206,69,171,244,137,3,103,9,103,18,220,214,224,165,56,119,44,141,90,146,42, +80,140,116,100,149,85,165,51,24,25,40,57,196,56,246,206,100,7,177,20,87,209,94,18,87,163,2,178,163,0, +47,224,74,187,204,123,171,214,147,16,96,112,25,227,120,242,131,68,47,179,29,179,125,137,136,62,30,207,16,56, +95,129,177,226,120,233,28,7,207,147,108,231,233,136,194,12,188,168,243,138,77,246,202,182,54,57,221,164,243,227, +99,100,74,39,242,122,182,19,254,210,207,155,135,111,195,132,79,135,167,159,183,79,89,255,247,186,190,121,215,224, +67,170,62,208,94,21,48,183,61,122,220,139,13,123,27,143,175,215,72,177,72,92,98,209,136,62,41,224,81,195, +69,0,25,171,200,124,192,159,92,14,235,12,131,154,104,66,219,185,119,227,190,117,100,133,103,46,155,238,109,231, +191,247,232,78,179,115,27,83,153,118,32,149,10,86,135,234,121,221,139,69,159,48,39,48,57,152,220,152,111,209, +124,110,118,158,142,230,12,206,188,72,2,85,125,95,211,111,101,59,221,89,24,52,46,107,213,55,91,105,252,118, +143,170,126,181,32,46,176,93,25,10,143,81,248,95,109,204,151,199,227,67,254,137,56,126,207,149,121,13,188,191, +51,125,44,13,246,199,31,253,240,129,63,13,181,72,106,254,23,55,114,216,244,215,251,228,158,133,57,11,179,120, +25,120,69,49,227,115,171,59,178,115,67,166,211,145,33,132,123,170,106,226,140,218,4,139,59,249,184,27,241,124, +173,32,227,146,97,162,112,65,47,213,149,127,97,202,117,124,15,167,6,174,65,126,91,205,198,182,104,165,122,47, +17,157,209,200,134,215,24,227,88,44,177,1,1,99,192,132,33,86,105,149,198,106,11,57,20,18,168,201,40,56, +213,67,241,100,160,8,147,247,84,79,69,76,85,64,73,41,22,106,7,73,4,117,215,101,164,95,205,89,135,114, +227,56,12,253,21,133,215,200,177,194,180,155,146,66,167,110,239,123,189,159,230,132,244,72,26,83,78,207,191,223, +3,41,219,162,36,111,188,158,182,45,150,89,30,64,242,129,120,80,56,56,52,44,129,242,252,201,131,166,17,9, +15,200,48,253,45,206,130,201,128,146,38,159,188,24,23,17,178,181,53,107,203,209,72,25,153,209,3,39,39,175, +129,34,104,108,107,190,95,142,92,246,172,26,129,95,65,135,25,207,101,57,159,240,88,225,142,237,0,109,148,180, +144,81,179,98,88,54,61,98,41,47,124,74,188,184,72,32,36,24,223,151,132,255,93,164,159,206,140,222,96,171, +8,8,224,170,125,249,225,201,219,131,230,38,249,159,199,43,227,239,94,89,64,198,157,20,101,31,169,51,66,233, +104,17,45,84,198,5,84,12,7,25,148,105,140,40,202,160,54,70,95,143,146,146,174,146,27,243,239,149,221,88, +90,250,26,149,78,6,223,52,194,204,21,166,250,56,183,101,175,217,200,103,199,139,124,184,178,255,198,188,228,93, +108,169,73,17,124,23,8,69,125,68,229,147,115,226,199,189,155,23,169,20,126,247,133,138,155,25,99,37,110,222, +8,104,170,214,254,252,196,150,249,224,198,252,241,87,216,2,196,107,131,130,116,152,121,201,84,87,53,119,83,93, +96,165,35,148,246,131,165,138,167,14,116,124,193,72,167,183,116,165,183,140,112,186,82,60,140,173,242,107,0,232, +175,247,201,17,125,202,108,120,142,128,29,83,118,97,121,186,15,117,50,53,230,176,221,253,96,59,176,152,202,153, +31,220,97,87,223,247,156,69,124,41,7,73,241,138,110,222,15,200,90,169,194,21,52,145,238,64,14,91,70,100, +248,164,207,127,64,35,214,167,143,125,247,102,227,96,104,251,229,15,239,222,130,11,3,75,146,212,70,231,65,133, +45,250,156,178,163,242,56,112,162,230,57,236,67,27,14,42,106,202,144,169,42,14,58,107,148,86,117,126,51,131, +194,137,198,210,232,81,74,169,76,255,110,20,212,191,12,16,117,82,252,193,30,16,114,206,249,95,209,190,159,26, +149,126,130,6,105,199,97,164,145,124,44,181,247,251,65,197,107,180,166,226,199,97,225,166,214,1,166,201,232,42, +154,96,85,209,88,55,154,103,121,65,153,201,179,119,248,8,218,157,59,232,216,231,207,160,7,209,100,147,35,238, +123,227,158,130,94,95,13,160,239,9,127,134,103,225,89,243,89,140,70,141,244,228,18,221,175,113,196,4,108,41, +92,178,23,177,165,44,173,8,86,163,93,72,199,187,89,99,160,109,229,140,110,10,6,17,177,36,156,169,120,226, +138,38,99,12,161,130,75,233,219,111,37,105,12,224,73,7,116,152,12,207,57,50,102,95,150,91,132,84,56,220, +218,172,78,47,112,51,102,149,19,147,129,88,236,37,85,22,190,253,54,92,13,124,236,30,168,79,82,184,45,118, +113,46,87,63,21,147,181,108,203,86,96,45,46,182,131,109,107,25,179,103,12,193,254,242,118,103,251,226,202,198, +178,106,67,247,13,176,219,6,59,33,224,196,172,167,122,153,156,15,169,225,224,31,45,51,127,41,181,225,55,229, +0,91,29,28,113,107,108,175,215,229,124,167,159,157,155,245,37,46,30,28,172,5,144,191,8,36,61,114,89,62, +126,25,81,234,239,162,121,146,215,202,28,201,107,165,182,6,127,247,184,69,248,23,24,26,9,58,244,210,141,88, +16,49,117,220,192,53,36,127,251,117,35,133,235,229,225,110,126,170,129,26,96,84,183,36,163,136,34,207,142,4, +83,140,139,142,109,57,107,210,81,27,225,142,251,249,53,43,97,55,44,157,28,202,134,250,81,119,100,196,31,162, +39,57,41,28,36,37,41,93,230,80,74,137,31,243,67,57,128,73,169,122,226,175,72,244,168,39,254,204,196,195, +72,125,121,58,245,140,111,110,40,173,251,123,57,30,231,223,243,253,152,23,166,209,244,220,213,74,129,199,193,11, +155,187,208,148,17,34,158,21,116,130,89,75,10,64,100,149,74,230,179,2,102,51,56,102,134,139,170,97,27,81, +131,44,220,41,169,25,208,186,24,218,99,110,14,128,42,141,19,241,123,81,6,234,12,110,213,221,220,95,229,139, +183,19,142,217,147,13,11,209,154,105,11,228,23,146,203,221,136,40,18,231,242,79,205,170,192,102,14,223,241,81, +119,41,66,227,4,160,117,180,68,13,211,184,78,213,131,165,242,5,103,101,128,84,202,171,22,51,247,247,147,147, +2,95,210,155,31,74,48,126,193,140,197,144,126,247,254,201,91,48,151,231,204,35,229,222,99,222,60,58,174,201, +32,193,14,8,197,221,171,220,237,139,161,14,45,112,240,238,13,174,154,146,219,242,36,165,84,196,114,196,123,112, +61,168,24,128,133,43,99,107,169,170,214,182,150,220,47,57,255,7,236,22,1,194,250,28,0,0 +}; +#endif diff --git a/lib/WebServer/src/WebServer.cpp b/lib/WebServer/src/WebServer.cpp index a3c76b4..eed640b 100644 --- a/lib/WebServer/src/WebServer.cpp +++ b/lib/WebServer/src/WebServer.cpp @@ -108,9 +108,15 @@ static String md5str(String &in){ return String(out); memset(_buf, 0x00, 16); mbedtls_md5_init(&_ctx); + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) mbedtls_md5_starts_ret(&_ctx); mbedtls_md5_update_ret(&_ctx, (const uint8_t *)in.c_str(), in.length()); mbedtls_md5_finish_ret(&_ctx, _buf); + #else + mbedtls_md5_starts(&_ctx); + mbedtls_md5_update(&_ctx, (const uint8_t *)in.c_str(), in.length()); + mbedtls_md5_finish(&_ctx, _buf); + #endif for(i = 0; i < 16; i++) { sprintf(out + (i * 2), "%02x", _buf[i]); } diff --git a/lib/WebServer/src/WebServer.h b/lib/WebServer/src/WebServer.h index fce4fed..bf34baa 100644 --- a/lib/WebServer/src/WebServer.h +++ b/lib/WebServer/src/WebServer.h @@ -62,8 +62,8 @@ typedef struct { } HTTPUpload; #include "detail/RequestHandler.h" -#include "EthServer.h" -#include "EthClient.h" +#include +#include namespace fs { class FS; diff --git a/lib/WebServer/src/hardware/WifiEthClient.cpp b/lib/WebServer/src/hardware/WifiEthClient.cpp index 95abf2f..e3b60e6 100644 --- a/lib/WebServer/src/hardware/WifiEthClient.cpp +++ b/lib/WebServer/src/hardware/WifiEthClient.cpp @@ -18,7 +18,8 @@ uint8_t WifiEthClient::connected() int WifiEthClient::setTimeout(uint32_t seconds) { - return _wifiClient->setTimeout(seconds); + _wifiClient->setTimeout(seconds); + return seconds; } size_t WifiEthClient::write(const char *buffer, size_t size) diff --git a/lib/WebServer/src/hardware/WifiEthServer.cpp b/lib/WebServer/src/hardware/WifiEthServer.cpp index baf8538..a349288 100644 --- a/lib/WebServer/src/hardware/WifiEthServer.cpp +++ b/lib/WebServer/src/hardware/WifiEthServer.cpp @@ -38,7 +38,7 @@ EthClient* WifiEthServer::available() _wifiEthClient = nullptr; } - _wifiClient = _wifiServer.available(); + _wifiClient = _wifiServer.accept(); _wifiEthClient = new WifiEthClient(&_wifiClient); return _wifiEthClient; } diff --git a/lib/espMqttClient/.github/ISSUE_TEMPLATE/bug_report.md b/lib/espMqttClient/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..4eeb3bb --- /dev/null +++ b/lib/espMqttClient/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,34 @@ +--- +name: Bug report +about: Create a report to help us improve espMqttClient +title: "[BUG]" +labels: '' +assignees: '' + +--- + +#### Do not use to discuss topics! + +**Describe the bug** +A clear and concise description of what the bug is. + +Which platform, esp8266 or esp32? +Do you use TLS or not? +Do you use an IDE (Arduino, Platformio...)? +Which version of the Arduino framework? + +Please include any debug output and/or decoded stack trace if applicable. + +**Expected behaviour** +A clear and concise description of what you expected to happen. + +**To Reproduce** +Steps to reproduce the behaviour: + +**Example code** +```cpp +// Put code here to reproduce the bug, if possible +``` + +**Additional context** +Add any other context about the problem here. diff --git a/lib/espMqttClient/.github/etc/mosquitto.conf b/lib/espMqttClient/.github/etc/mosquitto.conf new file mode 100644 index 0000000..daa4137 --- /dev/null +++ b/lib/espMqttClient/.github/etc/mosquitto.conf @@ -0,0 +1,2 @@ +listener 1883 +allow_anonymous true \ No newline at end of file diff --git a/lib/espMqttClient/.github/workflows/arduino-lint.yml b/lib/espMqttClient/.github/workflows/arduino-lint.yml new file mode 100644 index 0000000..3c1a16d --- /dev/null +++ b/lib/espMqttClient/.github/workflows/arduino-lint.yml @@ -0,0 +1,9 @@ +name: Arduino Lint + +on: [push, pull_request] +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: arduino/arduino-lint-action@v1 diff --git a/lib/espMqttClient/.github/workflows/build_arduino-ide.yml b/lib/espMqttClient/.github/workflows/build_arduino-ide.yml new file mode 100644 index 0000000..0c06d50 --- /dev/null +++ b/lib/espMqttClient/.github/workflows/build_arduino-ide.yml @@ -0,0 +1,62 @@ +name: Build with Arduino IDE +on: + - push + - pull_request + +jobs: + build-for-esp8266: + runs-on: ubuntu-latest + + strategy: + matrix: + fqbn: + - esp8266:esp8266:generic + + steps: + - uses: actions/checkout@v3 + - uses: arduino/compile-sketches@v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + fqbn: ${{ matrix.fqbn }} + enable-deltas-report: true + platforms: | + - name: esp8266:esp8266 + source-url: https://arduino.esp8266.com/stable/package_esp8266com_index.json + sketch-paths: | + - examples/largepayload-esp8266 + - examples/simple-esp8266 + - examples/simpleAsync-esp8266 + - examples/tls-esp8266 + libraries: | + - name: espMqttClient + source-path: ./ + - name: ESPAsyncTCP + source-url: https://github.com/me-no-dev/ESPAsyncTCP.git + + build-for-esp32: + runs-on: ubuntu-latest + + strategy: + matrix: + fqbn: + - esp32:esp32:esp32 + + steps: + - uses: actions/checkout@v3 + - uses: arduino/compile-sketches@v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + fqbn: ${{ matrix.fqbn }} + enable-deltas-report: true + platforms: | + - name: esp32:esp32 + source-url: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json + sketch-paths: | + - examples/simple-esp32 + - examples/simpleAsync-esp32 + - examples/tls-esp32 + libraries: | + - name: espMqttClient + source-path: ./ + - name: AsyncTCP + source-url: https://github.com/me-no-dev/AsyncTCP.git diff --git a/lib/espMqttClient/.github/workflows/build_platformio.yml b/lib/espMqttClient/.github/workflows/build_platformio.yml new file mode 100644 index 0000000..b1a139c --- /dev/null +++ b/lib/espMqttClient/.github/workflows/build_platformio.yml @@ -0,0 +1,90 @@ +name: Build with Platformio + +on: [push, pull_request] + +jobs: + build-for-esp8266: + runs-on: ubuntu-latest + strategy: + matrix: + example: [ + examples/largepayload-esp8266/largepayload-esp8266.ino, + examples/ota-esp8266/ota-esp8266.ino, + examples/simple-esp8266/simple-esp8266.ino, + examples/simpleAsync-esp8266/simpleAsync-esp8266.ino, + examples/tls-esp8266/tls-esp8266.ino + ] + steps: + - uses: actions/checkout@v3 + - uses: actions/cache@v3 + with: + path: | + ~/.cache/pip + ~/.platformio/.cache + key: ${{ runner.os }}-pio + - uses: actions/setup-python@v4 + with: + python-version: '3.9' + - name: Install PlatformIO Core + run: pip install --upgrade platformio + - name: Download external libraries + run: pio pkg install --global --library me-no-dev/ESPAsyncTCP + - name: Build PlatformIO examples + run: pio ci --lib="." --board=d1_mini + env: + PLATFORMIO_CI_SRC: ${{ matrix.example }} + + build-for-esp32: + runs-on: ubuntu-latest + strategy: + matrix: + example: [ + examples/notask-esp32/notask-esp32.ino, + examples/simple-esp32/simple-esp32.ino, + examples/simpleAsync-esp32/simpleAsync-esp32.ino, + examples/tls-esp32/tls-esp32.ino + ] + steps: + - uses: actions/checkout@v3 + - uses: actions/cache@v3 + with: + path: | + ~/.cache/pip + ~/.platformio/.cache + key: ${{ runner.os }}-pio + - uses: actions/setup-python@v4 + with: + python-version: '3.9' + - name: Install PlatformIO Core + run: pip install --upgrade platformio + - name: Download external libraries + run: pio pkg install --global --library me-no-dev/AsyncTCP + - name: Build PlatformIO examples + run: pio ci --lib="." --board=lolin32 + env: + PLATFORMIO_CI_SRC: ${{ matrix.example }} + + build-for-linux: + runs-on: ubuntu-latest + strategy: + matrix: + example: [ + examples/simple-linux/main.cpp + ] + steps: + - uses: actions/checkout@v3 + - uses: actions/cache@v3 + with: + path: | + ~/.cache/pip + ~/.platformio/.cache + key: ${{ runner.os }}-pio + - uses: actions/setup-python@v4 + with: + python-version: '3.9' + - name: Install PlatformIO Core + run: pip install --upgrade platformio + - name: Build PlatformIO examples + run: pio ci --lib="." --project-conf="./examples/simple-linux/platformio.ini" + env: + PLATFORMIO_CI_SRC: ${{ matrix.example }} diff --git a/lib/espMqttClient/.github/workflows/cppcheck.yml b/lib/espMqttClient/.github/workflows/cppcheck.yml new file mode 100644 index 0000000..cd02b46 --- /dev/null +++ b/lib/espMqttClient/.github/workflows/cppcheck.yml @@ -0,0 +1,22 @@ +name: Cppcheck + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install platformio + - name: Cppcheck + run: | + pio check --fail-on-defect=medium --fail-on-defect=high --flags "--inline-suppr --enable=warning --enable=style --enable=performance --suppress=unusedFunction --suppress=preprocessorErrorDirective" --skip-packages \ No newline at end of file diff --git a/lib/espMqttClient/.github/workflows/cpplint.yml b/lib/espMqttClient/.github/workflows/cpplint.yml new file mode 100644 index 0000000..36f64d5 --- /dev/null +++ b/lib/espMqttClient/.github/workflows/cpplint.yml @@ -0,0 +1,22 @@ +name: cpplint + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install cpplint + - name: Linting + run: | + cpplint --repository=. --recursive --filter=-whitespace/line_length,-build/include ./src \ No newline at end of file diff --git a/lib/espMqttClient/.github/workflows/test_platformio.yml b/lib/espMqttClient/.github/workflows/test_platformio.yml new file mode 100644 index 0000000..6a088b0 --- /dev/null +++ b/lib/espMqttClient/.github/workflows/test_platformio.yml @@ -0,0 +1,29 @@ +name: Test with Platformio + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + - name: Install dependencies + run: | + sudo apt update && sudo apt install -y valgrind + python -m pip install --upgrade pip + pip install platformio + - name: Start Mosquitto + uses: namoshek/mosquitto-github-action@v1 + with: + version: '2.0' + ports: '1883:1883' + config: ${{ github.workspace }}/.github/etc/mosquitto.conf + - name: Test + run: | + pio test -e native -v \ No newline at end of file diff --git a/lib/espMqttClient/.gitignore b/lib/espMqttClient/.gitignore new file mode 100644 index 0000000..00649df --- /dev/null +++ b/lib/espMqttClient/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode +cov +*cov.info +.idea diff --git a/lib/espMqttClient/README.md b/lib/espMqttClient/README.md index 2840306..7b0bfdd 100644 --- a/lib/espMqttClient/README.md +++ b/lib/espMqttClient/README.md @@ -15,7 +15,7 @@ Aims to be a non-blocking, fully compliant MQTT 3.1.1 client. - TCP and TCP/TLS using standard WiFiClient and WiFiClientSecure connections - Virtually unlimited incoming and outgoing payload sizes - Readable and understandable code -- Fully async clients available via [AsyncTCP](https://github.com/esphome/AsyncTCP) or [ESPAsnycTCP](https://github.com/esphome/ESPAsyncTCP) (no TLS supported) +- Fully async clients available via [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) or [ESPAsnycTCP](https://github.com/me-no-dev/ESPAsyncTCP) (no TLS supported). - Supported platforms: - Espressif ESP8266 and ESP32 using the Arduino framework - Espressif ESP32 using the ESP IDF, see [esp idf component](https://docs.espressif.com/projects/arduino-esp32/en/latest/esp-idf_component.html) @@ -23,6 +23,12 @@ Aims to be a non-blocking, fully compliant MQTT 3.1.1 client. > Linux compatibility is mainly for automatic testing. It relies on a quick and dirty Arduino-style `Client` with a POSIX TCP client underneath and Arduino-style `ClientPosixIPAddress` class. These are lacking many features needed for proper Linux support. +## Dependencies + +This libraries requires [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) and [ESPAsnycTCP](https://github.com/me-no-dev/ESPAsyncTCP). These libraries are not actively maintained and have some bugs. There are alternatives available on Github but make sure these alternatives fit in your project. + +Because of this, I have removed the explicit dependency. You will have to manually add the libraries so you can choose the version which best suites your code. + # Documentation See [documentation](https://www.emelis.net/espMqttClient/) and the [examples](examples/). diff --git a/lib/espMqttClient/docs/index.md b/lib/espMqttClient/docs/index.md index 077686b..4385ee9 100644 --- a/lib/espMqttClient/docs/index.md +++ b/lib/espMqttClient/docs/index.md @@ -10,13 +10,20 @@ - TCP and TCP/TLS using standard WiFiClient and WiFiClientSecure connections - Virtually unlimited incoming and outgoing payload sizes - Readable and understandable code -- Fully async clients available via [AsyncTCP](https://github.com/esphome/AsyncTCP) or [ESPAsnycTCP](https://github.com/esphome/ESPAsyncTCP) (no TLS supported) +- Fully async clients available via [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) or [ESPAsnycTCP](https://github.com/me-no-dev/ESPAsyncTCP) (no TLS supported). - Supported platforms: - Espressif ESP8266 and ESP32 using the Arduino framework + - Espressif ESP32 using the ESP IDF, see [esp idf component](https://docs.espressif.com/projects/arduino-esp32/en/latest/esp-idf_component.html) - Basic Linux compatibility*. This includes WSL on Windows > Linux compatibility is mainly for automatic testing. It relies on a quick and dirty Arduino-style `Client` with a POSIX TCP client underneath and Arduino-style `IPAddress` class. These are lacking many features needed for proper Linux support. +## Dependencies + +This libraries requires [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) and [ESPAsnycTCP](https://github.com/me-no-dev/ESPAsyncTCP). These libraries are not actively maintained and have some bugs. There are alternatives available on Github but make sure these alternatives fit in your project. + +Because of this, I have removed the explicit dependency. You will have to manually add the libraries so you can choose the version which best suites your code. + # Contents 1. [Runtime behaviour](#runtime-behaviour) @@ -410,6 +417,23 @@ This macro is by default not enabled so you can add a single callbacks to an eve You can enable a watchdog on the MQTT task. This is experimental and will probably result in resets because some (framework) function calls block without feeding the dog. +### EMC_USE_MEMPOOL 0 + +**Experimental** + +When set to `1`, (outgoing) MQTT packets and the outbox data is stored in a memory pool. The memory pool is part of the espMqttClient object and is thus allocated in the same memory type. There are two pools: one to hold the outgoing packets (dynamic size elements) and one for the outbox itself (fixed-size elements). + +#### EMC_NUM_POOL_ELEMENTS 32 + +This config variable is only used when enabling the memory pool. It defines +- the number of elements in the outbox-pool +- the number of blocks that will be allocated in the packet-pool + +#### EMC_SIZE_POOL_ELEMENTS 128 + +This defines the size of one packet-pool element. Together with `EMC_NUM_POOL_ELEMENTS`, you get the total packet-pool size. +The packet-pool can hold any size of element. The configuration only guarantees a minimum of `EMC_NUM_POOL_ELEMENTS` of size `EMC_SIZE_POOL_ELEMENTS` can fit in the pool. + ### Logging If needed, you have to enable logging at compile time. This is done differently on ESP32 and ESP8266. diff --git a/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino b/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino index 27bc675..867d883 100644 --- a/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino +++ b/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino @@ -31,13 +31,13 @@ void connectToMqtt() { void WiFiEvent(WiFiEvent_t event) { Serial.printf("[WiFi-event] event: %d\n", event); switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); connectToMqtt(); break; - case SYSTEM_EVENT_STA_DISCONNECTED: + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: Serial.println("WiFi lost connection"); break; default: @@ -117,7 +117,7 @@ void setup() { Serial.println(); Serial.println(); - WiFi.setAutoConnect(false); + WiFi.persistent(false); WiFi.setAutoReconnect(true); WiFi.onEvent(WiFiEvent); diff --git a/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp b/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp index 8833490..77c8148 100644 --- a/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp +++ b/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp @@ -32,13 +32,13 @@ void connectToMqtt() { void WiFiEvent(WiFiEvent_t event) { Serial.printf("[WiFi-event] event: %d\n", event); switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); connectToMqtt(); break; - case SYSTEM_EVENT_STA_DISCONNECTED: + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: Serial.println("WiFi lost connection"); break; default: @@ -118,7 +118,7 @@ void setup() { Serial.println(); Serial.println(); - WiFi.setAutoConnect(false); + WiFi.persistent(false); WiFi.setAutoReconnect(true); WiFi.onEvent(WiFiEvent); diff --git a/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino b/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino index c1bbbe5..1a5de37 100644 --- a/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino +++ b/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino @@ -31,13 +31,13 @@ void connectToMqtt() { void WiFiEvent(WiFiEvent_t event) { Serial.printf("[WiFi-event] event: %d\n", event); switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); connectToMqtt(); break; - case SYSTEM_EVENT_STA_DISCONNECTED: + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: Serial.println("WiFi lost connection"); break; default: @@ -117,7 +117,7 @@ void setup() { Serial.println(); Serial.println(); - WiFi.setAutoConnect(false); + WiFi.persistent(false); WiFi.setAutoReconnect(true); WiFi.onEvent(WiFiEvent); diff --git a/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino b/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino index 50fd5f6..109bcf0 100644 --- a/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino +++ b/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino @@ -31,13 +31,13 @@ void connectToMqtt() { void WiFiEvent(WiFiEvent_t event) { Serial.printf("[WiFi-event] event: %d\n", event); switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); connectToMqtt(); break; - case SYSTEM_EVENT_STA_DISCONNECTED: + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: Serial.println("WiFi lost connection"); break; default: @@ -117,7 +117,7 @@ void setup() { Serial.println(); Serial.println(); - WiFi.setAutoConnect(false); + WiFi.persistent(false); WiFi.setAutoReconnect(true); WiFi.onEvent(WiFiEvent); diff --git a/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino b/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino index ae6cebb..ce75a5a 100644 --- a/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino +++ b/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino @@ -39,13 +39,13 @@ void connectToMqtt() { void WiFiEvent(WiFiEvent_t event) { Serial.printf("[WiFi-event] event: %d\n", event); switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); connectToMqtt(); break; - case SYSTEM_EVENT_STA_DISCONNECTED: + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: Serial.println("WiFi lost connection"); break; default: @@ -128,7 +128,7 @@ void setup() { Serial.println(); Serial.println(); - WiFi.setAutoConnect(false); + WiFi.persistent(false); WiFi.setAutoReconnect(true); WiFi.onEvent(WiFiEvent); diff --git a/lib/espMqttClient/library.json b/lib/espMqttClient/library.json index ad44295..21c8429 100644 --- a/lib/espMqttClient/library.json +++ b/lib/espMqttClient/library.json @@ -14,24 +14,10 @@ "type": "git", "url": "https://github.com/bertmelis/espMqttClient.git" }, - "version": "1.6.0", + "version": "1.7.0", "frameworks": "arduino", "platforms": ["espressif8266", "espressif32"], "headers": ["espMqttClient.h", "espMqttClientAsync.h"], - "dependencies": [ - { - "owner": "esphome", - "name": "ESPAsyncTCP-esphome", - "version": ">=2.0.0", - "platforms": "espressif8266" - }, - { - "owner": "esphome", - "name": "AsyncTCP-esphome", - "version": ">=2.1.1", - "platforms": "espressif32" - } - ], "build": { "libLDFMode": "deep+" diff --git a/lib/espMqttClient/library.properties b/lib/espMqttClient/library.properties index 55d488a..3b906a9 100644 --- a/lib/espMqttClient/library.properties +++ b/lib/espMqttClient/library.properties @@ -1,5 +1,5 @@ name=espMqttClient -version=1.6.0 +version=1.7.0 author=Bert Melis maintainer=Bert Melis sentence=an MQTT client for the Arduino framework for ESP8266 / ESP32 diff --git a/lib/espMqttClient/platformio.ini b/lib/espMqttClient/platformio.ini index 77f8f5c..219ed3b 100644 --- a/lib/espMqttClient/platformio.ini +++ b/lib/espMqttClient/platformio.ini @@ -31,6 +31,7 @@ build_flags = -D EMC_RX_BUFFER_SIZE=100 -D EMC_TX_BUFFER_SIZE=10 -D EMC_MULTIPLE_CALLBACKS=1 + -D EMC_USE_MEMPOOL=1 ;extra_scripts = test-coverage.py build_type = debug test_testing_command = diff --git a/lib/espMqttClient/src/Config.h b/lib/espMqttClient/src/Config.h index 9c60911..935f7e1 100644 --- a/lib/espMqttClient/src/Config.h +++ b/lib/espMqttClient/src/Config.h @@ -60,3 +60,16 @@ the LICENSE file. #ifndef EMC_USE_WATCHDOG #define EMC_USE_WATCHDOG 0 #endif + +#ifndef EMC_USE_MEMPOOL +#define EMC_USE_MEMPOOL 0 +#endif + +#if EMC_USE_MEMPOOL + #ifndef EMC_NUM_POOL_ELEMENTS + #define EMC_NUM_POOL_ELEMENTS 32 + #endif + #ifndef EMC_SIZE_POOL_ELEMENTS + #define EMC_SIZE_POOL_ELEMENTS 128 + #endif +#endif diff --git a/lib/espMqttClient/src/MemoryPool/LICENSE b/lib/espMqttClient/src/MemoryPool/LICENSE new file mode 100644 index 0000000..526a0c7 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Bert Melis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/espMqttClient/src/MemoryPool/README.md b/lib/espMqttClient/src/MemoryPool/README.md new file mode 100644 index 0000000..7363e77 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/README.md @@ -0,0 +1,105 @@ +# Memory Pool + +EARLY VERSION. USE AT OWN RISK. + +### Description + +This is a simple memory pool that doesn't solve the fragmentation problem but contains it. Inside the pool you will still suffer memory fragmentation. The upside is that you're not restricted on memory size. As long as it fits in the pool, you can request any size! + +For applications where the (maximum) size to allocate is known, a simple fixed block size memory pool is available. There is no memory fragmentation happening in this case. The downside is wastage of memory if you need less then the specified blocksize. + +#### Features + +- pool memory is statically allocated +- pool size adjusts on architecture +- no size calculation required: input number of blocks and size of block +- header-only library +- Variable size pool: no restriction on allocated size +- Variable size pool: malloc and free are O(n); The number of allocated blocks affects lookup. +- Fixed size pool: malloc and free are O(1). + +[![Test with Platformio](https://github.com/bertmelis/MemoryPool/actions/workflows/test-platformio.yml/badge.svg)](https://github.com/bertmelis/MemoryPool/actions/workflows/test-platformio.yml) +[![cpplint](https://github.com/bertmelis/MemoryPool/actions/workflows/cpplint.yml/badge.svg)](https://github.com/bertmelis/MemoryPool/actions/workflows/cpplint.yml) + + +### Usage + +#### Variable size pool + +```cpp +#include + +Struct MyStruct { + unsigned int id; + std::size_t size; + unsigned char data[256]; +}; + +// pool will be able to hold 10 blocks the size of MyStruct +MemoryPool::Variable<10, sizeof(MyStruct)> pool; + +// you can allocate the specified blocksize +// allocation is done in number of 'unsigned char' +MyStruct* s = reinterpret_cast(pool.malloc(sizeof(MyStruct))); + +// you can allocate less than the specified blocksize +int* i = reinterpret_cast(pool.malloc(sizeof(int))); + +// you can allocate more than the specified blocksize +unsigned char* m = reinterpret_cast(pool.malloc(400)); + +pool.free(s); +pool.free(i); +pool.free(m); +``` + +#### Fixed size pool + +```cpp +#include + +Struct MyStruct { + unsigned int id; + std::size_t size; + unsigned char data[256]; +}; + +// pool will be able to hold 10 blocks the size of MyStruct +MemoryPool::Fixed<10, sizeof(MyStruct)> pool; + +// there is no size argument in the malloc function! +MyStruct* s = reinterpret_cast(pool.malloc()); + +// you can allocate less than the specified blocksize +int* i = reinterpret_cast(pool.malloc()); + +pool.free(s); +pool.free(i); +``` + +#### How it works + +##### Variable size pool + +Free blocks are organized as a linked list with their header (contains pointer to next and size). An allocated block also has this header with it's pointer set to `nullptr`. Therefore, each allocation wastes memory the size of the header (`sizeof(void*) + sizeof(std::size_t)`). On creation, the pool calculations the needed space to store the number of blocks wich each their header. + +However, memory allocation isn't restricted the the specified blocksize. So in reality, you can allocate more if you allocate larger chunks because less memory blocks means less headers. After all, memory needs to be contiguous. + +If you inspect the pool you'll see that a free pool only has one big block. + +Allocation is linear: the pool is iterated until a suitable spot is found. +Freeing is also linear as the pool is traversed to insert the chunk in the linked list of free blocks + +When freeing, free blocks which are adjacent are combined into one. + +##### Fixed size pool + +The fixed size pool is implemented as an array. Free blocks are saved as a linked list in this array. + +### Bugs and feature requests + +Please use Github's facilities to get in touch. + +### License + +This library is released under the MIT Licence. A copy is included in the repo. diff --git a/lib/espMqttClient/src/MemoryPool/keywords.txt b/lib/espMqttClient/src/MemoryPool/keywords.txt new file mode 100644 index 0000000..08db546 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/keywords.txt @@ -0,0 +1,16 @@ +# Datatypes (KEYWORD1) +Fixed KEYWORD1 +Variable KEYWORD1 + +# Methods and Functions (KEYWORD2) +malloc KEYWORD2 +free KEYWORD2 +freeMemory KEYWORD2 +maxBlockSize KEYWORD2 +print KEYWORD2 + +# Structures (KEYWORD3) +# structure KEYWORD3 + +# Constants (LITERAL1) +MemoryPool LITERAL1 diff --git a/lib/espMqttClient/src/MemoryPool/library.json b/lib/espMqttClient/src/MemoryPool/library.json new file mode 100644 index 0000000..be2b63d --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/library.json @@ -0,0 +1,21 @@ +{ + "name": "MemoryPool", + "keywords": "memory", + "description": "A simple memory pool for fixed and variable sizes", + "authors": + { + "name": "Bert Melis", + "url": "https://github.com/bertmelis" + }, + "license": "MIT", + "homepage": "https://github.com/bertmelis/MemoryPool", + "repository": + { + "type": "git", + "url": "https://github.com/bertmelis/MemoryPool.git" + }, + "version": "0.1.0", + "frameworks": "*", + "platforms": "*", + "headers": ["MemoryPool.h"] + } \ No newline at end of file diff --git a/lib/espMqttClient/src/MemoryPool/library.properties b/lib/espMqttClient/src/MemoryPool/library.properties new file mode 100644 index 0000000..4c4a443 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/library.properties @@ -0,0 +1,10 @@ +name=MemoryPool +version=0.1.0 +author=Bert Melis +maintainer=Bert Melis +sentence=A simple memory pool for fixed and variable sizes +paragraph= +category=Other +url=https://github.com/bertmelis/MemoryPool +architectures=* +includes=MemoryPool.h \ No newline at end of file diff --git a/lib/espMqttClient/src/MemoryPool/src/Fixed.h b/lib/espMqttClient/src/MemoryPool/src/Fixed.h new file mode 100644 index 0000000..d976b8f --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/src/Fixed.h @@ -0,0 +1,119 @@ +/* +Copyright (c) 2024 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#include // std::size_t +#include // assert +#if _GLIBCXX_HAS_GTHREADS +#include // NOLINT [build/c++11] std::mutex, std::lock_guard +#else +#warning "The memory pool is not thread safe" +#endif + +#ifdef MEMPOL_DEBUG +#include +#endif + +namespace MemoryPool { + +template +class Fixed { + public: + Fixed() // cppcheck-suppress uninitMemberVar + : _buffer{0} + , _head(_buffer) { + unsigned char* b = _head; + std::size_t adjustedBlocksize = sizeof(std::size_t) > blocksize ? sizeof(std::size_t) : blocksize; + for (std::size_t i = 0; i < nrBlocks - 1; ++i) { + *reinterpret_cast(b) = b + adjustedBlocksize; + b += adjustedBlocksize; + } + *reinterpret_cast(b) = nullptr; + } + + // no copy nor move + Fixed (const Fixed&) = delete; + Fixed& operator= (const Fixed&) = delete; + + void* malloc() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + if (_head) { + void* retVal = _head; + _head = *reinterpret_cast(_head); + return retVal; + } + return nullptr; + } + + void free(void* ptr) { + if (!ptr) return; + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + *reinterpret_cast(ptr) = _head; + _head = reinterpret_cast(ptr); + } + + std::size_t freeMemory() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + unsigned char* i = _head; + std::size_t retVal = 0; + while (i) { + retVal += blocksize; + i = reinterpret_cast(i)[0]; + } + return retVal; + } + + #ifdef MEMPOL_DEBUG + void print() { + std::size_t adjustedBlocksize = sizeof(std::size_t) > blocksize ? sizeof(std::size_t) : blocksize; + std::cout << "+--------------------" << std::endl; + std::cout << "|start:" << reinterpret_cast(_buffer) << std::endl; + std::cout << "|blocks:" << nrBlocks << std::endl; + std::cout << "|blocksize:" << adjustedBlocksize << std::endl; + std::cout << "|head: " << reinterpret_cast(_head) << std::endl; + unsigned char* currentBlock = _buffer; + + for (std::size_t i = 0; i < nrBlocks; ++i) { + std::cout << "|" << i + 1 << ": " << reinterpret_cast(currentBlock) << std::endl; + if (_isFree(currentBlock)) { + std::cout << "| free" << std::endl; + std::cout << "| next: " << reinterpret_cast(*reinterpret_cast(currentBlock)) << std::endl; + } else { + std::cout << "| allocated" << std::endl; + } + currentBlock += adjustedBlocksize; + } + std::cout << "+--------------------" << std::endl; + } + + bool _isFree(const unsigned char* ptr) { + unsigned char* b = _head; + while (b) { + if (b == ptr) return true; + b = *reinterpret_cast(b); + } + return false; + } + #endif + + private: + unsigned char _buffer[nrBlocks * (sizeof(std::size_t) > blocksize ? sizeof(std::size_t) : blocksize)]; + unsigned char* _head; + #if _GLIBCXX_HAS_GTHREADS + std::mutex _mutex; + #endif +}; + +} // end namespace MemoryPool diff --git a/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h b/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h new file mode 100644 index 0000000..af036fc --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h @@ -0,0 +1,12 @@ +/* +Copyright (c) 2024 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#include "Variable.h" +#include "Fixed.h" diff --git a/lib/espMqttClient/src/MemoryPool/src/Variable.h b/lib/espMqttClient/src/MemoryPool/src/Variable.h new file mode 100644 index 0000000..11483cc --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/src/Variable.h @@ -0,0 +1,242 @@ +/* +Copyright (c) 2024 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#include // std::size_t +#include // assert +#if _GLIBCXX_HAS_GTHREADS +#include // NOLINT [build/c++11] std::mutex, std::lock_guard +#else +#warning "The memory pool is not thread safe" +#endif + +#ifdef MEMPOL_DEBUG +#include +#endif + +namespace MemoryPool { + +template +class Variable { + public: + Variable() + : _buffer{0} + , _head(nullptr) + #ifdef MEMPOL_DEBUG + , _bufferSize(0) + #endif + { + std::size_t _normBlocksize = blocksize / sizeof(BlockHeader) + ((blocksize % sizeof(BlockHeader)) ? 1 : 0); + size_t nrBlocksToAlloc = nrBlocks * (_normBlocksize + 1); + BlockHeader* h = reinterpret_cast(_buffer); + h->next = nullptr; + h->size = nrBlocksToAlloc; + _head = h; + + #ifdef MEMPOL_DEBUG + _bufferSize = nrBlocksToAlloc; + #endif + } + + // no copy nor move + Variable (const Variable&) = delete; + Variable& operator= (const Variable&) = delete; + + void* malloc(size_t size) { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + if (size == 0) return nullptr; + + size = (size / sizeof(BlockHeader) + (size % sizeof(BlockHeader) != 0)) + 1; // count by BlockHeader size, add 1 for header + + #ifdef MEMPOL_DEBUG + std::cout << "malloc (raw) " << size << std::endl; + std::cout << "malloc (adj) " << size << " - "; + #endif + + BlockHeader* currentBlock = _head; + BlockHeader* previousBlock = nullptr; + void* retVal = nullptr; + + // iterate through linked free blocks + while (currentBlock) { + // consume whole block is size equals required size + if (currentBlock->size == size) { + if (previousBlock) previousBlock->next = currentBlock->next; + break; + + // split block if size is larger and add second part to list of free blocks + } else if (currentBlock->size > size) { + BlockHeader* newBlock = currentBlock + size; + if (previousBlock) previousBlock->next = newBlock; + newBlock->next = currentBlock->next; + newBlock->size = currentBlock->size - size; + currentBlock->next = newBlock; + break; + } + previousBlock = currentBlock; + currentBlock = currentBlock->next; + } + + if (currentBlock) { + if (currentBlock == _head) { + _head = currentBlock->next; + } + currentBlock->size = size; + currentBlock->next = nullptr; // used when freeing memory + retVal = currentBlock + 1; + #ifdef MEMPOL_DEBUG + std::cout << "ok" << std::endl; + #endif + } else { + #ifdef MEMPOL_DEBUG + std::cout << "nok" << std::endl; + #endif + (void)0; + } + + return retVal; + } + + void free(void* ptr) { + if (!ptr) return; + // check if ptr points to region in _buffer + + #ifdef MEMPOL_DEBUG + std::cout << "free " << static_cast(reinterpret_cast(ptr) - 1) << std::endl; + #endif + + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + + BlockHeader* toFree = reinterpret_cast(ptr) - 1; + BlockHeader* previous = reinterpret_cast(_buffer); + BlockHeader* next = _head; + + // toFree is the only free block + if (!next) { + _head = toFree; + return; + } + + while (previous) { + if (!next || toFree < next) { + // 1. add block to linked list of free blocks + if (toFree < _head) { + toFree->next = _head; + _head = toFree; + } else { + previous->next = toFree; + toFree->next = next; + } + + // 2. merge with previous if adjacent + if (toFree > _head && toFree == previous + previous->size) { + previous->size += toFree->size; + previous->next = toFree->next; + toFree = previous; // used in next check + } + + // 3. merge with next if adjacent + if (toFree + toFree->size == next) { + toFree->size += next->size; + toFree->next = next->next; + } + + // 4. done + return; + } + previous = next; + next = next->next; + } + } + + std::size_t freeMemory() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + size_t retVal = 0; + BlockHeader* currentBlock = reinterpret_cast(_head); + + while (currentBlock) { + retVal += currentBlock->size - 1; + currentBlock = currentBlock->next; + } + + return retVal * sizeof(BlockHeader); + } + + std::size_t maxBlockSize() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + size_t retVal = 0; + BlockHeader* currentBlock = reinterpret_cast(_head); + + while (currentBlock) { + retVal = (currentBlock->size - 1 > retVal) ? currentBlock->size - 1 : retVal; + currentBlock = currentBlock->next; + } + + return retVal * sizeof(BlockHeader); + } + + #ifdef MEMPOL_DEBUG + void print() { + std::cout << "+--------------------" << std::endl; + std::cout << "|start:" << static_cast(_buffer) << std::endl; + std::cout << "|size:" << _bufferSize << std::endl; + std::cout << "|headersize:" << sizeof(BlockHeader) << std::endl; + std::cout << "|head: " << static_cast(_head) << std::endl; + BlockHeader* nextFreeBlock = _head; + BlockHeader* currentBlock = reinterpret_cast(_buffer); + size_t blockNumber = 1; + while (currentBlock < reinterpret_cast(_buffer) + _bufferSize) { + std::cout << "|" << blockNumber << ": " << static_cast(currentBlock) << std::endl; + std::cout << "| " << static_cast(currentBlock->next) << std::endl; + std::cout << "| " << currentBlock->size << std::endl; + if (currentBlock == nextFreeBlock) { + std::cout << "| free" << std::endl; + nextFreeBlock = nextFreeBlock->next; + } else { + std::cout << "| allocated" << std::endl; + } + ++blockNumber; + currentBlock += currentBlock->size; + } + std::cout << "+--------------------" << std::endl; + } + #endif + + private: + struct BlockHeader { + BlockHeader* next; + std::size_t size; + }; + /* + pool size is aligned to sizeof(BlockHeader). + requested blocksize is therefore multiple of blockheader (rounded up) + total size = nr requested blocks * multiplier * blockheadersize + + see constructor for calculation + */ + unsigned char _buffer[(nrBlocks * ((blocksize / sizeof(BlockHeader) + ((blocksize % sizeof(BlockHeader)) ? 1 : 0)) + 1)) * sizeof(BlockHeader)]; + BlockHeader* _head; + #if _GLIBCXX_HAS_GTHREADS + std::mutex _mutex; + #endif + + #ifdef MEMPOL_DEBUG + std::size_t _bufferSize; + #endif +}; + +} // end namespace MemoryPool diff --git a/lib/espMqttClient/src/MqttClient.cpp b/lib/espMqttClient/src/MqttClient.cpp index fdc2cb2..dc21f74 100644 --- a/lib/espMqttClient/src/MqttClient.cpp +++ b/lib/espMqttClient/src/MqttClient.cpp @@ -118,9 +118,10 @@ bool MqttClient::connect() { } #endif } else { - EMC_SEMAPHORE_GIVE(); emc_log_e("Could not create CONNECT packet"); + EMC_SEMAPHORE_GIVE(); _onError(0, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); } EMC_SEMAPHORE_GIVE(); } @@ -151,7 +152,9 @@ uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, const uint16_t packetId = (qos > 0) ? _getNextPacketId() : 1; if (!_addPacket(packetId, topic, payload, length, qos, retain)) { emc_log_e("Could not create PUBLISH packet"); + EMC_SEMAPHORE_GIVE(); _onError(packetId, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); packetId = 0; } EMC_SEMAPHORE_GIVE(); @@ -175,7 +178,9 @@ uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, espMqt uint16_t packetId = (qos > 0) ? _getNextPacketId() : 1; if (!_addPacket(packetId, topic, callback, length, qos, retain)) { emc_log_e("Could not create PUBLISH packet"); + EMC_SEMAPHORE_GIVE(); _onError(packetId, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); packetId = 0; } EMC_SEMAPHORE_GIVE(); @@ -183,7 +188,9 @@ uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, espMqt } void MqttClient::clearQueue(bool deleteSessionData) { + EMC_SEMAPHORE_TAKE(); _clearQueue(deleteSessionData ? 2 : 0); + EMC_SEMAPHORE_GIVE(); } const char* MqttClient::getClientId() const { @@ -222,14 +229,19 @@ void MqttClient::loop() { _parser.reset(); _lastClientActivity = _lastServerActivity = millis(); _setState(State::connectingMqtt); + } else if (_transport->disconnected()) { // sync: implemented as "not connected"; async: depending on state of pcb in underlying lib + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; } break; case State::connectingMqtt: #if EMC_WAIT_FOR_CONNACK if (_transport->connected()) { + EMC_SEMAPHORE_TAKE(); _sendPacket(); _checkIncoming(); _checkPing(); + EMC_SEMAPHORE_GIVE(); } else { _setState(State::disconnectingTcp1); _disconnectReason = DisconnectReason::TCP_DISCONNECTED; @@ -246,10 +258,12 @@ void MqttClient::loop() { case State::disconnectingMqtt2: if (_transport->connected()) { // CONNECT packet is first in the queue + EMC_SEMAPHORE_TAKE(); _checkOutbox(); _checkIncoming(); _checkPing(); _checkTimeout(); + EMC_SEMAPHORE_GIVE(); } else { _setState(State::disconnectingTcp1); _disconnectReason = DisconnectReason::TCP_DISCONNECTED; @@ -262,15 +276,16 @@ void MqttClient::loop() { EMC_SEMAPHORE_GIVE(); emc_log_e("Could not create DISCONNECT packet"); _onError(0, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); } else { _setState(State::disconnectingMqtt2); } } - EMC_SEMAPHORE_GIVE(); _checkOutbox(); _checkIncoming(); _checkPing(); _checkTimeout(); + EMC_SEMAPHORE_GIVE(); break; case State::disconnectingTcp1: _transport->stop(); @@ -278,10 +293,14 @@ void MqttClient::loop() { break; // keep break to accomodate async clients case State::disconnectingTcp2: if (_transport->disconnected()) { + EMC_SEMAPHORE_TAKE(); _clearQueue(0); + EMC_SEMAPHORE_GIVE(); _bytesSent = 0; _setState(State::disconnected); - if (_onDisconnectCallback) _onDisconnectCallback(_disconnectReason); + if (_onDisconnectCallback) { + _onDisconnectCallback(_disconnectReason); + } } break; // all cases covered, no default case @@ -332,14 +351,12 @@ void MqttClient::_checkOutbox() { } int MqttClient::_sendPacket() { - EMC_SEMAPHORE_TAKE(); OutgoingPacket* packet = _outbox.getCurrent(); size_t written = 0; if (packet) { size_t wantToWrite = packet->packet.available(_bytesSent); if (wantToWrite == 0) { - EMC_SEMAPHORE_GIVE(); return 0; } written = _transport->write(packet->packet.data(_bytesSent), wantToWrite); @@ -348,12 +365,10 @@ int MqttClient::_sendPacket() { _bytesSent += written; emc_log_i("tx %zu/%zu (%02x)", _bytesSent, packet->packet.size(), packet->packet.packetType()); } - EMC_SEMAPHORE_GIVE(); return written; } bool MqttClient::_advanceOutbox() { - EMC_SEMAPHORE_TAKE(); OutgoingPacket* packet = _outbox.getCurrent(); if (packet && _bytesSent == packet->packet.size()) { if ((packet->packet.packetType()) == PacketType.DISCONNECT) { @@ -370,7 +385,6 @@ bool MqttClient::_advanceOutbox() { packet = _outbox.getCurrent(); _bytesSent = 0; } - EMC_SEMAPHORE_GIVE(); return packet; } @@ -390,7 +404,7 @@ void MqttClient::_checkIncoming() { _setState(State::disconnectingTcp1); return; } - switch (packetType & 0xF0) { + switch (packetType) { case PacketType.CONNACK: _onConnack(); if (_state != State::connected) { @@ -455,19 +469,15 @@ void MqttClient::_checkPing() { if (!_pingSent && ((currentMillis - _lastClientActivity > _keepAlive) || (currentMillis - _lastServerActivity > _keepAlive))) { - EMC_SEMAPHORE_TAKE(); if (!_addPacket(PacketType.PINGREQ)) { - EMC_SEMAPHORE_GIVE(); emc_log_e("Could not create PING packet"); return; } - EMC_SEMAPHORE_GIVE(); _pingSent = true; } } void MqttClient::_checkTimeout() { - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); // check that we're not busy sending // don't check when first item hasn't been sent yet @@ -477,7 +487,6 @@ void MqttClient::_checkTimeout() { _outbox.resetCurrent(); } } - EMC_SEMAPHORE_GIVE(); } void MqttClient::_onConnack() { @@ -489,7 +498,9 @@ void MqttClient::_onConnack() { _clearQueue(1); } if (_onConnectCallback) { + EMC_SEMAPHORE_GIVE(); _onConnectCallback(_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent); + EMC_SEMAPHORE_TAKE(); } } else { _setState(State::disconnectingTcp1); @@ -507,14 +518,11 @@ void MqttClient::_onPublish() { bool callback = true; if (qos == 1) { if (p.payload.index + p.payload.length == p.payload.total) { - EMC_SEMAPHORE_TAKE(); if (!_addPacket(PacketType.PUBACK, packetId)) { emc_log_e("Could not create PUBACK packet"); } - EMC_SEMAPHORE_GIVE(); } } else if (qos == 2) { - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); while (it) { if ((it.get()->packet.packetType()) == PacketType.PUBREC && it.get()->packet.packetId() == packetId) { @@ -529,20 +537,22 @@ void MqttClient::_onPublish() { emc_log_e("Could not create PUBREC packet"); } } - EMC_SEMAPHORE_GIVE(); } - if (callback && _onMessageCallback) _onMessageCallback({qos, dup, retain, packetId}, - p.variableHeader.topic, - p.payload.data, - p.payload.length, - p.payload.index, - p.payload.total); + if (callback && _onMessageCallback) { + EMC_SEMAPHORE_GIVE(); + _onMessageCallback({qos, dup, retain, packetId}, + p.variableHeader.topic, + p.payload.data, + p.payload.length, + p.payload.index, + p.payload.total); + EMC_SEMAPHORE_TAKE(); + } } void MqttClient::_onPuback() { bool callback = false; uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); while (it) { // PUBACKs come in the order PUBs are sent. So we only check the first PUB packet in outbox @@ -558,9 +568,12 @@ void MqttClient::_onPuback() { } ++it; } - EMC_SEMAPHORE_GIVE(); if (callback) { - if (_onPublishCallback) _onPublishCallback(idToMatch); + if (_onPublishCallback) { + EMC_SEMAPHORE_GIVE(); + _onPublishCallback(idToMatch); + EMC_SEMAPHORE_TAKE(); + } } else { emc_log_w("No matching PUBLISH packet found"); } @@ -569,7 +582,6 @@ void MqttClient::_onPuback() { void MqttClient::_onPubrec() { bool success = false; uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); while (it) { // PUBRECs come in the order PUBs are sent. So we only check the first PUB packet in outbox @@ -591,13 +603,11 @@ void MqttClient::_onPubrec() { if (!success) { emc_log_w("No matching PUBLISH packet found"); } - EMC_SEMAPHORE_GIVE(); } void MqttClient::_onPubrel() { bool success = false; uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); while (it) { // PUBRELs come in the order PUBRECs are sent. So we only check the first PUBREC packet in outbox @@ -619,12 +629,10 @@ void MqttClient::_onPubrel() { if (!success) { emc_log_w("No matching PUBREC packet found"); } - EMC_SEMAPHORE_GIVE(); } void MqttClient::_onPubcomp() { bool callback = false; - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; while (it) { @@ -641,9 +649,12 @@ void MqttClient::_onPubcomp() { } ++it; } - EMC_SEMAPHORE_GIVE(); if (callback) { - if (_onPublishCallback) _onPublishCallback(idToMatch); + if (_onPublishCallback) { + EMC_SEMAPHORE_GIVE(); + _onPublishCallback(idToMatch); + EMC_SEMAPHORE_TAKE(); + } } else { emc_log_w("No matching PUBREL packet found"); } @@ -652,7 +663,6 @@ void MqttClient::_onPubcomp() { void MqttClient::_onSuback() { bool callback = false; uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); while (it) { if (((it.get()->packet.packetType()) == PacketType.SUBSCRIBE) && it.get()->packet.packetId() == idToMatch) { @@ -662,9 +672,12 @@ void MqttClient::_onSuback() { } ++it; } - EMC_SEMAPHORE_GIVE(); if (callback) { - if (_onSubscribeCallback) _onSubscribeCallback(idToMatch, reinterpret_cast(_parser.getPacket().payload.data), _parser.getPacket().payload.total); + if (_onSubscribeCallback) { + EMC_SEMAPHORE_GIVE(); + _onSubscribeCallback(idToMatch, reinterpret_cast(_parser.getPacket().payload.data), _parser.getPacket().payload.total); + EMC_SEMAPHORE_TAKE(); + } } else { emc_log_w("received SUBACK without SUB"); } @@ -672,7 +685,6 @@ void MqttClient::_onSuback() { void MqttClient::_onUnsuback() { bool callback = false; - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; while (it) { @@ -683,9 +695,12 @@ void MqttClient::_onUnsuback() { } ++it; } - EMC_SEMAPHORE_GIVE(); if (callback) { - if (_onUnsubscribeCallback) _onUnsubscribeCallback(idToMatch); + if (_onUnsubscribeCallback) { + EMC_SEMAPHORE_GIVE(); + _onUnsubscribeCallback(idToMatch); + EMC_SEMAPHORE_TAKE(); + } } else { emc_log_w("received UNSUBACK without UNSUB"); } @@ -693,7 +708,6 @@ void MqttClient::_onUnsuback() { void MqttClient::_clearQueue(int clearData) { emc_log_i("clearing queue (clear session: %d)", clearData); - EMC_SEMAPHORE_TAKE(); espMqttClientInternals::Outbox::Iterator it = _outbox.front(); if (clearData == 0) { // keep PUB (qos > 0, aka packetID != 0), PUBREC and PUBREL @@ -723,7 +737,6 @@ void MqttClient::_clearQueue(int clearData) { _outbox.remove(it); } } - EMC_SEMAPHORE_GIVE(); } void MqttClient::_onError(uint16_t packetId, espMqttClientTypes::Error error) { diff --git a/lib/espMqttClient/src/MqttClient.h b/lib/espMqttClient/src/MqttClient.h index 4997942..eaf9d2d 100644 --- a/lib/espMqttClient/src/MqttClient.h +++ b/lib/espMqttClient/src/MqttClient.h @@ -32,11 +32,12 @@ class MqttClient { bool disconnect(bool force = false); template uint16_t subscribe(const char* topic, uint8_t qos, Args&&... args) { - uint16_t packetId = _getNextPacketId(); + uint16_t packetId = 0; if (_state != State::connected) { - packetId = 0; + return packetId; } else { EMC_SEMAPHORE_TAKE(); + packetId = _getNextPacketId(); if (!_addPacket(packetId, topic, qos, std::forward(args) ...)) { emc_log_e("Could not create SUBSCRIBE packet"); packetId = 0; @@ -47,11 +48,12 @@ class MqttClient { } template uint16_t unsubscribe(const char* topic, Args&&... args) { - uint16_t packetId = _getNextPacketId(); + uint16_t packetId = 0; if (_state != State::connected) { - packetId = 0; + return packetId; } else { EMC_SEMAPHORE_TAKE(); + packetId = _getNextPacketId(); if (!_addPacket(packetId, topic, std::forward(args) ...)) { emc_log_e("Could not create UNSUBSCRIBE packet"); packetId = 0; diff --git a/lib/espMqttClient/src/Outbox.h b/lib/espMqttClient/src/Outbox.h index 486b6ac..4f9971c 100644 --- a/lib/espMqttClient/src/Outbox.h +++ b/lib/espMqttClient/src/Outbox.h @@ -9,7 +9,12 @@ the LICENSE file. #pragma once -#include // new (std::nothrow) +#if EMC_USE_MEMPOOL + #include "MemoryPool/src/MemoryPool.h" + #include "Config.h" +#else + #include // new (std::nothrow) +#endif #include // std::forward namespace espMqttClientInternals { @@ -28,11 +33,20 @@ class Outbox { : _first(nullptr) , _last(nullptr) , _current(nullptr) - , _prev(nullptr) {} + , _prev(nullptr) + #if EMC_USE_MEMPOOL + , _memPool() + #endif + {} ~Outbox() { while (_first) { Node* n = _first->next; + #if EMC_USE_MEMPOOL + _first->~Node(); + _memPool.free(_first); + #else delete _first; + #endif _first = n; } } @@ -79,7 +93,15 @@ class Outbox { template Iterator emplace(Args&&... args) { Iterator it; - Node* node = new (std::nothrow) Node(std::forward(args) ...); + #if EMC_USE_MEMPOOL + void* buf = _memPool.malloc(); + Node* node = nullptr; + if (buf) { + node = new(buf) Node(std::forward(args) ...); + } + #else + Node* node = new(std::nothrow) Node(std::forward(args) ...); + #endif if (node != nullptr) { if (!_first) { // queue is empty @@ -103,7 +125,15 @@ class Outbox { template Iterator emplaceFront(Args&&... args) { Iterator it; - Node* node = new (std::nothrow) Node(std::forward(args) ...); + #if EMC_USE_MEMPOOL + void* buf = _memPool.malloc(); + Node* node = nullptr; + if (buf) { + node = new(buf) Node(std::forward(args) ...); + } + #else + Node* node = new(std::nothrow) Node(std::forward(args) ...); + #endif if (node != nullptr) { if (!_first) { // queue is empty @@ -178,6 +208,9 @@ class Outbox { Node* _last; Node* _current; Node* _prev; // element just before _current + #if EMC_USE_MEMPOOL + MemoryPool::Fixed _memPool; + #endif void _remove(Node* prev, Node* node) { if (!node) return; @@ -210,7 +243,12 @@ class Outbox { } // finally, delete the node - delete node; + #if EMC_USE_MEMPOOL + node->~Node(); + _memPool.free(node); + #else + delete node; + #endif } }; diff --git a/lib/espMqttClient/src/Packets/Packet.cpp b/lib/espMqttClient/src/Packets/Packet.cpp index 2f84b50..14d241b 100644 --- a/lib/espMqttClient/src/Packets/Packet.cpp +++ b/lib/espMqttClient/src/Packets/Packet.cpp @@ -10,8 +10,16 @@ the LICENSE file. namespace espMqttClientInternals { +#if EMC_USE_MEMPOOL +MemoryPool::Variable Packet::_memPool; +#endif + Packet::~Packet() { + #if EMC_USE_MEMPOOL + _memPool.free(_data); + #else free(_data); + #endif } size_t Packet::available(size_t index) { @@ -178,7 +186,7 @@ Packet::Packet(espMqttClientTypes::Error& error, _packetId = 0; } - if (!_allocate(remainingLength)) { + if (!_allocate(remainingLength, true)) { error = espMqttClientTypes::Error::OUT_OF_MEMORY; return; } @@ -215,7 +223,7 @@ Packet::Packet(espMqttClientTypes::Error& error, _packetId = 0; } - if (!_allocate(remainingLength - payloadLength + std::min(payloadLength, static_cast(EMC_RX_BUFFER_SIZE)))) { + if (!_allocate(remainingLength - payloadLength + std::min(payloadLength, static_cast(EMC_RX_BUFFER_SIZE)), true)) { error = espMqttClientTypes::Error::OUT_OF_MEMORY; return; } @@ -251,7 +259,7 @@ Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type, uint16_t p , _payloadStartIndex(0) , _payloadEndIndex(0) , _getPayload(nullptr) { - if (!_allocate(2)) { + if (!_allocate(2, true)) { error = espMqttClientTypes::Error::OUT_OF_MEMORY; return; } @@ -290,7 +298,7 @@ Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type) , _payloadStartIndex(0) , _payloadEndIndex(0) , _getPayload(nullptr) { - if (!_allocate(0)) { + if (!_allocate(0, true)) { error = espMqttClientTypes::Error::OUT_OF_MEMORY; return; } @@ -301,12 +309,20 @@ Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type) bool Packet::_allocate(size_t remainingLength, bool check) { + #if EMC_USE_MEMPOOL + (void) check; + #else if (check && EMC_GET_FREE_MEMORY() < EMC_MIN_FREE_MEMORY) { emc_log_w("Packet buffer not allocated: low memory"); return false; } + #endif _size = 1 + remainingLengthLength(remainingLength) + remainingLength; + #if EMC_USE_MEMPOOL + _data = reinterpret_cast(_memPool.malloc(_size)); + #else _data = reinterpret_cast(malloc(_size)); + #endif if (!_data) { _size = 0; emc_log_w("Alloc failed (l:%zu)", _size); @@ -357,7 +373,7 @@ void Packet::_createSubscribe(espMqttClientTypes::Error& error, size_t remainingLength = 2 + payload; // packetId + payload // allocate memory - if (!_allocate(remainingLength)) { + if (!_allocate(remainingLength, true)) { error = espMqttClientTypes::Error::OUT_OF_MEMORY; return; } @@ -387,7 +403,7 @@ void Packet::_createUnsubscribe(espMqttClientTypes::Error& error, size_t remainingLength = 2 + payload; // packetId + payload // allocate memory - if (!_allocate(remainingLength)) { + if (!_allocate(remainingLength, true)) { error = espMqttClientTypes::Error::OUT_OF_MEMORY; return; } diff --git a/lib/espMqttClient/src/Packets/Packet.h b/lib/espMqttClient/src/Packets/Packet.h index 00019fb..5d0b67b 100644 --- a/lib/espMqttClient/src/Packets/Packet.h +++ b/lib/espMqttClient/src/Packets/Packet.h @@ -19,6 +19,10 @@ the LICENSE file. #include "RemainingLength.h" #include "StringUtil.h" +#if EMC_USE_MEMPOOL + #include "MemoryPool/src/MemoryPool.h" +#endif + namespace espMqttClientInternals { class Packet { @@ -133,7 +137,7 @@ class Packet { private: // pass remainingLength = total size - header - remainingLengthLength! - bool _allocate(size_t remainingLength, bool check = true); + bool _allocate(size_t remainingLength, bool check); // fills header and returns index of next available byte in buffer size_t _fillPublishHeader(uint16_t packetId, @@ -150,6 +154,10 @@ class Packet { size_t _chunkedAvailable(size_t index); const uint8_t* _chunkedData(size_t index) const; + + #if EMC_USE_MEMPOOL + static MemoryPool::Variable _memPool; + #endif }; } // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/test/test_outbox/test_outbox.cpp b/lib/espMqttClient/test/test_outbox/test_outbox.cpp index 0d6c337..0a6a3ef 100644 --- a/lib/espMqttClient/test/test_outbox/test_outbox.cpp +++ b/lib/espMqttClient/test/test_outbox/test_outbox.cpp @@ -17,25 +17,25 @@ void test_outbox_create() { void test_outbox_emplace() { Outbox outbox; - outbox.emplace(1); - // 1, current points to 1 + outbox.emplace(523); + // 523, current points to 523 TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(1, *(outbox.getCurrent())); + TEST_ASSERT_EQUAL_UINT32(523, *(outbox.getCurrent())); TEST_ASSERT_FALSE(outbox.empty()); outbox.next(); - // 1, current points to nullptr + // 523, current points to nullptr TEST_ASSERT_NULL(outbox.getCurrent()); - outbox.emplace(2); - // 1 2, current points to 2 + outbox.emplace(286); + // 523 286, current points to 286 TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(2, *(outbox.getCurrent())); + TEST_ASSERT_EQUAL_UINT32(286, *(outbox.getCurrent())); - outbox.emplace(3); - // 1 2 3, current points to 2 + outbox.emplace(364); + // 523 286 364, current points to 286 TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(2, *(outbox.getCurrent())); + TEST_ASSERT_EQUAL_UINT32(286, *(outbox.getCurrent())); } void test_outbox_emplaceFront() { diff --git a/lib/gpio2go/src/Gpio2Go.cpp b/lib/gpio2go/src/Gpio2Go.cpp index e3e4965..1e8d477 100644 --- a/lib/gpio2go/src/Gpio2Go.cpp +++ b/lib/gpio2go/src/Gpio2Go.cpp @@ -1,5 +1,5 @@ #include "Gpio2Go.h" - +#include void Gpio2Go::configurePin(int pin, PinMode pin_Mode, InterruptMode interrupt_Mode, uint16_t timeoutAfterTriggerMS) { diff --git a/lib/nuki_ble b/lib/nuki_ble index 0ebea6a..f5adac5 160000 --- a/lib/nuki_ble +++ b/lib/nuki_ble @@ -1 +1 @@ -Subproject commit 0ebea6a99f0382fbb78349633b3e9116770a9b85 +Subproject commit f5adac596a635ec26f9e198a5daf9b2a5a17d9c1 diff --git a/partitions.csv b/partitions.csv index 0181072..6f27eb7 100644 --- a/partitions.csv +++ b/partitions.csv @@ -1 +1 @@ -# Espressif ESP32 Partition Table # Name, Type, SubType, Offset, Size, Flags nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x1E0000, app1, app, ota_1, 0x1F0000, 0x1E0000 #spiffs, data, spiffs, 0x3D0000, 0x30000 spiffs, data, spiffs, 0x3D0000, 0x20000, coredump, data, coredump,0x3F0000, 0x10000, \ No newline at end of file +# Espressif ESP32 Partition Table # Name, Type, SubType, Offset, Size, Flags nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x270000, app1, app, ota_1, 0x280000, 0x150000, spiffs, data, spiffs, 0x3D0000, 0x20000, coredump, data, coredump,0x3F0000, 0x10000, \ No newline at end of file diff --git a/pio_package.py b/pio_package.py index 68b4ae1..f142e26 100644 --- a/pio_package.py +++ b/pio_package.py @@ -21,12 +21,15 @@ def create_target_dir(env): def copy_files(source, target, env): file = Path(target[0].get_abspath()) target_dir = create_target_dir(env) + project_dir = env.get('PROJECT_DIR') board = get_board_name(env) if "partitions.bin" in file.name: shutil.copy(file, f"{target_dir}/nuki_hub.{file.name}") elif "firmware" in file.stem: shutil.copy(file, f"{target_dir}/nuki_hub_{board}{file.suffix}") + if env.GetProjectOption("custom_build") == 'release': + shutil.copy(f"{project_dir}/updater/release/{board}/updater.bin", f"{target_dir}/nuki_hub_updater_{board}{file.suffix}") else: shutil.copy(file, f"{target_dir}/{file.name}") @@ -51,28 +54,33 @@ def merge_bin(source, target, env): for position, bin_file in env.get('FLASH_EXTRA_IMAGES'): if "boot_app0.bin" in bin_file: - bin_file = "bin/boot_app0.bin" + bin_file = "resources/boot_app0.bin" flash_args.append(position) flash_args.append(bin_file) + flash_args.append("0x2B0000") + flash_args.append(f"{target_dir}/nuki_hub_updater_{board}.bin") + cmd = f"esptool.py --chip {chip} merge_bin -o {target_file} --flash_mode dio --flash_freq keep --flash_size keep " + " ".join(flash_args) env.Execute(cmd) def package_last_files(source, target, env): - files = ["bin/boot_app0.bin", "how-to-flash.txt"] + files = ["resources/boot_app0.bin", "resources/how-to-flash.txt"] target_dir = create_target_dir(env) for file in files: file = Path(file) shutil.copy(file, f"{target_dir}/{file.name}") - -if env.GetProjectOption("custom_build") == 'release': - env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", merge_bin) - + env.AddPostAction("$BUILD_DIR/firmware.bin", copy_files) +if env.GetProjectOption("custom_build") == 'release': + env.AddPostAction("$PROJECT_DIR/updater/release/" + get_board_name(env) + "/updater.bin", copy_files) env.AddPostAction("$BUILD_DIR/firmware.bin", package_last_files) env.AddPostAction("$BUILD_DIR/partitions.bin", copy_files) env.AddPostAction("$BUILD_DIR/bootloader.bin", copy_files) if env.GetProjectOption("custom_build") == 'debug': env.AddPostAction("$BUILD_DIR/firmware.elf", copy_files) + +if env.GetProjectOption("custom_build") == 'release': + env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", merge_bin) \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index aadaca2..a9dbd4b 100644 --- a/platformio.ini +++ b/platformio.ini @@ -13,11 +13,17 @@ default_envs = esp32dev boards_dir = boards [env] -platform = espressif32 -framework = arduino +platform = https://github.com/tasmota/platform-espressif32/releases/download/2024.06.11/platform-espressif32.zip +platform_packages = +framework = arduino, espidf build_type = release custom_build = release board_build.partitions = partitions.csv +build_unflags = + -DCONFIG_BT_NIMBLE_LOG_LEVEL + -DCONFIG_BTDM_BLE_SCAN_DUPL + -Werror=all + -Wall build_flags = -fexceptions -DTLS_CA_MAX_SIZE=2200 @@ -26,11 +32,28 @@ build_flags = -DESP_PLATFORM -DESP32 -DARDUINO_ARCH_ESP32 + -DNUKI_NO_WDT_RESET + -DNUKI_MUTEX_RECURSIVE + -DCONFIG_BTDM_BLE_SCAN_DUPL=y + -DCONFIG_ASYNC_TCP_MAX_ACK_TIME=3000 + -DCONFIG_ASYNC_TCP_PRIORITY=10 + -DCONFIG_ASYNC_TCP_QUEUE_SIZE=128 + -DCONFIG_ASYNC_TCP_RUNNING_CORE=0 + -DCONFIG_ASYNC_TCP_STACK_SIZE=4096 + -DWS_MAX_QUEUED_MESSAGES=128 + -Wno-ignored-qualifiers + -Wno-missing-field-initializers + -Wno-type-limits + -Wno-maybe-uninitialized + -Wno-implicit-fallthrough + -Wno-unused-result lib_deps = + BleScanner=symlink://lib/BleScanner + esp-nimble-cpp=symlink://lib/esp-nimble-cpp lib_ignore = - esp-nimble-cpp - NetworkClientSecure - + NimBLE-Arduino + ESPAsyncTCP-esphome + AsyncTCP_RP2040W monitor_speed = 115200 monitor_filters = esp32_exception_decoder @@ -43,6 +66,7 @@ build_flags = ${env.build_flags} -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_NONE -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 + -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 [env:esp32-c3] extends = env:esp32dev @@ -52,8 +76,13 @@ board = esp32-c3-devkitc-02 extends = env:esp32dev board = nuki-esp32-s3 +[env:esp32-c6] +extends = env:esp32dev +board = esp32-c6-devkitm-1 + [env:esp32solo1] platform = https://github.com/tasmota/platform-espressif32/releases/download/2023.10.03/platform-espressif32-2023.10.03.zip +framework = arduino board = esp32-solo1 extra_scripts = post:pio_package.py build_flags = @@ -61,7 +90,13 @@ build_flags = -DFRAMEWORK_ARDUINO_SOLO1 -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_NONE -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 - + -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 +lib_deps = + BleScanner=symlink://lib/BleScanner +lib_ignore = + esp-nimble-cpp + NetworkClientSecure + [env:esp32dev_dbg] extends = env:esp32dev custom_build = debug @@ -69,6 +104,7 @@ build_flags = ${env.build_flags} -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 + -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND @@ -84,6 +120,23 @@ build_flags = ${env.build_flags} -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 + -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 + -DDEBUG_NUKIHUB + -DDEBUG_SENSE_NUKI + -DDEBUG_NUKI_COMMAND + -DDEBUG_NUKI_CONNECT + -DDEBUG_NUKI_COMMUNICATION + ;-DDEBUG_NUKI_HEX_DATA + -DDEBUG_NUKI_READABLE_DATA + +[env:esp32-c6_dbg] +extends = env:esp32-c6 +custom_build = debug +build_flags = + ${env.build_flags} + -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG + -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 + -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND @@ -99,6 +152,7 @@ build_flags = ${env.build_flags} -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 + -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND @@ -121,4 +175,4 @@ build_flags = -DDEBUG_NUKI_CONNECT -DDEBUG_NUKI_COMMUNICATION ;-DDEBUG_NUKI_HEX_DATA - -DDEBUG_NUKI_READABLE_DATA + -DDEBUG_NUKI_READABLE_DATA \ No newline at end of file diff --git a/bin/boot_app0.bin b/resources/boot_app0.bin similarity index 100% rename from bin/boot_app0.bin rename to resources/boot_app0.bin diff --git a/how-to-flash.txt b/resources/how-to-flash.txt similarity index 67% rename from how-to-flash.txt rename to resources/how-to-flash.txt index 0493d6e..c282568 100644 --- a/how-to-flash.txt +++ b/resources/how-to-flash.txt @@ -29,24 +29,35 @@ e000 boot_app0.bin 1000 bootloader.bin 8000 nuki_hub.partitions.bin 10000 nuki_hub_esp32.bin +280000 nuki_hub_updater_esp32.bin ESP32-S3 e000 boot_app0.bin 0 bootloader.bin 8000 nuki_hub.partitions.bin 10000 nuki_hub_esp32s3.bin +280000 nuki_hub_updater_esp32s3.bin ESP32-C3 e000 boot_app0.bin 0 bootloader.bin 8000 nuki_hub.partitions.bin 10000 nuki_hub_esp32c3.bin +280000 nuki_hub_updater_esp32c3.bin -ESP32-Solo1 +ESP32-C6 +e000 boot_app0.bin +0 bootloader.bin +8000 nuki_hub.partitions.bin +10000 nuki_hub_esp32c6.bin +280000 nuki_hub_updater_esp32c6.bin + +ESP32SOLO1 e000 boot_app0.bin 1000 bootloader.bin 8000 nuki_hub.partitions.bin 10000 nuki_hub_esp32solo1.bin +280000 nuki_hub_updater_esp32solo1.bin Make sure the checkmarks for all files are enabled. @@ -62,18 +73,22 @@ As an alternative to the Download Tools, you can also use the esptool from the E ## ESP32 -esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x1000 bootloader.bin 0x10000 nuki_hub_esp32.bin 0x8000 nuki_hub.partitions.bin +esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x1000 bootloader.bin 0x10000 nuki_hub_esp32.bin 0x280000 nuki_hub_updater_esp32.bin 0x8000 nuki_hub.partitions.bin ## ESP32-S3 -esptool.py --chip esp32s3 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x0 bootloader.bin 0x10000 nuki_hub_esp32s3.bin 0x8000 nuki_hub.partitions.bin +esptool.py --chip esp32s3 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x0 bootloader.bin 0x10000 nuki_hub_esp32s3.bin 0x280000 nuki_hub_updater_esp32s3.bin 0x8000 nuki_hub.partitions.bin ## ESP32-C3 -esptool.py --chip esp32c3 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x0 bootloader.bin 0x10000 nuki_hub_esp32c3.bin 0x8000 nuki_hub.partitions.bin +esptool.py --chip esp32c3 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x0 bootloader.bin 0x10000 nuki_hub_esp32c3.bin 0x280000 nuki_hub_updater_esp32c3.bin 0x8000 nuki_hub.partitions.bin -## ESP32Solo1 +## ESP32-C6 -esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x1000 bootloader.bin 0x10000 nuki_hub_esp32solo1.bin 0x8000 nuki_hub.partitions.bin +esptool.py --chip esp32c6 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x0 bootloader.bin 0x10000 nuki_hub_esp32c6.bin 0x280000 nuki_hub_updater_esp32c6.bin 0x8000 nuki_hub.partitions.bin -Adjust the serial device and path to the binaries if necessary. +## ESP32SOLO1 + +esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq keep --flash_size detect 0xe000 boot_app0.bin 0x1000 bootloader.bin 0x10000 nuki_hub_esp32solo1.bin 0x280000 nuki_hub_updater_esp32solo1.bin 0x8000 nuki_hub.partitions.bin + +Adjust the serial device and path to the binaries if necessary. \ No newline at end of file diff --git a/resources/style.css b/resources/style.css index ae8eb0c..0c296d2 100644 --- a/resources/style.css +++ b/resources/style.css @@ -105,7 +105,7 @@ h4 { font-size: 1.25rem } h5 { font-size: 1rem } h6 { font-size: .875rem } a { color: var(--nc-lk-1) } -a:hover { color: var(--nc-lk-2) } +a:hover { color: var(--nc-lk-2) !important; } abbr { cursor: help } abbr:hover { cursor: help } diff --git a/sdkconfig.defaults b/sdkconfig.defaults new file mode 100644 index 0000000..4e3f25b --- /dev/null +++ b/sdkconfig.defaults @@ -0,0 +1,67 @@ +CONFIG_AUTOSTART_ARDUINO=y +CONFIG_FREERTOS_HZ=1000 +CONFIG_MBEDTLS_PSK_MODES=y +CONFIG_MBEDTLS_KEY_EXCHANGE_PSK=y +CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE=y +CONFIG_BT_ENABLED=y +CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y +CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n +CONFIG_BTDM_CTRL_MODE_BTDM=n +CONFIG_BT_BLUEDROID_ENABLED=n +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_LOG_LEVEL_NONE=y +CONFIG_BT_NIMBLE_LOG_LEVEL=0 +CONFIG_NIMBLE_PINNED_TO_CORE_0=y +CONFIG_NIMBLE_PINNED_TO_CORE=0 +CONFIG_NIMBLE_TASK_STACK_SIZE=8192 +CONFIG_BT_NIMBLE_TASK_STACK_SIZE=8192 +CONFIG_NIMBLE_ROLE_CENTRAL=y +CONFIG_NIMBLE_ROLE_PERIPHERAL=y +CONFIG_NIMBLE_ROLE_BROADCASTER=y +CONFIG_NIMBLE_ROLE_OBSERVER=y +CONFIG_NIMBLE_SM_LEGACY=y +CONFIG_NIMBLE_SM_SC=y +CONFIG_NIMBLE_SVC_GAP_DEVICE_NAME="nimble" +CONFIG_NIMBLE_GAP_DEVICE_NAME_MAX_LEN=31 +CONFIG_NIMBLE_ATT_PREFERRED_MTU=256 +CONFIG_NIMBLE_SVC_GAP_APPEARANCE=0 +CONFIG_BT_NIMBLE_MSYS1_BLOCK_COUNT=12 +CONFIG_BT_NIMBLE_MSYS_1_BLOCK_SIZE=256 +CONFIG_BT_NIMBLE_MSYS_2_BLOCK_COUNT=24 +CONFIG_BT_NIMBLE_MSYS_2_BLOCK_SIZE=320 +CONFIG_BT_NIMBLE_ACL_BUF_COUNT=24 +CONFIG_BT_NIMBLE_ACL_BUF_SIZE=255 +CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE=70 +CONFIG_BT_NIMBLE_HCI_EVT_HI_BUF_COUNT=30 +CONFIG_BT_NIMBLE_HCI_EVT_LO_BUF_COUNT=8 +CONFIG_NIMBLE_HS_FLOW_CTRL=y +CONFIG_NIMBLE_HS_FLOW_CTRL_ITVL=1000 +CONFIG_NIMBLE_HS_FLOW_CTRL_THRESH=2 +CONFIG_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT=y +CONFIG_NIMBLE_RPA_TIMEOUT=900 +CONFIG_NIMBLE_CRYPTO_STACK_MBEDTLS=y +CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY=y +CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN=3 +CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF=3 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF=0 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF=0 +CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE=0 +CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI=y +CONFIG_BTDM_CONTROLLER_MODEM_SLEEP=y +CONFIG_BLE_SCAN_DUPLICATE=y +CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR=y +CONFIG_SCAN_DUPLICATE_TYPE=0 +CONFIG_DUPLICATE_SCAN_CACHE_SIZE=100 +CONFIG_BTDM_CONTROLLER_FULL_SCAN_SUPPORTED=y +CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED=y +CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_NUM=100 +CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD=20 +CONFIG_BT_NIMBLE_MSYS_BUF_FROM_HEAP=n +CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT=n +CONFIG_IEEE802154_ENABLED=n +CONFIG_ARDUINO_SELECTIVE_COMPILATION=y +CONFIG_ARDUINO_SELECTIVE_HTTPClient=n +CONFIG_ARDUINO_SELECTIVE_WebServer=n \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..483bc0c --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,6 @@ +# This file was automatically generated for projects +# without default 'CMakeLists.txt' file. + +FILE(GLOB_RECURSE app_sources ${CMAKE_SOURCE_DIR}/src/*.*) + +idf_component_register(SRCS ${app_sources}) diff --git a/src/Config.h b/src/Config.h index 85c284f..2068b3e 100644 --- a/src/Config.h +++ b/src/Config.h @@ -5,30 +5,39 @@ #define NUKI_HUB_VERSION "8.35" #define NUKI_HUB_BUILD "unknownbuildnr" -#define GITHUB_LATEST_RELEASE_URL "https://github.com/technyon/nuki_hub/releases/latest" -#define GITHUB_LATEST_RELEASE_API_URL "https://api.github.com/repos/technyon/nuki_hub/releases/latest" +#define GITHUB_LATEST_RELEASE_URL (char*)"https://github.com/technyon/nuki_hub/releases/latest" +#define GITHUB_LATEST_RELEASE_API_URL (char*)"https://api.github.com/repos/technyon/nuki_hub/releases/latest" #if defined(CONFIG_IDF_TARGET_ESP32C3) -#define GITHUB_LATEST_RELEASE_BINARY_URL "https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32c3.bin" +#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32c3.bin" +#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_updater_esp32c3.bin" #elif defined(CONFIG_IDF_TARGET_ESP32S3) -#define GITHUB_LATEST_RELEASE_BINARY_URL "https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32s3.bin" +#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32s3.bin" +#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_updater_esp32s3.bin" +#elif defined(CONFIG_IDF_TARGET_ESP32C6) +#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32c6.bin" +#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_updater_esp32c6.bin" #else #if defined(FRAMEWORK_ARDUINO_SOLO1) -#define GITHUB_LATEST_RELEASE_BINARY_URL "https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32solo1.bin" -#else +#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32solo1.bin" +#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_updater_esp32solo1.bin" +#else #define GITHUB_LATEST_RELEASE_BINARY_URL "https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_esp32.bin" +#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://github.com/technyon/nuki_hub/raw/master/ota/nuki_hub_updater_esp32.bin" #endif #endif +#ifndef NUKI_HUB_UPDATER #define MQTT_QOS_LEVEL 1 #define MQTT_CLEAN_SESSIONS false - +#define MQTT_KEEP_ALIVE 60 #define GPIO_DEBOUNCE_TIME 200 - #define CHAR_BUFFER_SIZE 4096 -#define NETWORK_TASK_SIZE 12288 #define NUKI_TASK_SIZE 8192 #define PD_TASK_SIZE 1024 #define MAX_AUTHLOG 5 #define MAX_KEYPAD 10 #define MAX_TIMECONTROL 10 +#endif + +#define NETWORK_TASK_SIZE 12288 \ No newline at end of file diff --git a/src/Gpio.cpp b/src/Gpio.cpp index f3d9334..74ffa6c 100644 --- a/src/Gpio.cpp +++ b/src/Gpio.cpp @@ -5,7 +5,7 @@ #include "Logger.h" #include "PreferencesKeys.h" #include "RestartReason.h" -#include "../lib/gpio2go/src/Gpio2Go.h" +#include "Gpio2Go.h" Gpio* Gpio::_inst = nullptr; unsigned long Gpio::_debounceTs = 0; diff --git a/src/Logger.h b/src/Logger.h index ba75c92..ce97d71 100644 --- a/src/Logger.h +++ b/src/Logger.h @@ -1,7 +1,13 @@ +#ifndef NUKI_HUB_UPDATER #ifndef MQTT_LOGGER_GLOBAL #define MQTT_LOGGER_GLOBAL #include "MqttLogger.h" +#include "WebSerial.h" extern Print* Log; +#endif +#else +#include +extern Print* Log; #endif \ No newline at end of file diff --git a/src/MqttTopics.h b/src/MqttTopics.h index de52c4e..f53ae46 100644 --- a/src/MqttTopics.h +++ b/src/MqttTopics.h @@ -14,7 +14,7 @@ #define mqtt_topic_lock_log "/lock/log" #define mqtt_topic_lock_log_latest "/lock/shortLog" #define mqtt_topic_lock_log_rolling "/lock/rollingLog" -#define mqtt_topic_lock_log_rolling_last "lock/lastRollingLog" +#define mqtt_topic_lock_log_rolling_last "/lock/lastRollingLog" #define mqtt_topic_lock_auth_id "/lock/authorizationId" #define mqtt_topic_lock_auth_name "/lock/authorizationName" #define mqtt_topic_lock_completionStatus "/lock/completionStatus" @@ -93,6 +93,7 @@ #define mqtt_topic_info_nuki_hub_ip "/info/nukiHubIp" #define mqtt_topic_reset "/maintenance/reset" +#define mqtt_topic_update "/maintenance/update" #define mqtt_topic_webserver_state "/maintenance/webserver/state" #define mqtt_topic_webserver_action "/maintenance/webserver/enable" #define mqtt_topic_uptime "/maintenance/uptime" diff --git a/src/NukiDeviceId.cpp b/src/NukiDeviceId.cpp index a6e6ecc..561273d 100644 --- a/src/NukiDeviceId.cpp +++ b/src/NukiDeviceId.cpp @@ -1,3 +1,4 @@ +#include #include #include #include "NukiDeviceId.h" diff --git a/src/Network.cpp b/src/NukiNetwork.cpp similarity index 94% rename from src/Network.cpp rename to src/NukiNetwork.cpp index fd7d2e6..18e8239 100644 --- a/src/Network.cpp +++ b/src/NukiNetwork.cpp @@ -1,25 +1,34 @@ -#include "Network.h" +#include "NukiNetwork.h" #include "PreferencesKeys.h" #include "networkDevices/W5500Device.h" #include "networkDevices/WifiDevice.h" #include "Logger.h" #include "Config.h" -#include #include "RestartReason.h" +#if defined(CONFIG_IDF_TARGET_ESP32) #include "networkDevices/EthLan8720Device.h" +#endif -Network* Network::_inst = nullptr; -unsigned long Network::_ignoreSubscriptionsTs = 0; +#ifndef NUKI_HUB_UPDATER +#include bool _versionPublished = false; +#endif + +NukiNetwork* NukiNetwork::_inst = nullptr; RTC_NOINIT_ATTR char WiFi_fallbackDetect[14]; -Network::Network(Preferences *preferences, PresenceDetection* presenceDetection, Gpio* gpio, const String& maintenancePathPrefix, char* buffer, size_t bufferSize) +#ifndef NUKI_HUB_UPDATER +NukiNetwork::NukiNetwork(Preferences *preferences, PresenceDetection* presenceDetection, Gpio* gpio, const String& maintenancePathPrefix, char* buffer, size_t bufferSize) : _preferences(preferences), _presenceDetection(presenceDetection), _gpio(gpio), _buffer(buffer), _bufferSize(bufferSize) +#else +NukiNetwork::NukiNetwork(Preferences *preferences) +: _preferences(preferences) +#endif { // Remove obsolete W5500 hardware detection configuration if(_preferences->getInt(preference_network_hardware_gpio) != 0) @@ -30,6 +39,7 @@ Network::Network(Preferences *preferences, PresenceDetection* presenceDetection, _inst = this; _hostname = _preferences->getString(preference_hostname); + #ifndef NUKI_HUB_UPDATER memset(_maintenancePathPrefix, 0, sizeof(_maintenancePathPrefix)); size_t len = maintenancePathPrefix.length(); for(int i=0; i < len; i++) @@ -46,11 +56,12 @@ Network::Network(Preferences *preferences, PresenceDetection* presenceDetection, { _mqttConnectionStateTopic[i] = connectionStateTopic.charAt(i); } + #endif setupDevice(); } -void Network::setupDevice() +void NukiNetwork::setupDevice() { _ipConfiguration = new IPConfiguration(_preferences); @@ -94,6 +105,7 @@ void Network::setupDevice() Log->println(F("W5500 on M5Stack Atom POE")); _networkDeviceType = NetworkDeviceType::W5500; break; + #if defined(CONFIG_IDF_TARGET_ESP32) case 4: Log->println(F("Olimex ESP32-POE / ESP-POE-ISO")); _networkDeviceType = NetworkDeviceType::Olimex_LAN8720; @@ -114,6 +126,7 @@ void Network::setupDevice() Log->println(F("GL-S10")); _networkDeviceType = NetworkDeviceType::GL_S10; break; + #endif default: Log->println(F("Unknown hardware selected, falling back to Wi-Fi.")); _networkDeviceType = NetworkDeviceType::WiFi; @@ -126,6 +139,7 @@ void Network::setupDevice() case NetworkDeviceType::W5500: _device = new W5500Device(_hostname, _preferences, _ipConfiguration, hardwareDetect); break; + #if defined(CONFIG_IDF_TARGET_ESP32) case NetworkDeviceType::Olimex_LAN8720: _device = new EthLan8720Device(_hostname, _preferences, _ipConfiguration, "Olimex (LAN8720)", ETH_PHY_ADDR, 12, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLOCK_GPIO17_OUT); break; @@ -141,6 +155,7 @@ void Network::setupDevice() case NetworkDeviceType::LilyGO_T_ETH_POE: _device = new EthLan8720Device(_hostname, _preferences, _ipConfiguration, "LilyGO T-ETH-POE", 0, -1, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLOCK_GPIO17_OUT); break; + #endif case NetworkDeviceType::WiFi: _device = new WifiDevice(_hostname, _preferences, _ipConfiguration); break; @@ -149,6 +164,7 @@ void Network::setupDevice() break; } + #ifndef NUKI_HUB_UPDATER _device->mqttOnConnect([&](bool sessionPresent) { onMqttConnect(sessionPresent); @@ -157,9 +173,68 @@ void Network::setupDevice() { onMqttDisconnect(reason); }); + #endif } -void Network::initialize() +void NukiNetwork::reconfigureDevice() +{ + _device->reconfigure(); +} + +const String NukiNetwork::networkDeviceName() const +{ + return _device->deviceName(); +} + +const String NukiNetwork::networkBSSID() const +{ + return _device->BSSIDstr(); +} + +const NetworkDeviceType NukiNetwork::networkDeviceType() +{ + return _networkDeviceType; +} + +void NukiNetwork::setKeepAliveCallback(std::function reconnectTick) +{ + _keepAliveCallback = reconnectTick; +} + +void NukiNetwork::clearWifiFallback() +{ + memset(WiFi_fallbackDetect, 0, sizeof(WiFi_fallbackDetect)); +} + +NetworkDevice *NukiNetwork::device() +{ + return _device; +} + +#ifdef NUKI_HUB_UPDATER +void NukiNetwork::initialize() +{ + _hostname = _preferences->getString(preference_hostname); + + if(_hostname == "") + { + _hostname = "nukihub"; + _preferences->putString(preference_hostname, _hostname); + } + strcpy(_hostnameArr, _hostname.c_str()); + _device->initialize(); + + Log->print(F("Host name: ")); + Log->println(_hostname); +} + +bool NukiNetwork::update() +{ + _device->update(); + return true; +} +#else +void NukiNetwork::initialize() { _restartOnDisconnect = _preferences->getBool(preference_restart_on_disconnect, false); _rssiPublishInterval = _preferences->getInt(preference_rssi_publish_interval) * 1000; @@ -219,6 +294,7 @@ void Network::initialize() _device->mqttSetClientId(_hostnameArr); _device->mqttSetCleanSession(MQTT_CLEAN_SESSIONS); + _device->mqttSetKeepAlive(MQTT_KEEP_ALIVE); _networkTimeout = _preferences->getInt(preference_network_timeout); if(_networkTimeout == 0) @@ -261,6 +337,8 @@ void Network::initialize() buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_state}); subscribe(_lockPath.c_str(), gpioPath); break; + default: + break; } } _gpio->addCallback([this](const GpioAction& action, const int& pin) @@ -269,7 +347,7 @@ void Network::initialize() }); } -bool Network::update() +bool NukiNetwork::update() { unsigned long ts = millis(); @@ -282,6 +360,8 @@ bool Network::update() if(!_device->isConnected()) { + _device->mqttDisconnect(true); + if(_restartOnDisconnect && millis() > 60000) { restartEsp(RestartReason::RestartOnDisconnectWatchdog); @@ -306,10 +386,9 @@ bool Network::update() Log->println(F("Reconnect failed")); break; } - } - if(!_device->mqttConnected()) + if(!_device->mqttConnected() && _device->isConnected()) { if(_networkTimeout > 0 && (ts - _lastConnectedTs > _networkTimeout * 1000) && ts > 60000) { @@ -323,16 +402,17 @@ bool Network::update() { return false; } + delay(2000); } + if(!_device->mqttConnected() || !_device->isConnected()) return false; + _lastConnectedTs = ts; if(_presenceDetection != nullptr && (_lastPresenceTs == 0 || (ts - _lastPresenceTs) > 3000)) { char* presenceCsv = _presenceDetection->generateCsv(); - -// if(_presenceCsv != nullptr && strlen(_presenceCsv) > 0) - bool success = publishString(_mqttPresencePrefix, mqtt_topic_presence, presenceCsv); + bool success = publishString(_mqttPresencePrefix, mqtt_topic_presence, presenceCsv, true); if(!success) { Log->println(F("Failed to publish presence CSV data.")); @@ -349,25 +429,25 @@ bool Network::update() if(rssi != _lastRssi) { - publishInt(_maintenancePathPrefix, mqtt_topic_wifi_rssi, _device->signalStrength()); + publishInt(_maintenancePathPrefix, mqtt_topic_wifi_rssi, _device->signalStrength(), true); _lastRssi = rssi; } } if(_lastMaintenanceTs == 0 || (ts - _lastMaintenanceTs) > 30000) { - publishULong(_maintenancePathPrefix, mqtt_topic_uptime, ts / 1000 / 60); - publishString(_maintenancePathPrefix, mqtt_topic_mqtt_connection_state, "online"); - + publishULong(_maintenancePathPrefix, mqtt_topic_uptime, ts / 1000 / 60, true); + publishString(_maintenancePathPrefix, mqtt_topic_mqtt_connection_state, "online", true); + if(_publishDebugInfo) { - publishUInt(_maintenancePathPrefix, mqtt_topic_freeheap, esp_get_free_heap_size()); - publishString(_maintenancePathPrefix, mqtt_topic_restart_reason_fw, getRestartReason().c_str()); - publishString(_maintenancePathPrefix, mqtt_topic_restart_reason_esp, getEspRestartReason().c_str()); + publishUInt(_maintenancePathPrefix, mqtt_topic_freeheap, esp_get_free_heap_size(), true); + publishString(_maintenancePathPrefix, mqtt_topic_restart_reason_fw, getRestartReason().c_str(), true); + publishString(_maintenancePathPrefix, mqtt_topic_restart_reason_esp, getEspRestartReason().c_str(), true); } if (!_versionPublished) { - publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_version, NUKI_HUB_VERSION); - publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_build, NUKI_HUB_BUILD); + publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_version, NUKI_HUB_VERSION, true); + publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_build, NUKI_HUB_BUILD, true); _versionPublished = true; } _lastMaintenanceTs = ts; @@ -392,7 +472,7 @@ bool Network::update() if (!jsonError) { _latestVersion = doc["tag_name"]; - publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_latest, _latestVersion); + publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_latest, _latestVersion, true); if (_latestVersion != _preferences->getString(preference_latest_version).c_str()) { @@ -429,14 +509,14 @@ bool Network::update() } -void Network::onMqttConnect(const bool &sessionPresent) +void NukiNetwork::onMqttConnect(const bool &sessionPresent) { _connectReplyReceived = true; } -void Network::onMqttDisconnect(const espMqttClientTypes::DisconnectReason &reason) +void NukiNetwork::onMqttDisconnect(const espMqttClientTypes::DisconnectReason &reason) { - _connectReplyReceived = true; + _connectReplyReceived = false; Log->print("MQTT disconnected. Reason: "); switch(reason) @@ -471,7 +551,7 @@ void Network::onMqttDisconnect(const espMqttClientTypes::DisconnectReason &reaso } } -bool Network::reconnect() +bool NukiNetwork::reconnect() { _mqttConnectionState = 0; int port = _preferences->getInt(preference_mqtt_broker_port); @@ -521,8 +601,7 @@ bool Network::reconnect() _mqttConnectionState = 1; delay(100); - _ignoreSubscriptionsTs = millis() + 2000; - _device->mqttOnMessage(Network::onMqttDataReceivedCallback); + _device->mqttOnMessage(NukiNetwork::onMqttDataReceivedCallback); for(const String& topic : _subscribedTopics) { _device->mqttSubscribe(topic.c_str(), MQTT_QOS_LEVEL); @@ -530,15 +609,15 @@ bool Network::reconnect() if(_firstConnect) { _firstConnect = false; - publishString(_maintenancePathPrefix, mqtt_topic_network_device, _device->deviceName().c_str()); + publishString(_maintenancePathPrefix, mqtt_topic_network_device, _device->deviceName().c_str(), true); for(const auto& it : _initTopics) { _device->mqttPublish(it.first.c_str(), MQTT_QOS_LEVEL, true, it.second.c_str()); } } - publishString(_maintenancePathPrefix, mqtt_topic_mqtt_connection_state, "online"); - publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_ip, _device->localIP().c_str()); + publishString(_maintenancePathPrefix, mqtt_topic_mqtt_connection_state, "online", true); + publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_ip, _device->localIP().c_str(), true); _mqttConnectionState = 2; for(const auto& callback : _reconnectedCallbacks) @@ -552,20 +631,20 @@ bool Network::reconnect() _device->printError(); _mqttConnectionState = 0; _nextReconnect = millis() + 5000; - _device->mqttDisconnect(true); + //_device->mqttDisconnect(true); } } return _mqttConnectionState > 0; } -void Network::subscribe(const char* prefix, const char *path) +void NukiNetwork::subscribe(const char* prefix, const char *path) { char prefixedPath[500]; buildMqttPath(prefixedPath, { prefix, path }); _subscribedTopics.push_back(prefixedPath); } -void Network::initTopic(const char *prefix, const char *path, const char *value) +void NukiNetwork::initTopic(const char *prefix, const char *path, const char *value) { char prefixedPath[500]; buildMqttPath(prefixedPath, { prefix, path }); @@ -574,7 +653,7 @@ void Network::initTopic(const char *prefix, const char *path, const char *value) _initTopics[pathStr] = valueStr; } -void Network::buildMqttPath(char* outPath, std::initializer_list paths) +void NukiNetwork::buildMqttPath(char* outPath, std::initializer_list paths) { int offset = 0; int pathCount = 0; @@ -600,12 +679,12 @@ void Network::buildMqttPath(char* outPath, std::initializer_list pa outPath[offset] = 0x00; } -void Network::registerMqttReceiver(MqttReceiver* receiver) +void NukiNetwork::registerMqttReceiver(MqttReceiver* receiver) { _mqttReceivers.push_back(receiver); } -void Network::onMqttDataReceivedCallback(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) +void NukiNetwork::onMqttDataReceivedCallback(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { uint8_t value[800] = {0}; @@ -619,15 +698,10 @@ void Network::onMqttDataReceivedCallback(const espMqttClientTypes::MessageProper _inst->onMqttDataReceived(properties, topic, value, len, index, total); } -void Network::onMqttDataReceived(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total) +void NukiNetwork::onMqttDataReceived(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total) { parseGpioTopics(properties, topic, payload, len, index, total); - if(millis() < _ignoreSubscriptionsTs) - { - return; - } - for(auto receiver : _mqttReceivers) { receiver->onMqttDataReceived(topic, (byte*)payload, index); @@ -635,7 +709,7 @@ void Network::onMqttDataReceived(const espMqttClientTypes::MessageProperties& pr } -void Network::parseGpioTopics(const espMqttClientTypes::MessageProperties &properties, const char *topic, const uint8_t *payload, size_t& len, size_t& index, size_t& total) +void NukiNetwork::parseGpioTopics(const espMqttClientTypes::MessageProperties &properties, const char *topic, const uint8_t *payload, size_t& len, size_t& index, size_t& total) { char gpioPath[250]; buildMqttPath(gpioPath, {_lockPath.c_str(), mqtt_topic_gpio_prefix, mqtt_topic_gpio_pin}); @@ -665,49 +739,34 @@ void Network::parseGpioTopics(const espMqttClientTypes::MessageProperties &prope } } -void Network::gpioActionCallback(const GpioAction &action, const int &pin) +void NukiNetwork::gpioActionCallback(const GpioAction &action, const int &pin) { _gpioTs[pin] = millis(); } -void Network::reconfigureDevice() -{ - _device->reconfigure(); -} - -void Network::setMqttPresencePath(char *path) +void NukiNetwork::setMqttPresencePath(char *path) { memset(_mqttPresencePrefix, 0, sizeof(_mqttPresencePrefix)); strcpy(_mqttPresencePrefix, path); } -void Network::disableAutoRestarts() +void NukiNetwork::disableAutoRestarts() { _networkTimeout = 0; _restartOnDisconnect = false; } -int Network::mqttConnectionState() +int NukiNetwork::mqttConnectionState() { return _mqttConnectionState; } -bool Network::encryptionSupported() +bool NukiNetwork::encryptionSupported() { return _device->supportsEncryption(); } -const String Network::networkDeviceName() const -{ - return _device->deviceName(); -} - -const String Network::networkBSSID() const -{ - return _device->BSSIDstr(); -} - -void Network::publishFloat(const char* prefix, const char* topic, const float value, const uint8_t precision, bool retain) +void NukiNetwork::publishFloat(const char* prefix, const char* topic, const float value, const uint8_t precision, bool retain) { char str[30]; dtostrf(value, 0, precision, str); @@ -716,7 +775,7 @@ void Network::publishFloat(const char* prefix, const char* topic, const float va _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); } -void Network::publishInt(const char* prefix, const char *topic, const int value, bool retain) +void NukiNetwork::publishInt(const char* prefix, const char *topic, const int value, bool retain) { char str[30]; itoa(value, str, 10); @@ -725,7 +784,7 @@ void Network::publishInt(const char* prefix, const char *topic, const int value, _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); } -void Network::publishUInt(const char* prefix, const char *topic, const unsigned int value, bool retain) +void NukiNetwork::publishUInt(const char* prefix, const char *topic, const unsigned int value, bool retain) { char str[30]; utoa(value, str, 10); @@ -734,7 +793,7 @@ void Network::publishUInt(const char* prefix, const char *topic, const unsigned _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); } -void Network::publishULong(const char* prefix, const char *topic, const unsigned long value, bool retain) +void NukiNetwork::publishULong(const char* prefix, const char *topic, const unsigned long value, bool retain) { char str[30]; utoa(value, str, 10); @@ -743,7 +802,7 @@ void Network::publishULong(const char* prefix, const char *topic, const unsigned _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); } -void Network::publishBool(const char* prefix, const char *topic, const bool value, bool retain) +void NukiNetwork::publishBool(const char* prefix, const char *topic, const bool value, bool retain) { char str[2] = {0}; str[0] = value ? '1' : '0'; @@ -752,14 +811,14 @@ void Network::publishBool(const char* prefix, const char *topic, const bool valu _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); } -bool Network::publishString(const char* prefix, const char *topic, const char *value, bool retain) +bool NukiNetwork::publishString(const char* prefix, const char *topic, const char *value, bool retain) { char path[200] = {0}; buildMqttPath(path, { prefix, topic }); return _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, value) > 0; } -void Network::publishHASSConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const char* availabilityTopic, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction) +void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const char* availabilityTopic, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction) { JsonDocument json; json.clear(); @@ -843,7 +902,7 @@ void Network::publishHASSConfig(char* deviceType, const char* baseTopic, char* n "diagnostic", "", { {(char*)"unit_of_meas", (char*)"V"}, - {(char*)"val_tpl", (char*)"{{value_json.level}}" }}); + {(char*)"val_tpl", (char*)"{{value_json.batteryVoltage}}" }}); // Trigger publishHassTopic("sensor", @@ -991,23 +1050,47 @@ void Network::publishHASSConfig(char* deviceType, const char* baseTopic, char* n _lockPath.toCharArray(latest_version_topic,_lockPath.length() + 1); strcat(latest_version_topic, mqtt_topic_info_nuki_hub_latest); - publishHassTopic("update", - "nuki_hub_update", - uidString, - "_nuki_hub_update", - "NUKI Hub firmware update", - name, - baseTopic, - _lockPath + mqtt_topic_info_nuki_hub_version, - deviceType, - "firmware", - "", - "diagnostic", - "", - { { (char*)"en", (char*)"true" }, - { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, - { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, - { (char*)"l_ver_t", (char*)latest_version_topic }}); + if(!_preferences->getBool(preference_update_from_mqtt, false)) + { + publishHassTopic("update", + "nuki_hub_update", + uidString, + "_nuki_hub_update", + "NUKI Hub firmware update", + name, + baseTopic, + _lockPath + mqtt_topic_info_nuki_hub_version, + deviceType, + "firmware", + "", + "diagnostic", + "", + { { (char*)"en", (char*)"true" }, + { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, + { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, + { (char*)"l_ver_t", (char*)latest_version_topic }}); + } + else + { + publishHassTopic("update", + "nuki_hub_update", + uidString, + "_nuki_hub_update", + "NUKI Hub firmware update", + name, + baseTopic, + _lockPath + mqtt_topic_info_nuki_hub_version, + deviceType, + "firmware", + "", + "diagnostic", + _lockPath + mqtt_topic_update, + { { (char*)"en", (char*)"true" }, + { (char*)"pl_inst", (char*)"1" }, + { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, + { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, + { (char*)"l_ver_t", (char*)latest_version_topic }}); + } } else { @@ -1099,8 +1182,7 @@ void Network::publishHASSConfig(char* deviceType, const char* baseTopic, char* n { {(char*)"unit_of_meas", (char*)"dBm"} }); } - -void Network::publishHASSConfigAdditionalLockEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) +void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) { uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); @@ -2150,7 +2232,7 @@ void Network::publishHASSConfigAdditionalLockEntities(char *deviceType, const ch } } -void Network::publishHASSConfigDoorSensor(char *deviceType, const char *baseTopic, char *name, char *uidString) +void NukiNetwork::publishHASSConfigDoorSensor(char *deviceType, const char *baseTopic, char *name, char *uidString) { publishHassTopic("binary_sensor", "door_sensor", @@ -2170,7 +2252,7 @@ void Network::publishHASSConfigDoorSensor(char *deviceType, const char *baseTopi {(char*)"pl_not_avail", (char*)"unavailable"}}); } -void Network::publishHASSConfigAdditionalOpenerEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) +void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) { uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); @@ -3027,7 +3109,7 @@ void Network::publishHASSConfigAdditionalOpenerEntities(char *deviceType, const } } -void Network::publishHASSConfigAccessLog(char *deviceType, const char *baseTopic, char *name, char *uidString) +void NukiNetwork::publishHASSConfigAccessLog(char *deviceType, const char *baseTopic, char *name, char *uidString) { publishHassTopic("sensor", "last_action_authorization", @@ -3064,10 +3146,10 @@ void Network::publishHASSConfigAccessLog(char *deviceType, const char *baseTopic "", { { (char*)"ic", (char*)"mdi:format-list-bulleted" }, { (char*)"json_attr_t", (char*)rollingStateChr }, - { (char*)"val_tpl", (char*)"{{value_json.authorizationId}}" }}); + { (char*)"val_tpl", (char*)"{{value_json.index}}" }}); } -void Network::publishHASSConfigKeypad(char *deviceType, const char *baseTopic, char *name, char *uidString) +void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopic, char *name, char *uidString) { // Keypad battery critical publishHassTopic("binary_sensor", @@ -3121,7 +3203,7 @@ void Network::publishHASSConfigKeypad(char *deviceType, const char *baseTopic, c { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'KeypadAction')|first|default).completionStatus|default }}" }}); } -void Network::publishHASSWifiRssiConfig(char *deviceType, const char *baseTopic, char *name, char *uidString) +void NukiNetwork::publishHASSWifiRssiConfig(char *deviceType, const char *baseTopic, char *name, char *uidString) { if(_device->signalStrength() == 127) { @@ -3144,7 +3226,7 @@ void Network::publishHASSWifiRssiConfig(char *deviceType, const char *baseTopic, { {(char*)"unit_of_meas", (char*)"dBm"} }); } -void Network::publishHassTopic(const String& mqttDeviceType, +void NukiNetwork::publishHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString, const String& uidStringPostfix, @@ -3172,7 +3254,7 @@ void Network::publishHassTopic(const String& mqttDeviceType, } } -String Network::createHassTopicPath(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString) +String NukiNetwork::createHassTopicPath(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString) { String discoveryTopic = _preferences->getString(preference_mqtt_hass_discovery); String path = discoveryTopic; @@ -3187,7 +3269,7 @@ String Network::createHassTopicPath(const String& mqttDeviceType, const String& return path; } -void Network::removeHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString) +void NukiNetwork::removeHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString) { String discoveryTopic = _preferences->getString(preference_mqtt_hass_discovery); @@ -3198,7 +3280,7 @@ void Network::removeHassTopic(const String& mqttDeviceType, const String& mqttDe } } -void Network::removeTopic(const String& mqttPath, const String& mqttTopic) +void NukiNetwork::removeTopic(const String& mqttPath, const String& mqttTopic) { String path = mqttPath; path.concat(mqttTopic); @@ -3211,7 +3293,7 @@ void Network::removeTopic(const String& mqttPath, const String& mqttTopic) } -void Network::removeHASSConfig(char* uidString) +void NukiNetwork::removeHASSConfig(char* uidString) { removeHassTopic((char*)"lock", (char*)"smartlock", uidString); removeHassTopic((char*)"binary_sensor", (char*)"battery_low", uidString); @@ -3300,12 +3382,12 @@ void Network::removeHASSConfig(char* uidString) removeHassTopic((char*)"switch", (char*)"auto_unlatch", uidString); } -void Network::removeHASSConfigTopic(char *deviceType, char *name, char *uidString) +void NukiNetwork::removeHASSConfigTopic(char *deviceType, char *name, char *uidString) { removeHassTopic(deviceType, name, uidString); } -JsonDocument Network::createHassJson(const String& uidString, +JsonDocument NukiNetwork::createHassJson(const String& uidString, const String& uidStringPostfix, const String& displayName, const String& name, @@ -3377,7 +3459,7 @@ JsonDocument Network::createHassJson(const String& uidString, return json; } -void Network::batteryTypeToString(const Nuki::BatteryType battype, char* str) { +void NukiNetwork::batteryTypeToString(const Nuki::BatteryType battype, char* str) { switch (battype) { case Nuki::BatteryType::Alkali: strcpy(str, "Alkali"); @@ -3394,7 +3476,7 @@ void Network::batteryTypeToString(const Nuki::BatteryType battype, char* str) { } } -void Network::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str) { +void NukiNetwork::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str) { switch (advmode) { case Nuki::AdvertisingMode::Automatic: strcpy(str, "Automatic"); @@ -3414,7 +3496,7 @@ void Network::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* } } -void Network::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) { +void NukiNetwork::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) { switch (timeZoneId) { case Nuki::TimeZoneId::Africa_Cairo: strcpy(str, "Africa/Cairo"); @@ -3563,38 +3645,19 @@ void Network::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) { } } -const NetworkDeviceType Network::networkDeviceType() -{ - return _networkDeviceType; -} - -uint16_t Network::subscribe(const char *topic, uint8_t qos) +uint16_t NukiNetwork::subscribe(const char *topic, uint8_t qos) { return _device->mqttSubscribe(topic, qos); } -void Network::setKeepAliveCallback(std::function reconnectTick) -{ - _keepAliveCallback = reconnectTick; -} - -void Network::addReconnectedCallback(std::function reconnectedCallback) +void NukiNetwork::addReconnectedCallback(std::function reconnectedCallback) { _reconnectedCallbacks.push_back(reconnectedCallback); } -void Network::clearWifiFallback() -{ - memset(WiFi_fallbackDetect, 0, sizeof(WiFi_fallbackDetect)); -} - -void Network::disableMqtt() +void NukiNetwork::disableMqtt() { _device->disableMqtt(); _mqttEnabled = false; } - -NetworkDevice *Network::device() -{ - return _device; -} +#endif \ No newline at end of file diff --git a/src/Network.h b/src/NukiNetwork.h similarity index 95% rename from src/Network.h rename to src/NukiNetwork.h index aa26ef2..a962a09 100644 --- a/src/Network.h +++ b/src/NukiNetwork.h @@ -4,14 +4,17 @@ #include #include #include "networkDevices/NetworkDevice.h" -#include "MqttReceiver.h" #include "networkDevices/IPConfiguration.h" +#include + +#ifndef NUKI_HUB_UPDATER +#include "MqttReceiver.h" #include "MqttTopics.h" #include "Gpio.h" #include -#include #include "NukiConstants.h" #include "PresenceDetection.h" +#endif enum class NetworkDeviceType { @@ -26,20 +29,27 @@ enum class NetworkDeviceType #define JSON_BUFFER_SIZE 1024 -class Network +class NukiNetwork { public: - explicit Network(Preferences* preferences, - PresenceDetection* presenceDetection, - Gpio* gpio, - const String& maintenancePathPrefix, - char* buffer, - size_t bufferSize); - void initialize(); bool update(); - void registerMqttReceiver(MqttReceiver* receiver); void reconfigureDevice(); + void clearWifiFallback(); + + const String networkDeviceName() const; + const String networkBSSID() const; + const NetworkDeviceType networkDeviceType(); + void setKeepAliveCallback(std::function reconnectTick); + + NetworkDevice* device(); + + #ifdef NUKI_HUB_UPDATER + explicit NukiNetwork(Preferences* preferences); + #else + explicit NukiNetwork(Preferences* preferences, PresenceDetection* presenceDetection, Gpio* gpio, const String& maintenancePathPrefix, char* buffer, size_t bufferSize); + + void registerMqttReceiver(MqttReceiver* receiver); void setMqttPresencePath(char* path); void disableAutoRestarts(); // disable on OTA start void disableMqtt(); @@ -83,29 +93,38 @@ public: void advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str); void timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str); - void clearWifiFallback(); - int mqttConnectionState(); // 0 = not connected; 1 = connected; 2 = connected and mqtt processed bool encryptionSupported(); - const String networkDeviceName() const; - const String networkBSSID() const; - - const NetworkDeviceType networkDeviceType(); uint16_t subscribe(const char* topic, uint8_t qos); - void setKeepAliveCallback(std::function reconnectTick); void addReconnectedCallback(std::function reconnectedCallback); - - NetworkDevice* device(); - + #endif private: + void setupDevice(); + bool reconnect(); + + static NukiNetwork* _inst; + + const char* _latestVersion; + HTTPClient https; + + Preferences* _preferences; + IPConfiguration* _ipConfiguration = nullptr; + String _hostname; + char _hostnameArr[101] = {0}; + NetworkDevice* _device = nullptr; + + std::function _keepAliveCallback = nullptr; + std::vector> _reconnectedCallbacks; + + NetworkDeviceType _networkDeviceType = (NetworkDeviceType)-1; + + #ifndef NUKI_HUB_UPDATER static void onMqttDataReceivedCallback(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total); void onMqttDataReceived(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total); void parseGpioTopics(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total); void gpioActionCallback(const GpioAction& action, const int& pin); - void setupDevice(); - bool reconnect(); String createHassTopicPath(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString); JsonDocument createHassJson(const String& uidString, @@ -127,22 +146,13 @@ private: void buildMqttPath(char* outPath, std::initializer_list paths); - static Network* _inst; - const char* _lastWillPayload = "offline"; char _mqttConnectionStateTopic[211] = {0}; String _lockPath; - const char* _latestVersion; - HTTPClient https; - - Preferences* _preferences; PresenceDetection* _presenceDetection; Gpio* _gpio; - IPConfiguration* _ipConfiguration = nullptr; - String _hostname; - char _hostnameArr[101] = {0}; - NetworkDevice* _device = nullptr; + int _mqttConnectionState = 0; bool _connectReplyReceived = false; @@ -166,18 +176,12 @@ private: unsigned long _lastPresenceTs = 0; unsigned long _lastRssiTs = 0; bool _mqttEnabled = true; - static unsigned long _ignoreSubscriptionsTs; long _rssiPublishInterval = 0; std::map _gpioTs; char* _buffer; const size_t _bufferSize; - std::function _keepAliveCallback = nullptr; - std::vector> _reconnectedCallbacks; - - NetworkDeviceType _networkDeviceType = (NetworkDeviceType)-1; - int8_t _lastRssi = 127; - -}; + #endif +}; \ No newline at end of file diff --git a/src/NetworkLock.cpp b/src/NukiNetworkLock.cpp similarity index 84% rename from src/NetworkLock.cpp rename to src/NukiNetworkLock.cpp index 72a5963..8f8b84c 100644 --- a/src/NetworkLock.cpp +++ b/src/NukiNetworkLock.cpp @@ -1,6 +1,7 @@ -#include "NetworkLock.h" +#include "NukiNetworkLock.h" #include // https://github.com/tzapu/WiFiManager #include "Arduino.h" +#include "Config.h" #include "MqttTopics.h" #include "PreferencesKeys.h" #include "Logger.h" @@ -8,7 +9,7 @@ #include #include -NetworkLock::NetworkLock(Network* network, Preferences* preferences, char* buffer, size_t bufferSize) +NukiNetworkLock::NukiNetworkLock(NukiNetwork* network, Preferences* preferences, char* buffer, size_t bufferSize) : _network(network), _preferences(preferences), _buffer(buffer), @@ -33,11 +34,11 @@ NetworkLock::NetworkLock(Network* network, Preferences* preferences, char* buffe _network->registerMqttReceiver(this); } -NetworkLock::~NetworkLock() +NukiNetworkLock::~NukiNetworkLock() { } -void NetworkLock::initialize() +void NukiNetworkLock::initialize() { String mqttPath = _preferences->getString(preference_mqtt_lock_path); if(mqttPath.length() > 0) @@ -63,8 +64,16 @@ void NetworkLock::initialize() _network->initTopic(_mqttPath, mqtt_topic_config_action, "--"); _network->subscribe(_mqttPath, mqtt_topic_config_action); - _network->subscribe(_mqttPath, mqtt_topic_reset); - _network->initTopic(_mqttPath, mqtt_topic_reset, "0"); + if(_preferences->getBool(preference_update_from_mqtt, false)) + { + _network->subscribe(_mqttPath, mqtt_topic_reset); + _network->initTopic(_mqttPath, mqtt_topic_reset, "0"); + } + + #if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) + _network->subscribe(_mqttPath, mqtt_topic_update); + _network->initTopic(_mqttPath, mqtt_topic_update, "0"); + #endif _network->subscribe(_mqttPath, mqtt_topic_webserver_action); _network->initTopic(_mqttPath, mqtt_topic_webserver_action, "--"); @@ -167,7 +176,7 @@ void NetworkLock::initialize() }); } -void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) +void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) { char* value = (char*)payload; @@ -178,6 +187,16 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns delay(200); restartEsp(RestartReason::RequestedViaMqtt); } + #if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) + else if(comparePrefixedPath(topic, mqtt_topic_update) && strcmp(value, "1") == 0 && _preferences->getBool(preference_update_from_mqtt, false)) + { + Log->println(F("Update requested via MQTT.")); + _preferences->putString(preference_ota_updater_url, GITHUB_LATEST_UPDATER_BINARY_URL); + _preferences->putString(preference_ota_main_url, GITHUB_LATEST_RELEASE_BINARY_URL); + delay(200); + restartEsp(RestartReason::OTAReboot); + } + #endif else if(comparePrefixedPath(topic, mqtt_topic_webserver_action)) { if(strcmp(value, "") == 0 || @@ -197,7 +216,7 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns _preferences->putBool(preference_webserver_enabled, false); } - publishString(mqtt_topic_webserver_action, "--"); + publishString(mqtt_topic_webserver_action, "--", true); _network->clearWifiFallback(); delay(200); restartEsp(RestartReason::RequestedViaMqtt); @@ -275,12 +294,12 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns if(strcmp(value, "--") != 0) { - publishString(mqtt_topic_keypad_command_action, "--"); + publishString(mqtt_topic_keypad_command_action, "--", true); } - publishInt(mqtt_topic_keypad_command_id, _keypadCommandId); - publishString(mqtt_topic_keypad_command_name, _keypadCommandName); - publishString(mqtt_topic_keypad_command_code, _keypadCommandCode); - publishInt(mqtt_topic_keypad_command_enabled, _keypadCommandEnabled); + publishInt(mqtt_topic_keypad_command_id, _keypadCommandId, true); + publishString(mqtt_topic_keypad_command_name, _keypadCommandName, true); + publishString(mqtt_topic_keypad_command_code, _keypadCommandCode, true); + publishInt(mqtt_topic_keypad_command_enabled, _keypadCommandEnabled, true); } } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_id)) @@ -304,22 +323,22 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns if(comparePrefixedPath(topic, mqtt_topic_query_config) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_CONFIG; - publishString(mqtt_topic_query_config, "0"); + publishString(mqtt_topic_query_config, "0", true); } else if(comparePrefixedPath(topic, mqtt_topic_query_lockstate) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_LOCKSTATE; - publishString(mqtt_topic_query_lockstate, "0"); + publishString(mqtt_topic_query_lockstate, "0", true); } else if(comparePrefixedPath(topic, mqtt_topic_query_keypad) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_KEYPAD; - publishString(mqtt_topic_query_keypad, "0"); + publishString(mqtt_topic_query_keypad, "0", true); } else if(comparePrefixedPath(topic, mqtt_topic_query_battery) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_BATTERY; - publishString(mqtt_topic_query_battery, "0"); + publishString(mqtt_topic_query_battery, "0", true); } if(comparePrefixedPath(topic, mqtt_topic_config_action)) @@ -331,7 +350,7 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns _configUpdateReceivedCallback(value); } - publishString(mqtt_topic_config_action, "--"); + publishString(mqtt_topic_config_action, "--", true); } if(comparePrefixedPath(topic, mqtt_topic_keypad_json_action)) @@ -343,7 +362,7 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns _keypadJsonCommandReceivedReceivedCallback(value); } - publishString(mqtt_topic_keypad_json_action, "--"); + publishString(mqtt_topic_keypad_json_action, "--", true); } if(comparePrefixedPath(topic, mqtt_topic_timecontrol_action)) @@ -355,11 +374,11 @@ void NetworkLock::onMqttDataReceived(const char* topic, byte* payload, const uns _timeControlCommandReceivedReceivedCallback(value); } - publishString(mqtt_topic_timecontrol_action, "--"); + publishString(mqtt_topic_timecontrol_action, "--", true); } } -void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurnerState, const NukiLock::KeyTurnerState& lastKeyTurnerState) +void NukiNetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurnerState, const NukiLock::KeyTurnerState& lastKeyTurnerState) { char str[50]; memset(&str, 0, sizeof(str)); @@ -374,7 +393,7 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne if(keyTurnerState.lockState != NukiLock::LockState::Undefined) { - publishString(mqtt_topic_lock_state, str); + publishString(mqtt_topic_lock_state, str, true); if(_haEnabled) { @@ -400,7 +419,7 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne if(_firstTunerStatePublish || keyTurnerState.trigger != lastKeyTurnerState.trigger) { - publishString(mqtt_topic_lock_trigger, str); + publishString(mqtt_topic_lock_trigger, str, true); } json["trigger"] = str; @@ -425,7 +444,7 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne if(_firstTunerStatePublish || keyTurnerState.lastLockAction != lastKeyTurnerState.lastLockAction) { - publishString(mqtt_topic_lock_last_lock_action, str); + publishString(mqtt_topic_lock_last_lock_action, str, true); } json["last_lock_action"] = str; @@ -445,7 +464,7 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne if(_firstTunerStatePublish || keyTurnerState.lastLockActionCompletionStatus != lastKeyTurnerState.lastLockActionCompletionStatus) { - publishString(mqtt_topic_lock_completionStatus, str); + publishString(mqtt_topic_lock_completionStatus, str, true); } json["lock_completion_status"] = str; @@ -457,7 +476,7 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne if(_firstTunerStatePublish || keyTurnerState.doorSensorState != lastKeyTurnerState.doorSensorState) { - publishString(mqtt_topic_lock_door_sensor_state, str); + publishString(mqtt_topic_lock_door_sensor_state, str, true); } json["door_sensor_state"] = str; @@ -474,14 +493,14 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne if((_firstTunerStatePublish || keyTurnerState.criticalBatteryState != lastKeyTurnerState.criticalBatteryState) && !_preferences->getBool(preference_disable_non_json, false)) { - publishBool(mqtt_topic_battery_critical, critical); - publishBool(mqtt_topic_battery_charging, charging); - publishInt(mqtt_topic_battery_level, level); + publishBool(mqtt_topic_battery_critical, critical, true); + publishBool(mqtt_topic_battery_charging, charging, true); + publishInt(mqtt_topic_battery_level, level, true); } if((_firstTunerStatePublish || keyTurnerState.accessoryBatteryState != lastKeyTurnerState.accessoryBatteryState) && !_preferences->getBool(preference_disable_non_json, false)) { - publishBool(mqtt_topic_battery_keypad_critical, keypadCritical); + publishBool(mqtt_topic_battery_keypad_critical, keypadCritical, true); } } else @@ -494,55 +513,55 @@ void NetworkLock::publishKeyTurnerState(const NukiLock::KeyTurnerState& keyTurne json["auth_name"] = _authName; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_lock_json, _buffer); + publishString(mqtt_topic_lock_json, _buffer, true); serializeJson(jsonBattery, _buffer, _bufferSize); - publishString(mqtt_topic_battery_basic_json, _buffer); + publishString(mqtt_topic_battery_basic_json, _buffer, true); _firstTunerStatePublish = false; } -void NetworkLock::publishState(NukiLock::LockState lockState) +void NukiNetworkLock::publishState(NukiLock::LockState lockState) { switch(lockState) { case NukiLock::LockState::Locked: - publishString(mqtt_topic_lock_ha_state, "locked"); - publishString(mqtt_topic_lock_binary_state, "locked"); + publishString(mqtt_topic_lock_ha_state, "locked", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); break; case NukiLock::LockState::Locking: - publishString(mqtt_topic_lock_ha_state, "locking"); - publishString(mqtt_topic_lock_binary_state, "locked"); + publishString(mqtt_topic_lock_ha_state, "locking", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); break; case NukiLock::LockState::Unlocking: - publishString(mqtt_topic_lock_ha_state, "unlocking"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "unlocking", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiLock::LockState::Unlocked: case NukiLock::LockState::UnlockedLnga: - publishString(mqtt_topic_lock_ha_state, "unlocked"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "unlocked", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiLock::LockState::Unlatched: - publishString(mqtt_topic_lock_ha_state, "open"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "open", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiLock::LockState::Unlatching: - publishString(mqtt_topic_lock_ha_state, "opening"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "opening", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiLock::LockState::Uncalibrated: case NukiLock::LockState::Calibration: case NukiLock::LockState::BootRun: case NukiLock::LockState::MotorBlocked: - publishString(mqtt_topic_lock_ha_state, "jammed"); + publishString(mqtt_topic_lock_ha_state, "jammed", true); break; default: break; } } -void NetworkLock::publishAuthorizationInfo(const std::list& logEntries, bool latest) +void NukiNetworkLock::publishAuthorizationInfo(const std::list& logEntries, bool latest) { char str[50]; char authName[33]; @@ -659,46 +678,47 @@ void NetworkLock::publishAuthorizationInfo(const std::list& _lastRollingLog = log.index; serializeJson(entry, _buffer, _bufferSize); publishString(mqtt_topic_lock_log_rolling, _buffer); - publishInt(mqtt_topic_lock_log_rolling_last, log.index); + publishInt(mqtt_topic_lock_log_rolling_last, log.index, true); } } serializeJson(json, _buffer, _bufferSize); - if(latest) publishString(mqtt_topic_lock_log_latest, _buffer); - else publishString(mqtt_topic_lock_log, _buffer); + if(latest) publishString(mqtt_topic_lock_log_latest, _buffer, true); + else publishString(mqtt_topic_lock_log, _buffer, true); if(authIndex > 0) { - publishUInt(mqtt_topic_lock_auth_id, _authId); - publishString(mqtt_topic_lock_auth_name, _authName); + publishUInt(mqtt_topic_lock_auth_id, _authId, true); + publishString(mqtt_topic_lock_auth_name, _authName, true); } } -void NetworkLock::clearAuthorizationInfo() +void NukiNetworkLock::clearAuthorizationInfo() { - publishString(mqtt_topic_lock_log, "--"); - publishUInt(mqtt_topic_lock_auth_id, 0); - publishString(mqtt_topic_lock_auth_name, "--");} - -void NetworkLock::publishCommandResult(const char *resultStr) -{ - publishString(mqtt_topic_lock_action_command_result, resultStr); + publishString(mqtt_topic_lock_log, "--", true); + publishUInt(mqtt_topic_lock_auth_id, 0, true); + publishString(mqtt_topic_lock_auth_name, "--", true); } -void NetworkLock::publishLockstateCommandResult(const char *resultStr) +void NukiNetworkLock::publishCommandResult(const char *resultStr) { - publishString(mqtt_topic_query_lockstate_command_result, resultStr); + publishString(mqtt_topic_lock_action_command_result, resultStr, true); } -void NetworkLock::publishBatteryReport(const NukiLock::BatteryReport& batteryReport) +void NukiNetworkLock::publishLockstateCommandResult(const char *resultStr) +{ + publishString(mqtt_topic_query_lockstate_command_result, resultStr, true); +} + +void NukiNetworkLock::publishBatteryReport(const NukiLock::BatteryReport& batteryReport) { if(!_preferences->getBool(preference_disable_non_json, false)) { - publishFloat(mqtt_topic_battery_voltage, (float)batteryReport.batteryVoltage / 1000.0); - publishInt(mqtt_topic_battery_drain, batteryReport.batteryDrain); // milliwatt seconds - publishFloat(mqtt_topic_battery_max_turn_current, (float)batteryReport.maxTurnCurrent / 1000.0); - publishInt(mqtt_topic_battery_lock_distance, batteryReport.lockDistance); // degrees + publishFloat(mqtt_topic_battery_voltage, (float)batteryReport.batteryVoltage / 1000.0, true); + publishInt(mqtt_topic_battery_drain, batteryReport.batteryDrain, true); // milliwatt seconds + publishFloat(mqtt_topic_battery_max_turn_current, (float)batteryReport.maxTurnCurrent / 1000.0, true); + publishInt(mqtt_topic_battery_lock_distance, batteryReport.lockDistance, true); // degrees } char str[50]; @@ -719,10 +739,10 @@ void NetworkLock::publishBatteryReport(const NukiLock::BatteryReport& batteryRep json["batteryResistance"] = (float)batteryReport.batteryResistance / 1000.0; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_battery_advanced_json, _buffer); + publishString(mqtt_topic_battery_advanced_json, _buffer, true); } -void NetworkLock::publishConfig(const NukiLock::Config &config) +void NukiNetworkLock::publishConfig(const NukiLock::Config &config) { char str[50]; char curTime[20]; @@ -773,21 +793,21 @@ void NetworkLock::publishConfig(const NukiLock::Config &config) json["timeZone"] = str; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_config_basic_json, _buffer); + publishString(mqtt_topic_config_basic_json, _buffer, true); if(!_preferences->getBool(preference_disable_non_json, false)) { - publishBool(mqtt_topic_config_button_enabled, config.buttonEnabled == 1); - publishBool(mqtt_topic_config_led_enabled, config.ledEnabled == 1); - publishInt(mqtt_topic_config_led_brightness, config.ledBrightness); - publishBool(mqtt_topic_config_single_lock, config.singleLock == 1); + publishBool(mqtt_topic_config_button_enabled, config.buttonEnabled == 1, true); + publishBool(mqtt_topic_config_led_enabled, config.ledEnabled == 1, true); + publishInt(mqtt_topic_config_led_brightness, config.ledBrightness, true); + publishBool(mqtt_topic_config_single_lock, config.singleLock == 1, true); } - publishString(mqtt_topic_info_firmware_version, std::to_string(config.firmwareVersion[0]) + "." + std::to_string(config.firmwareVersion[1]) + "." + std::to_string(config.firmwareVersion[2])); - publishString(mqtt_topic_info_hardware_version, std::to_string(config.hardwareRevision[0]) + "." + std::to_string(config.hardwareRevision[1])); + publishString(mqtt_topic_info_firmware_version, std::to_string(config.firmwareVersion[0]) + "." + std::to_string(config.firmwareVersion[1]) + "." + std::to_string(config.firmwareVersion[2]), true); + publishString(mqtt_topic_info_hardware_version, std::to_string(config.hardwareRevision[0]) + "." + std::to_string(config.hardwareRevision[1]), true); } -void NetworkLock::publishAdvancedConfig(const NukiLock::AdvancedConfig &config) +void NukiNetworkLock::publishAdvancedConfig(const NukiLock::AdvancedConfig &config) { char str[50]; char nmst[6]; @@ -828,31 +848,31 @@ void NetworkLock::publishAdvancedConfig(const NukiLock::AdvancedConfig &config) json["autoUpdateEnabled"] = config.autoUpdateEnabled; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_config_advanced_json, _buffer); + publishString(mqtt_topic_config_advanced_json, _buffer, true); if(!_preferences->getBool(preference_disable_non_json, false)) { - publishBool(mqtt_topic_config_auto_unlock, config.autoUnLockDisabled == 0); - publishBool(mqtt_topic_config_auto_lock, config.autoLockEnabled == 1); + publishBool(mqtt_topic_config_auto_unlock, config.autoUnLockDisabled == 0, true); + publishBool(mqtt_topic_config_auto_lock, config.autoLockEnabled == 1, true); } } -void NetworkLock::publishRssi(const int& rssi) +void NukiNetworkLock::publishRssi(const int& rssi) { - publishInt(mqtt_topic_lock_rssi, rssi); + publishInt(mqtt_topic_lock_rssi, rssi, true); } -void NetworkLock::publishRetry(const std::string& message) +void NukiNetworkLock::publishRetry(const std::string& message) { - publishString(mqtt_topic_lock_retry, message); + publishString(mqtt_topic_lock_retry, message, true); } -void NetworkLock::publishBleAddress(const std::string &address) +void NukiNetworkLock::publishBleAddress(const std::string &address) { - publishString(mqtt_topic_lock_address, address); + publishString(mqtt_topic_lock_address, address, true); } -void NetworkLock::publishKeypad(const std::list& entries, uint maxKeypadCodeCount) +void NukiNetworkLock::publishKeypad(const std::list& entries, uint maxKeypadCodeCount) { uint index = 0; char uidString[20]; @@ -956,7 +976,7 @@ void NetworkLock::publishKeypad(const std::list& entries, jsonEntry["name_ha"] = entry.name; jsonEntry["index"] = index; serializeJson(jsonEntry, _buffer, _bufferSize); - publishString(basePath.c_str(), _buffer); + publishString(basePath.c_str(), _buffer, true); String basePathPrefix = "~"; basePathPrefix.concat(basePath); @@ -997,7 +1017,7 @@ void NetworkLock::publishKeypad(const std::list& entries, } serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_keypad_json, _buffer); + publishString(mqtt_topic_keypad_json, _buffer, true); if(!_preferences->getBool(preference_disable_non_json, false)) { @@ -1047,7 +1067,7 @@ void NetworkLock::publishKeypad(const std::list& entries, _network->removeTopic(codeTopic, "createdSec"); _network->removeTopic(codeTopic, "lockCount"); } - + for(int j=entries.size(); j& entries, } } -void NetworkLock::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) +void NukiNetworkLock::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) { if(_preferences->getBool(preference_disable_non_json, false)) return; @@ -1070,25 +1090,25 @@ void NetworkLock::publishKeypadEntry(const String topic, NukiLock::KeypadEntry e memset(codeName, 0, sizeof(codeName)); memcpy(codeName, entry.name, sizeof(entry.name)); - publishInt(concat(topic, "/id").c_str(), entry.codeId); - publishBool(concat(topic, "/enabled").c_str(), entry.enabled); - publishString(concat(topic, "/name").c_str(), codeName); + publishInt(concat(topic, "/id").c_str(), entry.codeId, true); + publishBool(concat(topic, "/enabled").c_str(), entry.enabled, true); + publishString(concat(topic, "/name").c_str(), codeName, true); if(_preferences->getBool(preference_keypad_publish_code, false)) { - publishInt(concat(topic, "/code").c_str(), entry.code); + publishInt(concat(topic, "/code").c_str(), entry.code, true); } - publishInt(concat(topic, "/createdYear").c_str(), entry.dateCreatedYear); - publishInt(concat(topic, "/createdMonth").c_str(), entry.dateCreatedMonth); - publishInt(concat(topic, "/createdDay").c_str(), entry.dateCreatedDay); - publishInt(concat(topic, "/createdHour").c_str(), entry.dateCreatedHour); - publishInt(concat(topic, "/createdMin").c_str(), entry.dateCreatedMin); - publishInt(concat(topic, "/createdSec").c_str(), entry.dateCreatedSec); - publishInt(concat(topic, "/lockCount").c_str(), entry.lockCount); + publishInt(concat(topic, "/createdYear").c_str(), entry.dateCreatedYear, true); + publishInt(concat(topic, "/createdMonth").c_str(), entry.dateCreatedMonth, true); + publishInt(concat(topic, "/createdDay").c_str(), entry.dateCreatedDay, true); + publishInt(concat(topic, "/createdHour").c_str(), entry.dateCreatedHour, true); + publishInt(concat(topic, "/createdMin").c_str(), entry.dateCreatedMin, true); + publishInt(concat(topic, "/createdSec").c_str(), entry.dateCreatedSec, true); + publishInt(concat(topic, "/lockCount").c_str(), entry.lockCount, true); } -void NetworkLock::publishTimeControl(const std::list& timeControlEntries, uint maxTimeControlEntryCount) +void NukiNetworkLock::publishTimeControl(const std::list& timeControlEntries, uint maxTimeControlEntryCount) { uint index = 0; char str[50]; @@ -1166,7 +1186,7 @@ void NetworkLock::publishTimeControl(const std::list basePath.concat(std::to_string(index).c_str()); jsonEntry["index"] = index; serializeJson(jsonEntry, _buffer, _bufferSize); - publishString(basePath.c_str(), _buffer); + publishString(basePath.c_str(), _buffer, true); String basePathPrefix = "~"; basePathPrefix.concat(basePath); @@ -1199,13 +1219,13 @@ void NetworkLock::publishTimeControl(const std::list { (char*)"stat_on", (char*)"1" }, { (char*)"stat_off", (char*)"0" }}); } - + ++index; } serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_timecontrol_json, _buffer); - + publishString(mqtt_topic_timecontrol_json, _buffer, true); + for(int j=timeControlEntries.size(); j } } -void NetworkLock::publishConfigCommandResult(const char* result) +void NukiNetworkLock::publishConfigCommandResult(const char* result) { - publishString(mqtt_topic_config_action_command_result, result); + publishString(mqtt_topic_config_action_command_result, result, true); } -void NetworkLock::publishKeypadCommandResult(const char* result) +void NukiNetworkLock::publishKeypadCommandResult(const char* result) { if(_preferences->getBool(preference_disable_non_json, false)) return; - publishString(mqtt_topic_keypad_command_result, result); + publishString(mqtt_topic_keypad_command_result, result, true); } -void NetworkLock::publishKeypadJsonCommandResult(const char* result) +void NukiNetworkLock::publishKeypadJsonCommandResult(const char* result) { - publishString(mqtt_topic_keypad_json_command_result, result); + publishString(mqtt_topic_keypad_json_command_result, result, true); } -void NetworkLock::publishTimeControlCommandResult(const char* result) +void NukiNetworkLock::publishTimeControlCommandResult(const char* result) { - publishString(mqtt_topic_timecontrol_command_result, result); + publishString(mqtt_topic_timecontrol_command_result, result, true); } -void NetworkLock::publishStatusUpdated(const bool statusUpdated) +void NukiNetworkLock::publishStatusUpdated(const bool statusUpdated) { publishBool(mqtt_topic_lock_status_updated, statusUpdated); } -void NetworkLock::setLockActionReceivedCallback(LockActionResult (*lockActionReceivedCallback)(const char *)) +void NukiNetworkLock::setLockActionReceivedCallback(LockActionResult (*lockActionReceivedCallback)(const char *)) { _lockActionReceivedCallback = lockActionReceivedCallback; } -void NetworkLock::setOfficialUpdateReceivedCallback(void (*officialUpdateReceivedCallback)(const char *, const char *)) +void NukiNetworkLock::setOfficialUpdateReceivedCallback(void (*officialUpdateReceivedCallback)(const char *, const char *)) { _officialUpdateReceivedCallback = officialUpdateReceivedCallback; } -void NetworkLock::setConfigUpdateReceivedCallback(void (*configUpdateReceivedCallback)(const char *)) +void NukiNetworkLock::setConfigUpdateReceivedCallback(void (*configUpdateReceivedCallback)(const char *)) { _configUpdateReceivedCallback = configUpdateReceivedCallback; } -void NetworkLock::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) +void NukiNetworkLock::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) { if(_preferences->getBool(preference_disable_non_json, false)) return; _keypadCommandReceivedReceivedCallback = keypadCommandReceivedReceivedCallback; } -void NetworkLock::setKeypadJsonCommandReceivedCallback(void (*keypadJsonCommandReceivedReceivedCallback)(const char *)) +void NukiNetworkLock::setKeypadJsonCommandReceivedCallback(void (*keypadJsonCommandReceivedReceivedCallback)(const char *)) { _keypadJsonCommandReceivedReceivedCallback = keypadJsonCommandReceivedReceivedCallback; } -void NetworkLock::setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char *)) +void NukiNetworkLock::setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char *)) { _timeControlCommandReceivedReceivedCallback = timeControlCommandReceivedReceivedCallback; } -void NetworkLock::buildMqttPath(const char* path, char* outPath, bool offPath) +void NukiNetworkLock::buildMqttPath(const char* path, char* outPath, bool offPath) { int offset = 0; char inPath[181] = {0}; @@ -1301,14 +1321,14 @@ void NetworkLock::buildMqttPath(const char* path, char* outPath, bool offPath) outPath[i+1] = 0x00; } -bool NetworkLock::comparePrefixedPath(const char *fullPath, const char *subPath, bool offPath) +bool NukiNetworkLock::comparePrefixedPath(const char *fullPath, const char *subPath, bool offPath) { char prefixedPath[500]; buildMqttPath(subPath, prefixedPath, offPath); return strcmp(fullPath, prefixedPath) == 0; } -void NetworkLock::publishHASSConfig(char *deviceType, const char *baseTopic, char *name, char *uidString, const char *softwareVersion, const char *hardwareVersion, const bool& hasDoorSensor, const bool& hasKeypad, const bool& publishAuthData, char *lockAction, +void NukiNetworkLock::publishHASSConfig(char *deviceType, const char *baseTopic, char *name, char *uidString, const char *softwareVersion, const char *hardwareVersion, const bool& hasDoorSensor, const bool& hasKeypad, const bool& publishAuthData, char *lockAction, char *unlockAction, char *openAction) { _network->publishHASSConfig(deviceType, baseTopic, name, uidString, softwareVersion, hardwareVersion, "~/maintenance/mqttConnectionState", hasKeypad, lockAction, unlockAction, openAction); @@ -1345,37 +1365,37 @@ void NetworkLock::publishHASSConfig(char *deviceType, const char *baseTopic, cha } } -void NetworkLock::removeHASSConfig(char *uidString) +void NukiNetworkLock::removeHASSConfig(char *uidString) { _network->removeHASSConfig(uidString); } -void NetworkLock::publishOffAction(const int value) +void NukiNetworkLock::publishOffAction(const int value) { _network->publishInt(_offMqttPath, mqtt_topic_official_lock_action, value, false); } -void NetworkLock::publishFloat(const char *topic, const float value, const uint8_t precision, bool retain) +void NukiNetworkLock::publishFloat(const char *topic, const float value, const uint8_t precision, bool retain) { _network->publishFloat(_mqttPath, topic, value, precision, retain); } -void NetworkLock::publishInt(const char *topic, const int value, bool retain) +void NukiNetworkLock::publishInt(const char *topic, const int value, bool retain) { _network->publishInt(_mqttPath, topic, value, retain); } -void NetworkLock::publishUInt(const char *topic, const unsigned int value, bool retain) +void NukiNetworkLock::publishUInt(const char *topic, const unsigned int value, bool retain) { _network->publishUInt(_mqttPath, topic, value, retain); } -void NetworkLock::publishBool(const char *topic, const bool value, bool retain) +void NukiNetworkLock::publishBool(const char *topic, const bool value, bool retain) { _network->publishBool(_mqttPath, topic, value, retain); } -bool NetworkLock::publishString(const char *topic, const String &value, bool retain) +bool NukiNetworkLock::publishString(const char *topic, const String &value, bool retain) { char str[value.length() + 1]; memset(str, 0, sizeof(str)); @@ -1383,7 +1403,7 @@ bool NetworkLock::publishString(const char *topic, const String &value, bool ret return publishString(topic, str, retain); } -bool NetworkLock::publishString(const char *topic, const std::string &value, bool retain) +bool NukiNetworkLock::publishString(const char *topic, const std::string &value, bool retain) { char str[value.size() + 1]; memset(str, 0, sizeof(str)); @@ -1391,38 +1411,38 @@ bool NetworkLock::publishString(const char *topic, const std::string &value, boo return publishString(topic, str, retain); } -bool NetworkLock::publishString(const char *topic, const char *value, bool retain) +bool NukiNetworkLock::publishString(const char *topic, const char *value, bool retain) { return _network->publishString(_mqttPath, topic, value, retain); } -void NetworkLock::publishULong(const char *topic, const unsigned long value, bool retain) +void NukiNetworkLock::publishULong(const char *topic, const unsigned long value, bool retain) { return _network->publishULong(_mqttPath, topic, value, retain); } -String NetworkLock::concat(String a, String b) +String NukiNetworkLock::concat(String a, String b) { String c = a; c.concat(b); return c; } -bool NetworkLock::reconnected() +bool NukiNetworkLock::reconnected() { bool r = _reconnected; _reconnected = false; return r; } -uint8_t NetworkLock::queryCommands() +uint8_t NukiNetworkLock::queryCommands() { uint8_t qc = _queryCommands; _queryCommands = 0; return qc; } -void NetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str) { +void NukiNetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str) { switch (btnPressAction) { case NukiLock::ButtonPressAction::NoAction: strcpy(str, "No Action"); @@ -1451,7 +1471,7 @@ void NetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction bt } } -void NetworkLock::homeKitStatusToString(const int hkstatus, char* str) { +void NukiNetworkLock::homeKitStatusToString(const int hkstatus, char* str) { switch (hkstatus) { case 0: strcpy(str, "Not Available"); @@ -1471,7 +1491,7 @@ void NetworkLock::homeKitStatusToString(const int hkstatus, char* str) { } } -void NetworkLock::fobActionToString(const int fobact, char* str) { +void NukiNetworkLock::fobActionToString(const int fobact, char* str) { switch (fobact) { case 0: strcpy(str, "No Action"); diff --git a/src/NetworkLock.h b/src/NukiNetworkLock.h similarity index 96% rename from src/NetworkLock.h rename to src/NukiNetworkLock.h index bfe4c1a..0944094 100644 --- a/src/NetworkLock.h +++ b/src/NukiNetworkLock.h @@ -8,17 +8,17 @@ #include #include "NukiConstants.h" #include "NukiLockConstants.h" -#include "Network.h" +#include "NukiNetwork.h" #include "QueryCommand.h" #include "LockActionResult.h" #define LOCK_LOG_JSON_BUFFER_SIZE 2048 -class NetworkLock : public MqttReceiver +class NukiNetworkLock : public MqttReceiver { public: - explicit NetworkLock(Network* network, Preferences* preferences, char* buffer, size_t bufferSize); - virtual ~NetworkLock(); + explicit NukiNetworkLock(NukiNetwork* network, Preferences* preferences, char* buffer, size_t bufferSize); + virtual ~NukiNetworkLock(); void initialize(); @@ -99,7 +99,7 @@ private: void buildMqttPath(const char* path, char* outPath, bool offPath = false); - Network* _network; + NukiNetwork* _network; Preferences* _preferences; std::vector _offTopics; diff --git a/src/NetworkOpener.cpp b/src/NukiNetworkOpener.cpp similarity index 85% rename from src/NetworkOpener.cpp rename to src/NukiNetworkOpener.cpp index 08d5431..ffa0d1e 100644 --- a/src/NetworkOpener.cpp +++ b/src/NukiNetworkOpener.cpp @@ -1,4 +1,4 @@ -#include "NetworkOpener.h" +#include "NukiNetworkOpener.h" #include "Arduino.h" #include "MqttTopics.h" #include "PreferencesKeys.h" @@ -6,7 +6,7 @@ #include "Config.h" #include -NetworkOpener::NetworkOpener(Network* network, Preferences* preferences, char* buffer, size_t bufferSize) +NukiNetworkOpener::NukiNetworkOpener(NukiNetwork* network, Preferences* preferences, char* buffer, size_t bufferSize) : _preferences(preferences), _network(network), _buffer(buffer), @@ -18,7 +18,7 @@ NetworkOpener::NetworkOpener(Network* network, Preferences* preferences, char* b _network->registerMqttReceiver(this); } -void NetworkOpener::initialize() +void NukiNetworkOpener::initialize() { String mqttPath = _preferences->getString(preference_mqtt_opener_path); if(mqttPath.length() > 0) @@ -120,16 +120,16 @@ void NetworkOpener::initialize() }); } -void NetworkOpener::update() +void NukiNetworkOpener::update() { if(_resetRingStateTs != 0 && millis() >= _resetRingStateTs) { _resetRingStateTs = 0; - publishString(mqtt_topic_lock_binary_ring, "standby"); + publishString(mqtt_topic_lock_binary_ring, "standby", true); } } -void NetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) +void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) { char* value = (char*)payload; @@ -192,12 +192,12 @@ void NetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const u if(strcmp(value, "--") != 0) { - publishString(mqtt_topic_keypad_command_action, "--"); + publishString(mqtt_topic_keypad_command_action, "--", true); } - publishInt(mqtt_topic_keypad_command_id, _keypadCommandId); - publishString(mqtt_topic_keypad_command_name, _keypadCommandName); - publishString(mqtt_topic_keypad_command_code, _keypadCommandCode); - publishInt(mqtt_topic_keypad_command_enabled, _keypadCommandEnabled); + publishInt(mqtt_topic_keypad_command_id, _keypadCommandId, true); + publishString(mqtt_topic_keypad_command_name, _keypadCommandName, true); + publishString(mqtt_topic_keypad_command_code, _keypadCommandCode, true); + publishInt(mqtt_topic_keypad_command_enabled, _keypadCommandEnabled, true); } } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_id)) @@ -221,22 +221,22 @@ void NetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const u if(comparePrefixedPath(topic, mqtt_topic_query_config) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_CONFIG; - publishString(mqtt_topic_query_config, "0"); + publishString(mqtt_topic_query_config, "0", true); } else if(comparePrefixedPath(topic, mqtt_topic_query_lockstate) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_LOCKSTATE; - publishString(mqtt_topic_query_lockstate, "0"); + publishString(mqtt_topic_query_lockstate, "0", true); } else if(comparePrefixedPath(topic, mqtt_topic_query_keypad) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_KEYPAD; - publishString(mqtt_topic_query_keypad, "0"); + publishString(mqtt_topic_query_keypad, "0", true); } else if(comparePrefixedPath(topic, mqtt_topic_query_battery) && strcmp(value, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_BATTERY; - publishString(mqtt_topic_query_battery, "0"); + publishString(mqtt_topic_query_battery, "0", true); } if(comparePrefixedPath(topic, mqtt_topic_config_action)) @@ -248,7 +248,7 @@ void NetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const u _configUpdateReceivedCallback(value); } - publishString(mqtt_topic_config_action, "--"); + publishString(mqtt_topic_config_action, "--", true); } if(comparePrefixedPath(topic, mqtt_topic_keypad_json_action)) @@ -260,7 +260,7 @@ void NetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const u _keypadJsonCommandReceivedReceivedCallback(value); } - publishString(mqtt_topic_keypad_json_action, "--"); + publishString(mqtt_topic_keypad_json_action, "--", true); } if(comparePrefixedPath(topic, mqtt_topic_timecontrol_action)) @@ -272,11 +272,11 @@ void NetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const u _timeControlCommandReceivedReceivedCallback(value); } - publishString(mqtt_topic_timecontrol_action, "--"); + publishString(mqtt_topic_timecontrol_action, "--", true); } } -void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurnerState, const NukiOpener::OpenerState& lastKeyTurnerState) +void NukiNetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurnerState, const NukiOpener::OpenerState& lastKeyTurnerState) { _currentLockState = keyTurnerState.lockState; @@ -290,7 +290,7 @@ void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurn if((_firstTunerStatePublish || keyTurnerState.lockState != lastKeyTurnerState.lockState || keyTurnerState.nukiState != lastKeyTurnerState.nukiState) && keyTurnerState.lockState != NukiOpener::LockState::Undefined) { - publishString(mqtt_topic_lock_state, str); + publishString(mqtt_topic_lock_state, str, true); if(_haEnabled) { @@ -314,7 +314,7 @@ void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurn if(_firstTunerStatePublish || keyTurnerState.trigger != lastKeyTurnerState.trigger) { - publishString(mqtt_topic_lock_trigger, str); + publishString(mqtt_topic_lock_trigger, str, true); } json["trigger"] = str; @@ -329,7 +329,7 @@ void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurn if(_firstTunerStatePublish || keyTurnerState.lastLockAction != lastKeyTurnerState.lastLockAction) { - publishString(mqtt_topic_lock_last_lock_action, str); + publishString(mqtt_topic_lock_last_lock_action, str, true); } json["last_lock_action"] = str; @@ -343,7 +343,7 @@ void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurn if(_firstTunerStatePublish || keyTurnerState.lastLockActionCompletionStatus != lastKeyTurnerState.lastLockActionCompletionStatus) { - publishString(mqtt_topic_lock_completionStatus, str); + publishString(mqtt_topic_lock_completionStatus, str, true); } json["lock_completion_status"] = str; @@ -353,7 +353,7 @@ void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurn if(_firstTunerStatePublish || keyTurnerState.doorSensorState != lastKeyTurnerState.doorSensorState) { - publishString(mqtt_topic_lock_door_sensor_state, str); + publishString(mqtt_topic_lock_door_sensor_state, str, true); } json["door_sensor_state"] = str; @@ -363,66 +363,66 @@ void NetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& keyTurn if((_firstTunerStatePublish || keyTurnerState.criticalBatteryState != lastKeyTurnerState.criticalBatteryState) && !_preferences->getBool(preference_disable_non_json, false)) { - publishBool(mqtt_topic_battery_critical, critical); + publishBool(mqtt_topic_battery_critical, critical, true); } json["auth_id"] = _authId; json["auth_name"] = _authName; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_lock_json, _buffer); + publishString(mqtt_topic_lock_json, _buffer, true); serializeJson(jsonBattery, _buffer, _bufferSize); - publishString(mqtt_topic_battery_basic_json, _buffer); + publishString(mqtt_topic_battery_basic_json, _buffer, true); _firstTunerStatePublish = false; } -void NetworkOpener::publishRing(const bool locked) +void NukiNetworkOpener::publishRing(const bool locked) { if(locked) { - publishString(mqtt_topic_lock_ring, "ringlocked"); + publishString(mqtt_topic_lock_ring, "ringlocked", true); } else { - publishString(mqtt_topic_lock_ring, "ring"); + publishString(mqtt_topic_lock_ring, "ring", true); } - publishString(mqtt_topic_lock_binary_ring, "ring"); + publishString(mqtt_topic_lock_binary_ring, "ring", true); _resetRingStateTs = millis() + 2000; } -void NetworkOpener::publishState(NukiOpener::OpenerState lockState) +void NukiNetworkOpener::publishState(NukiOpener::OpenerState lockState) { if(lockState.nukiState == NukiOpener::State::ContinuousMode) { - publishString(mqtt_topic_lock_ha_state, "unlocked"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "unlocked", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); } else { switch (lockState.lockState) { case NukiOpener::LockState::Locked: - publishString(mqtt_topic_lock_ha_state, "locked"); - publishString(mqtt_topic_lock_binary_state, "locked"); + publishString(mqtt_topic_lock_ha_state, "locked", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); break; case NukiOpener::LockState::RTOactive: - publishString(mqtt_topic_lock_ha_state, "unlocked"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "unlocked", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiOpener::LockState::Open: - publishString(mqtt_topic_lock_ha_state, "open"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "open", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiOpener::LockState::Opening: - publishString(mqtt_topic_lock_ha_state, "opening"); - publishString(mqtt_topic_lock_binary_state, "unlocked"); + publishString(mqtt_topic_lock_ha_state, "opening", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); break; case NukiOpener::LockState::Undefined: case NukiOpener::LockState::Uncalibrated: - publishString(mqtt_topic_lock_ha_state, "jammed"); + publishString(mqtt_topic_lock_ha_state, "jammed", true); break; default: break; @@ -430,7 +430,7 @@ void NetworkOpener::publishState(NukiOpener::OpenerState lockState) } } -void NetworkOpener::publishAuthorizationInfo(const std::list& logEntries, bool latest) +void NukiNetworkOpener::publishAuthorizationInfo(const std::list& logEntries, bool latest) { char str[50]; char authName[33]; @@ -581,45 +581,45 @@ void NetworkOpener::publishAuthorizationInfo(const std::list 0) { - publishUInt(mqtt_topic_lock_auth_id, _authId); - publishString(mqtt_topic_lock_auth_name, _authName); + publishUInt(mqtt_topic_lock_auth_id, _authId, true); + publishString(mqtt_topic_lock_auth_name, _authName, true); } } -void NetworkOpener::clearAuthorizationInfo() +void NukiNetworkOpener::clearAuthorizationInfo() { - publishString(mqtt_topic_lock_log, "--"); - publishUInt(mqtt_topic_lock_auth_id, 0); - publishString(mqtt_topic_lock_auth_name, "--"); + publishString(mqtt_topic_lock_log, "--", true); + publishUInt(mqtt_topic_lock_auth_id, 0, true); + publishString(mqtt_topic_lock_auth_name, "--", true); } -void NetworkOpener::publishCommandResult(const char *resultStr) +void NukiNetworkOpener::publishCommandResult(const char *resultStr) { - publishString(mqtt_topic_lock_action_command_result, resultStr); + publishString(mqtt_topic_lock_action_command_result, resultStr, true); } -void NetworkOpener::publishLockstateCommandResult(const char *resultStr) +void NukiNetworkOpener::publishLockstateCommandResult(const char *resultStr) { - publishString(mqtt_topic_query_lockstate_command_result, resultStr); + publishString(mqtt_topic_query_lockstate_command_result, resultStr, true); } -void NetworkOpener::publishBatteryReport(const NukiOpener::BatteryReport& batteryReport) +void NukiNetworkOpener::publishBatteryReport(const NukiOpener::BatteryReport& batteryReport) { if(!_preferences->getBool(preference_disable_non_json, false)) { - publishFloat(mqtt_topic_battery_voltage, (float)batteryReport.batteryVoltage / 1000.0); + publishFloat(mqtt_topic_battery_voltage, (float)batteryReport.batteryVoltage / 1000.0, true); } char str[50]; @@ -635,10 +635,10 @@ void NetworkOpener::publishBatteryReport(const NukiOpener::BatteryReport& batter json["lowestVoltage"] = (float)batteryReport.lowestVoltage / 1000.0; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_battery_advanced_json, _buffer); + publishString(mqtt_topic_battery_advanced_json, _buffer, true); } -void NetworkOpener::publishConfig(const NukiOpener::Config &config) +void NukiNetworkOpener::publishConfig(const NukiOpener::Config &config) { char str[50]; char curTime[20]; @@ -689,19 +689,19 @@ void NetworkOpener::publishConfig(const NukiOpener::Config &config) json["timeZone"] = str; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_config_basic_json, _buffer); + publishString(mqtt_topic_config_basic_json, _buffer, true); if(!_preferences->getBool(preference_disable_non_json, false)) { - publishBool(mqtt_topic_config_button_enabled, config.buttonEnabled == 1); - publishBool(mqtt_topic_config_led_enabled, config.ledFlashEnabled == 1); + publishBool(mqtt_topic_config_button_enabled, config.buttonEnabled == 1, true); + publishBool(mqtt_topic_config_led_enabled, config.ledFlashEnabled == 1, true); } - publishString(mqtt_topic_info_firmware_version, std::to_string(config.firmwareVersion[0]) + "." + std::to_string(config.firmwareVersion[1]) + "." + std::to_string(config.firmwareVersion[2])); - publishString(mqtt_topic_info_hardware_version, std::to_string(config.hardwareRevision[0]) + "." + std::to_string(config.hardwareRevision[1])); + publishString(mqtt_topic_info_firmware_version, std::to_string(config.firmwareVersion[0]) + "." + std::to_string(config.firmwareVersion[1]) + "." + std::to_string(config.firmwareVersion[2]), true); + publishString(mqtt_topic_info_hardware_version, std::to_string(config.hardwareRevision[0]) + "." + std::to_string(config.hardwareRevision[1]), true); } -void NetworkOpener::publishAdvancedConfig(const NukiOpener::AdvancedConfig &config) +void NukiNetworkOpener::publishAdvancedConfig(const NukiOpener::AdvancedConfig &config) { char str[50]; @@ -745,30 +745,30 @@ void NetworkOpener::publishAdvancedConfig(const NukiOpener::AdvancedConfig &conf json["automaticBatteryTypeDetection"] = config.automaticBatteryTypeDetection; serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_config_advanced_json, _buffer); + publishString(mqtt_topic_config_advanced_json, _buffer, true); if(!_preferences->getBool(preference_disable_non_json, false)) { - publishUInt(mqtt_topic_config_sound_level, config.soundLevel); + publishUInt(mqtt_topic_config_sound_level, config.soundLevel, true); } } -void NetworkOpener::publishRssi(const int &rssi) +void NukiNetworkOpener::publishRssi(const int &rssi) { - publishInt(mqtt_topic_lock_rssi, rssi); + publishInt(mqtt_topic_lock_rssi, rssi, true); } -void NetworkOpener::publishRetry(const std::string& message) +void NukiNetworkOpener::publishRetry(const std::string& message) { - publishString(mqtt_topic_lock_retry, message); + publishString(mqtt_topic_lock_retry, message, true); } -void NetworkOpener::publishBleAddress(const std::string &address) +void NukiNetworkOpener::publishBleAddress(const std::string &address) { - publishString(mqtt_topic_lock_address, address); + publishString(mqtt_topic_lock_address, address, true); } -void NetworkOpener::publishHASSConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const bool& publishAuthData, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction) +void NukiNetworkOpener::publishHASSConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const bool& publishAuthData, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction) { String availabilityTopic = _preferences->getString("mqttpath"); availabilityTopic.concat("/maintenance/mqttConnectionState"); @@ -795,12 +795,12 @@ void NetworkOpener::publishHASSConfig(char* deviceType, const char* baseTopic, c } } -void NetworkOpener::removeHASSConfig(char* uidString) +void NukiNetworkOpener::removeHASSConfig(char* uidString) { _network->removeHASSConfig(uidString); } -void NetworkOpener::publishKeypad(const std::list& entries, uint maxKeypadCodeCount) +void NukiNetworkOpener::publishKeypad(const std::list& entries, uint maxKeypadCodeCount) { uint index = 0; char uidString[20]; @@ -904,7 +904,7 @@ void NetworkOpener::publishKeypad(const std::list& entrie jsonEntry["name_ha"] = entry.name; jsonEntry["index"] = index; serializeJson(jsonEntry, _buffer, _bufferSize); - publishString(basePath.c_str(), _buffer); + publishString(basePath.c_str(), _buffer, true); String basePathPrefix = "~"; basePathPrefix.concat(basePath); @@ -945,7 +945,7 @@ void NetworkOpener::publishKeypad(const std::list& entrie } serializeJson(json, _buffer, _bufferSize); - publishString(mqtt_topic_keypad_json, _buffer); + publishString(mqtt_topic_keypad_json, _buffer, true); if(!_preferences->getBool(preference_disable_non_json, false)) { @@ -1008,7 +1008,7 @@ void NetworkOpener::publishKeypad(const std::list& entrie } } -void NetworkOpener::publishTimeControl(const std::list& timeControlEntries, uint maxTimeControlEntryCount) +void NukiNetworkOpener::publishTimeControl(const std::list& timeControlEntries, uint maxTimeControlEntryCount) { uint index = 0; char str[50]; @@ -1086,7 +1086,7 @@ void NetworkOpener::publishTimeControl(const std::listgetBool(preference_disable_non_json, false)) return; - publishString(mqtt_topic_keypad_command_result, result); + publishString(mqtt_topic_keypad_command_result, result, true); } -void NetworkOpener::publishKeypadJsonCommandResult(const char* result) +void NukiNetworkOpener::publishKeypadJsonCommandResult(const char* result) { - publishString(mqtt_topic_keypad_json_command_result, result); + publishString(mqtt_topic_keypad_json_command_result, result, true); } -void NetworkOpener::publishTimeControlCommandResult(const char* result) +void NukiNetworkOpener::publishTimeControlCommandResult(const char* result) { - publishString(mqtt_topic_timecontrol_command_result, result); + publishString(mqtt_topic_timecontrol_command_result, result, true); } -void NetworkOpener::publishStatusUpdated(const bool statusUpdated) +void NukiNetworkOpener::publishStatusUpdated(const bool statusUpdated) { publishBool(mqtt_topic_lock_status_updated, statusUpdated); } -void NetworkOpener::setLockActionReceivedCallback(LockActionResult (*lockActionReceivedCallback)(const char *)) +void NukiNetworkOpener::setLockActionReceivedCallback(LockActionResult (*lockActionReceivedCallback)(const char *)) { _lockActionReceivedCallback = lockActionReceivedCallback; } -void NetworkOpener::setConfigUpdateReceivedCallback(void (*configUpdateReceivedCallback)(const char *)) +void NukiNetworkOpener::setConfigUpdateReceivedCallback(void (*configUpdateReceivedCallback)(const char *)) { _configUpdateReceivedCallback = configUpdateReceivedCallback; } -void NetworkOpener::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) +void NukiNetworkOpener::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) { if(_preferences->getBool(preference_disable_non_json, false)) return; _keypadCommandReceivedReceivedCallback = keypadCommandReceivedReceivedCallback; } -void NetworkOpener::setKeypadJsonCommandReceivedCallback(void (*keypadJsonCommandReceivedReceivedCallback)(const char *)) +void NukiNetworkOpener::setKeypadJsonCommandReceivedCallback(void (*keypadJsonCommandReceivedReceivedCallback)(const char *)) { _keypadJsonCommandReceivedReceivedCallback = keypadJsonCommandReceivedReceivedCallback; } -void NetworkOpener::setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char *)) +void NukiNetworkOpener::setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char *)) { _timeControlCommandReceivedReceivedCallback = timeControlCommandReceivedReceivedCallback; } -void NetworkOpener::publishFloat(const char *topic, const float value, const uint8_t precision, bool retain) +void NukiNetworkOpener::publishFloat(const char *topic, const float value, const uint8_t precision, bool retain) { _network->publishFloat(_mqttPath, topic, value, precision, retain); } -void NetworkOpener::publishInt(const char *topic, const int value, bool retain) +void NukiNetworkOpener::publishInt(const char *topic, const int value, bool retain) { _network->publishInt(_mqttPath, topic, value, retain); } -void NetworkOpener::publishUInt(const char *topic, const unsigned int value, bool retain) +void NukiNetworkOpener::publishUInt(const char *topic, const unsigned int value, bool retain) { _network->publishUInt(_mqttPath, topic, value, retain); } -void NetworkOpener::publishBool(const char *topic, const bool value, bool retain) +void NukiNetworkOpener::publishBool(const char *topic, const bool value, bool retain) { _network->publishBool(_mqttPath, topic, value, retain); } -void NetworkOpener::publishString(const char *topic, const String &value, bool retain) +void NukiNetworkOpener::publishString(const char *topic, const String &value, bool retain) { char str[value.length() + 1]; memset(str, 0, sizeof(str)); @@ -1216,7 +1216,7 @@ void NetworkOpener::publishString(const char *topic, const String &value, bool r publishString(topic, str, retain); } -void NetworkOpener::publishString(const char *topic, const std::string &value, bool retain) +void NukiNetworkOpener::publishString(const char *topic, const std::string &value, bool retain) { char str[value.size() + 1]; memset(str, 0, sizeof(str)); @@ -1224,12 +1224,12 @@ void NetworkOpener::publishString(const char *topic, const std::string &value, b publishString(topic, str, retain); } -void NetworkOpener::publishString(const char* topic, const char* value, bool retain) +void NukiNetworkOpener::publishString(const char* topic, const char* value, bool retain) { _network->publishString(_mqttPath, topic, value, retain); } -void NetworkOpener::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) +void NukiNetworkOpener::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) { if(_preferences->getBool(preference_disable_non_json, false)) return; @@ -1237,25 +1237,25 @@ void NetworkOpener::publishKeypadEntry(const String topic, NukiLock::KeypadEntry memset(codeName, 0, sizeof(codeName)); memcpy(codeName, entry.name, sizeof(entry.name)); - publishInt(concat(topic, "/id").c_str(), entry.codeId); - publishBool(concat(topic, "/enabled").c_str(), entry.enabled); - publishString(concat(topic, "/name").c_str(), codeName); + publishInt(concat(topic, "/id").c_str(), entry.codeId, true); + publishBool(concat(topic, "/enabled").c_str(), entry.enabled, true); + publishString(concat(topic, "/name").c_str(), codeName, true); if(_preferences->getBool(preference_keypad_publish_code, false)) { - publishInt(concat(topic, "/code").c_str(), entry.code); + publishInt(concat(topic, "/code").c_str(), entry.code, true); } - publishInt(concat(topic, "/createdYear").c_str(), entry.dateCreatedYear); - publishInt(concat(topic, "/createdMonth").c_str(), entry.dateCreatedMonth); - publishInt(concat(topic, "/createdDay").c_str(), entry.dateCreatedDay); - publishInt(concat(topic, "/createdHour").c_str(), entry.dateCreatedHour); - publishInt(concat(topic, "/createdMin").c_str(), entry.dateCreatedMin); - publishInt(concat(topic, "/createdSec").c_str(), entry.dateCreatedSec); - publishInt(concat(topic, "/lockCount").c_str(), entry.lockCount); + publishInt(concat(topic, "/createdYear").c_str(), entry.dateCreatedYear, true); + publishInt(concat(topic, "/createdMonth").c_str(), entry.dateCreatedMonth, true); + publishInt(concat(topic, "/createdDay").c_str(), entry.dateCreatedDay, true); + publishInt(concat(topic, "/createdHour").c_str(), entry.dateCreatedHour, true); + publishInt(concat(topic, "/createdMin").c_str(), entry.dateCreatedMin, true); + publishInt(concat(topic, "/createdSec").c_str(), entry.dateCreatedSec, true); + publishInt(concat(topic, "/lockCount").c_str(), entry.lockCount, true); } -void NetworkOpener::buildMqttPath(const char* path, char* outPath) +void NukiNetworkOpener::buildMqttPath(const char* path, char* outPath) { int offset = 0; for(const char& c : _mqttPath) @@ -1277,14 +1277,14 @@ void NetworkOpener::buildMqttPath(const char* path, char* outPath) outPath[offset] = 0x00; } -void NetworkOpener::subscribe(const char *path) +void NukiNetworkOpener::subscribe(const char *path) { char prefixedPath[500]; buildMqttPath(path, prefixedPath); _network->subscribe(prefixedPath, MQTT_QOS_LEVEL); } -bool NetworkOpener::comparePrefixedPath(const char *fullPath, const char *subPath) +bool NukiNetworkOpener::comparePrefixedPath(const char *fullPath, const char *subPath) { char prefixedPath[500]; buildMqttPath(subPath, prefixedPath); @@ -1292,28 +1292,28 @@ bool NetworkOpener::comparePrefixedPath(const char *fullPath, const char *subPat return strcmp(fullPath, prefixedPath) == 0; } -String NetworkOpener::concat(String a, String b) +String NukiNetworkOpener::concat(String a, String b) { String c = a; c.concat(b); return c; } -bool NetworkOpener::reconnected() +bool NukiNetworkOpener::reconnected() { bool r = _reconnected; _reconnected = false; return r; } -uint8_t NetworkOpener::queryCommands() +uint8_t NukiNetworkOpener::queryCommands() { uint8_t qc = _queryCommands; _queryCommands = 0; return qc; } -void NetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str) { +void NukiNetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str) { switch (btnPressAction) { case NukiOpener::ButtonPressAction::NoAction: strcpy(str, "No Action"); @@ -1345,7 +1345,7 @@ void NetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressActio } } -void NetworkOpener::fobActionToString(const int fobact, char* str) { +void NukiNetworkOpener::fobActionToString(const int fobact, char* str) { switch (fobact) { case 0: strcpy(str, "No Action"); @@ -1371,7 +1371,7 @@ void NetworkOpener::fobActionToString(const int fobact, char* str) { } } -void NetworkOpener::capabilitiesToString(const int capabilities, char* str) { +void NukiNetworkOpener::capabilitiesToString(const int capabilities, char* str) { switch (capabilities) { case 0: strcpy(str, "Door opener"); @@ -1388,7 +1388,7 @@ void NetworkOpener::capabilitiesToString(const int capabilities, char* str) { } } -void NetworkOpener::operatingModeToString(const int opmode, char* str) { +void NukiNetworkOpener::operatingModeToString(const int opmode, char* str) { switch (opmode) { case 0: strcpy(str, "Generic door opener"); @@ -1444,7 +1444,7 @@ void NetworkOpener::operatingModeToString(const int opmode, char* str) { } } -void NetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) { +void NukiNetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) { switch (dbsupr) { case 0: strcpy(str, "Off"); @@ -1476,7 +1476,7 @@ void NetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) { } } -void NetworkOpener::soundToString(const int sound, char* str) { +void NukiNetworkOpener::soundToString(const int sound, char* str) { switch (sound) { case 0: strcpy(str, "No Sound"); diff --git a/src/NetworkOpener.h b/src/NukiNetworkOpener.h similarity index 95% rename from src/NetworkOpener.h rename to src/NukiNetworkOpener.h index 161c6f6..1c13ed3 100644 --- a/src/NetworkOpener.h +++ b/src/NukiNetworkOpener.h @@ -7,13 +7,13 @@ #include #include "NukiConstants.h" #include "NukiOpenerConstants.h" -#include "NetworkLock.h" +#include "NukiNetworkLock.h" -class NetworkOpener : public MqttReceiver +class NukiNetworkOpener : public MqttReceiver { public: - explicit NetworkOpener(Network* network, Preferences* preferences, char* buffer, size_t bufferSize); - virtual ~NetworkOpener() = default; + explicit NukiNetworkOpener(NukiNetwork* network, Preferences* preferences, char* buffer, size_t bufferSize); + virtual ~NukiNetworkOpener() = default; void initialize(); void update(); @@ -77,7 +77,7 @@ private: Preferences* _preferences; - Network* _network = nullptr; + NukiNetwork* _network = nullptr; char _mqttPath[181] = {0}; bool _isConnected = false; diff --git a/src/NukiOpenerWrapper.cpp b/src/NukiOpenerWrapper.cpp index 22f047b..de688fc 100644 --- a/src/NukiOpenerWrapper.cpp +++ b/src/NukiOpenerWrapper.cpp @@ -10,7 +10,7 @@ NukiOpenerWrapper* nukiOpenerInst; Preferences* nukiOpenerPreferences = nullptr; -NukiOpenerWrapper::NukiOpenerWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NetworkOpener* network, Gpio* gpio, Preferences* preferences) +NukiOpenerWrapper::NukiOpenerWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkOpener* network, Gpio* gpio, Preferences* preferences) : _deviceName(deviceName), _deviceId(deviceId), _nukiOpener(deviceName, _deviceId->get()), @@ -103,6 +103,7 @@ void NukiOpenerWrapper::initialize() } _nukiOpener.setEventHandler(this); + _nukiOpener.setDisonnectTimeout(5000); Log->print(F("Lock state interval: ")); Log->print(_intervalLockstate); @@ -220,17 +221,8 @@ void NukiOpenerWrapper::update() if(_nextLockAction != (NukiOpener::LockAction)0xff && ts > _nextRetryTs) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; Nuki::CmdResult cmdResult = _nukiOpener.lockAction(_nextLockAction, 0, 0); - _taskRunning = false; + delay(250); char resultStr[15] = {0}; NukiOpener::cmdResultToString(cmdResult, resultStr); @@ -350,28 +342,18 @@ void NukiOpenerWrapper::unpair() void NukiOpenerWrapper::updateKeyTurnerState() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Querying opener state: ")); result =_nukiOpener.requestOpenerState(&_keyTurnerState); - _taskRunning = false; - if(!_nukiConfigValid) { + delay(250); + if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } char resultStr[15]; @@ -383,7 +365,7 @@ void NukiOpenerWrapper::updateKeyTurnerState() { _retryLockstateCount++; postponeBleWatchdog(); - if(_retryLockstateCount < _nrOfRetries) + if(_retryLockstateCount < _nrOfRetries + 1) { _nextLockStateUpdateTs = millis() + _retryDelay; } @@ -435,28 +417,18 @@ void NukiOpenerWrapper::updateKeyTurnerState() void NukiOpenerWrapper::updateBatteryState() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Querying opener battery state: ")); result = _nukiOpener.requestBatteryReport(&_batteryReport); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } printCommandResult(result); @@ -495,27 +467,17 @@ void NukiOpenerWrapper::updateConfig() const int pinStatus = _preferences->getInt(preference_opener_pin_status, 4); if(isPinSet()) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; result = _nukiOpener.verifySecurityPin(); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if(result != Nuki::CmdResult::Success) @@ -577,28 +539,18 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) if(!retrieved) { delay(250); - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Retrieve log entries: ")); result = _nukiOpener.retrieveLogEntries(0, _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 1, false); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } Log->println(result); @@ -654,28 +606,18 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) if(!retrieved) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Querying opener keypad: ")); result = _nukiOpener.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } printCommandResult(result); @@ -725,28 +667,18 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) if(!retrieved) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Querying opener time control: ")); result = _nukiOpener.retrieveTimeControlEntries(); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } printCommandResult(result); @@ -1045,14 +977,6 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(basicKeys[i], "name") == 0) { if(strlen(jsonchar) <= 32) @@ -1210,8 +1134,6 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if(cmdResult == Nuki::CmdResult::Success) basicUpdated = true; @@ -1245,14 +1167,6 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(advancedKeys[j], "intercomID") == 0) { const uint16_t keyvalue = atoi(jsonchar); @@ -1478,8 +1392,6 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if(cmdResult == Nuki::CmdResult::Success) advancedUpdated = true; @@ -1573,14 +1485,6 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(command, "add") == 0) { if(name == "" || name == "--") @@ -1604,10 +1508,10 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint size_t nameLen = name.length(); memcpy(&entry.name, name.c_str(), nameLen > 20 ? 20 : nameLen); entry.code = codeInt; - _taskRunning = true; result = _nukiOpener.addKeypadEntry(entry); - _taskRunning = false; - Log->print("Add keypad code: "); Log->println((int)result); + delay(250); + Log->print("Add keypad code: "); + Log->println((int)result); updateKeypad(false); } else if(strcmp(command, "delete") == 0) @@ -1618,10 +1522,10 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint return; } - _taskRunning = true; result = _nukiOpener.deleteKeypadEntry(id); - _taskRunning = false; - Log->print("Delete keypad code: "); Log->println((int)result); + delay(250); + Log->print("Delete keypad code: "); + Log->println((int)result); updateKeypad(false); } else if(strcmp(command, "update") == 0) @@ -1654,13 +1558,13 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint memcpy(&entry.name, name.c_str(), nameLen > 20 ? 20 : nameLen); entry.code = codeInt; entry.enabled = enabled == 0 ? 0 : 1; - _taskRunning = true; result = _nukiOpener.updateKeypadEntry(entry); - _taskRunning = false; - Log->print("Update keypad code: "); Log->println((int)result); + delay(250); + Log->print("Update keypad code: "); + Log->println((int)result); updateKeypad(false); } - else if(command == "--") + else if(strcmp(command, "--") == 0) { return; } @@ -1674,8 +1578,6 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if((int)result != -1) @@ -1771,20 +1673,11 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(action, "delete") == 0) { if(idExists) { - _taskRunning = true; result = _nukiOpener.deleteKeypadEntry(codeId); - _taskRunning = false; + delay(250); Log->print(F("Delete keypad code: ")); Log->println((int)result); } @@ -1970,9 +1863,8 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) entry.allowedUntilTimeMin = allowedUntilTimeAr[1]; } - _taskRunning = true; result = _nukiOpener.addKeypadEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Add keypad code: ")); Log->println((int)result); } @@ -1990,17 +1882,8 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) return; } - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; Nuki::CmdResult resultKp = _nukiOpener.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - _taskRunning = false; + delay(250); bool foundExisting = false; if(resultKp == Nuki::CmdResult::Success) @@ -2075,7 +1958,7 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) entry.codeId = codeId; entry.code = code; - if(name.length() < 1) + if(!name.length() > 0) { size_t nameLen = strlen(oldName); memcpy(&entry.name, oldName, nameLen > 20 ? 20 : nameLen); @@ -2128,9 +2011,8 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) } } - _taskRunning = true; result = _nukiOpener.updateKeypadEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Update keypad code: ")); Log->println((int)result); } @@ -2145,8 +2027,6 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } updateKeypad(false); @@ -2235,20 +2115,11 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(action, "delete") == 0) { if(idExists) { - _taskRunning = true; result = _nukiOpener.removeTimeControlEntry(entryId); - _taskRunning = false; + delay(250); Log->print(F("Delete time control: ")); Log->println((int)result); } @@ -2306,10 +2177,8 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) } entry.lockAction = timeControlLockAction; - - _taskRunning = true; result = _nukiOpener.addTimeControlEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Add time control: ")); Log->println((int)result); } @@ -2321,17 +2190,8 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) return; } - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; Nuki::CmdResult resultTc = _nukiOpener.retrieveTimeControlEntries(); - _taskRunning = false; + delay(250); bool foundExisting = false; if(resultTc == Nuki::CmdResult::Success) @@ -2380,10 +2240,8 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) } entry.lockAction = timeControlLockAction; - - _taskRunning = true; result = _nukiOpener.updateTimeControlEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Update time control: ")); Log->println((int)result); } @@ -2398,8 +2256,6 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if((int)result != -1) @@ -2448,6 +2304,7 @@ void NukiOpenerWrapper::notify(Nuki::EventType eventType) { if(eventType == Nuki::EventType::KeyTurnerStatusUpdated) { + Log->println("KeyTurnerStatusUpdated"); _statusUpdated = true; _network->publishStatusUpdated(_statusUpdated); } @@ -2455,30 +2312,19 @@ void NukiOpenerWrapper::notify(Nuki::EventType eventType) void NukiOpenerWrapper::readConfig() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; - Log->print(F("Reading opener config. Result: ")); Nuki::CmdResult result = _nukiOpener.requestConfig(&_nukiConfig); - _taskRunning = false; + delay(250); _nukiConfigValid = result == Nuki::CmdResult::Success; if(!_nukiConfigValid) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } char resultStr[20]; @@ -2489,29 +2335,19 @@ void NukiOpenerWrapper::readConfig() void NukiOpenerWrapper::readAdvancedConfig() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; result = _nukiOpener.requestAdvancedConfig(&_nukiAdvancedConfig); - _taskRunning = false; + delay(250); _nukiAdvancedConfigValid = result == Nuki::CmdResult::Success; if(!_nukiAdvancedConfigValid) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } char resultStr[20]; @@ -2541,29 +2377,19 @@ void NukiOpenerWrapper::disableHASS() { if(!_nukiConfigValid) // only ask for config once to save battery life { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; result = _nukiOpener.requestConfig(&_nukiConfig); - _taskRunning = false; + delay(250); _nukiConfigValid = result == Nuki::CmdResult::Success; if(!_nukiConfigValid) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } } diff --git a/src/NukiOpenerWrapper.h b/src/NukiOpenerWrapper.h index 87decd5..0c74a0d 100644 --- a/src/NukiOpenerWrapper.h +++ b/src/NukiOpenerWrapper.h @@ -1,7 +1,7 @@ #pragma once #include "NukiOpener.h" -#include "NetworkOpener.h" +#include "NukiNetworkOpener.h" #include "NukiOpenerConstants.h" #include "NukiDataTypes.h" #include "BleScanner.h" @@ -11,7 +11,7 @@ class NukiOpenerWrapper : public NukiOpener::SmartlockEventHandler { public: - NukiOpenerWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NetworkOpener* network, Gpio* gpio, Preferences* preferences); + NukiOpenerWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkOpener* network, Gpio* gpio, Preferences* preferences); virtual ~NukiOpenerWrapper(); void initialize(); @@ -90,7 +90,7 @@ private: NukiDeviceId* _deviceId = nullptr; NukiOpener::NukiOpener _nukiOpener; BleScanner::Scanner* _bleScanner = nullptr; - NetworkOpener* _network = nullptr; + NukiNetworkOpener* _network = nullptr; Gpio* _gpio = nullptr; Preferences* _preferences = nullptr; int _intervalLockstate = 0; // seconds @@ -100,7 +100,6 @@ private: int _restartBeaconTimeout = 0; // seconds bool _publishAuthData = false; bool _clearAuthData = false; - bool _taskRunning = false; int _nrOfRetries = 0; int _retryDelay = 0; int _retryCount = 0; diff --git a/src/NukiWrapper.cpp b/src/NukiWrapper.cpp index 2ebd1b6..ccc49a5 100644 --- a/src/NukiWrapper.cpp +++ b/src/NukiWrapper.cpp @@ -8,10 +8,10 @@ #include "Config.h" NukiWrapper* nukiInst; -NetworkLock* networkInst; +NukiNetworkLock* networkInst; Preferences* nukiLockPreferences = nullptr; -NukiWrapper::NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NetworkLock* network, Gpio* gpio, Preferences* preferences) +NukiWrapper::NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkLock* network, Gpio* gpio, Preferences* preferences) : _deviceName(deviceName), _deviceId(deviceId), _bleScanner(scanner), @@ -72,65 +72,106 @@ void NukiWrapper::initialize(const bool& firstStart) if(firstStart) { + Log->println("First start, setting preference defaults"); + _preferences->putBool(preference_network_wifi_fallback_disabled, false); + _preferences->putBool(preference_find_best_rssi, false); + _preferences->putBool(preference_check_updates, true); + _preferences->putBool(preference_opener_continuous_mode, false); + _preferences->putBool(preference_network_wifi_fallback_disabled, false); + _preferences->putBool(preference_official_hybrid, false); + _preferences->putBool(preference_official_hybrid_actions, false); + _preferences->putBool(preference_official_hybrid_retry, false); + _preferences->putBool(preference_disable_non_json, false); + _preferences->putBool(preference_update_from_mqtt, false); + _preferences->putBool(preference_ip_dhcp_enabled, true); + _preferences->putBool(preference_enable_bootloop_reset, false); + _preferences->putBool(preference_show_secrets, false); + + _preferences->putBool(preference_conf_info_enabled, true); + _preferences->putBool(preference_keypad_info_enabled, false); + _preferences->putBool(preference_keypad_topic_per_entry, false); + _preferences->putBool(preference_keypad_publish_code, false); + _preferences->putBool(preference_keypad_control_enabled, false); + _preferences->putBool(preference_timecontrol_info_enabled, false); + _preferences->putBool(preference_timecontrol_topic_per_entry, false); + _preferences->putBool(preference_timecontrol_control_enabled, false); + _preferences->putBool(preference_publish_authdata, false); + _preferences->putBool(preference_register_as_app, false); + _preferences->putBool(preference_register_opener_as_app, false); + + _preferences->putInt(preference_mqtt_broker_port, 1883); + _preferences->putInt(preference_buffer_size, CHAR_BUFFER_SIZE); + _preferences->putInt(preference_task_size_network, NETWORK_TASK_SIZE); + _preferences->putInt(preference_task_size_nuki, NUKI_TASK_SIZE); + _preferences->putInt(preference_authlog_max_entries, MAX_AUTHLOG); + _preferences->putInt(preference_keypad_max_entries, MAX_KEYPAD); + _preferences->putInt(preference_timecontrol_max_entries, MAX_TIMECONTROL); + _preferences->putInt(preference_query_interval_hybrid_lockstate, 600); + _preferences->putInt(preference_rssi_publish_interval, 60); + _preferences->putInt(preference_network_timeout, 60); _preferences->putInt(preference_command_nr_of_retries, 3); _preferences->putInt(preference_command_retry_delay, 1000); _preferences->putInt(preference_restart_ble_beacon_lost, 60); - uint32_t aclPrefs[17] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; - _preferences->putBytes(preference_acl, (byte*)(&aclPrefs), sizeof(aclPrefs)); - uint32_t basicLockConfigAclPrefs[16] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; - _preferences->putBytes(preference_conf_lock_basic_acl, (byte*)(&basicLockConfigAclPrefs), sizeof(basicLockConfigAclPrefs)); - uint32_t basicOpenerConfigAclPrefs[14] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; - _preferences->putBytes(preference_conf_opener_basic_acl, (byte*)(&basicOpenerConfigAclPrefs), sizeof(basicOpenerConfigAclPrefs)); - uint32_t advancedLockConfigAclPrefs[22] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; - _preferences->putBytes(preference_conf_lock_advanced_acl, (byte*)(&advancedLockConfigAclPrefs), sizeof(advancedLockConfigAclPrefs)); - uint32_t advancedOpenerConfigAclPrefs[20] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; - _preferences->putBytes(preference_conf_opener_advanced_acl, (byte*)(&advancedOpenerConfigAclPrefs), sizeof(advancedOpenerConfigAclPrefs)); + _preferences->putInt(preference_query_interval_lockstate, 1800); + _preferences->putInt(preference_query_interval_configuration, 3600); + _preferences->putInt(preference_query_interval_battery, 1800); + _preferences->putInt(preference_query_interval_keypad, 1800); + _preferences->putInt(preference_presence_detection_timeout, -1); } if(_nrOfRetries < 0 || _nrOfRetries == 200) { + Log->println("Invalid nrOfRetries, revert to default (3)"); _nrOfRetries = 3; _preferences->putInt(preference_command_nr_of_retries, _nrOfRetries); } if(_retryDelay <= 100) { + Log->println("Invalid retryDelay, revert to default (100)"); _retryDelay = 100; _preferences->putInt(preference_command_retry_delay, _retryDelay); } if(_intervalLockstate == 0) { + Log->println("Invalid intervalLockstate, revert to default (1800)"); _intervalLockstate = 60 * 30; _preferences->putInt(preference_query_interval_lockstate, _intervalLockstate); } if(_intervalHybridLockstate == 0) { + Log->println("Invalid intervalHybridLockstate, revert to default (600)"); _intervalHybridLockstate = 60 * 10; _preferences->putInt(preference_query_interval_hybrid_lockstate, _intervalHybridLockstate); } if(_intervalConfig == 0) { + Log->println("Invalid intervalConfig, revert to default (3600)"); _intervalConfig = 60 * 60; _preferences->putInt(preference_query_interval_configuration, _intervalConfig); } if(_intervalBattery == 0) { + Log->println("Invalid intervalBattery, revert to default (1800)"); _intervalBattery = 60 * 30; _preferences->putInt(preference_query_interval_battery, _intervalBattery); } if(_intervalKeypad == 0) { + Log->println("Invalid intervalKeypad, revert to default (1800)"); _intervalKeypad = 60 * 30; _preferences->putInt(preference_query_interval_keypad, _intervalKeypad); } if(_restartBeaconTimeout < 10) { + Log->println("Invalid restartBeaconTimeout, revert to default (-1)"); _restartBeaconTimeout = -1; _preferences->putInt(preference_restart_ble_beacon_lost, _restartBeaconTimeout); } - + _nukiLock.setEventHandler(this); + _nukiLock.setDisonnectTimeout(5000); Log->print(F("Lock state interval: ")); Log->print(_intervalLockstate); @@ -150,6 +191,7 @@ void NukiWrapper::update() if(!_paired) { Log->println(F("Nuki lock start pairing")); + _preferences->getBool(preference_register_as_app) ? Log->println(F("Pairing as app")) : Log->println(F("Pairing as bridge")); _network->publishBleAddress(""); Nuki::AuthorizationIdType idType = _preferences->getBool(preference_register_as_app) ? @@ -190,6 +232,7 @@ void NukiWrapper::update() if(_statusUpdated || _nextLockStateUpdateTs == 0 || ts >= _nextLockStateUpdateTs || (queryCommands & QUERY_COMMAND_LOCKSTATE) > 0) { + Log->println("Updating Lock state based on timer or query"); _statusUpdated = false; _nextLockStateUpdateTs = ts + _intervalLockstate * 1000; updateKeyTurnerState(); @@ -202,11 +245,13 @@ void NukiWrapper::update() } if(_nextBatteryReportTs == 0 || ts > _nextBatteryReportTs || (queryCommands & QUERY_COMMAND_BATTERY) > 0) { + Log->println("Updating Lock battery state based on timer or query"); _nextBatteryReportTs = ts + _intervalBattery * 1000; updateBatteryState(); } if(_nextConfigUpdateTs == 0 || ts > _nextConfigUpdateTs || (queryCommands & QUERY_COMMAND_CONFIG) > 0) { + Log->println("Updating Lock config based on timer or query"); _nextConfigUpdateTs = ts + _intervalConfig * 1000; updateConfig(); if(_hassEnabled && !_hassSetupCompleted) @@ -247,23 +292,14 @@ void NukiWrapper::update() if(_hasKeypad && _keypadEnabled && (_nextKeypadUpdateTs == 0 || ts > _nextKeypadUpdateTs || (queryCommands & QUERY_COMMAND_KEYPAD) > 0)) { + Log->println("Updating Lock keypad based on timer or query"); _nextKeypadUpdateTs = ts + _intervalKeypad * 1000; updateKeypad(false); } if(_nextLockAction != (NukiLock::LockAction)0xff && ts > _nextRetryTs) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; Nuki::CmdResult cmdResult = _nukiLock.lockAction(_nextLockAction, 0, 0); - _taskRunning = false; char resultStr[15] = {0}; NukiLock::cmdResultToString(cmdResult, resultStr); @@ -315,6 +351,7 @@ void NukiWrapper::update() if(_clearAuthData) { + Log->println("Clearing Lock auth data"); _network->clearAuthorizationInfo(); _clearAuthData = false; } @@ -376,28 +413,23 @@ void NukiWrapper::unpair() void NukiWrapper::updateKeyTurnerState() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; + + Log->println("Querying lock state"); while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; - Log->print(F("Querying lock state: ")); + Log->print(F("Result (attempt ")); + Log->print(_retryCount + 1); + Log->print("): "); result =_nukiLock.requestKeyTurnerState(&_keyTurnerState); - _taskRunning = false; - if(!_nukiConfigValid) { + delay(250); + + if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } char resultStr[15]; @@ -407,10 +439,14 @@ void NukiWrapper::updateKeyTurnerState() if(result != Nuki::CmdResult::Success) { + Log->println("Query lock state failed"); _retryLockstateCount++; postponeBleWatchdog(); - if(_retryLockstateCount < _nrOfRetries) + if(_retryLockstateCount < _nrOfRetries + 1) { + Log->print(F("Query lock state retrying in ")); + Log->print(_retryDelay); + Log->println("ms"); _nextLockStateUpdateTs = millis() + _retryDelay; } return; @@ -438,28 +474,22 @@ void NukiWrapper::updateKeyTurnerState() void NukiWrapper::updateBatteryState() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; + + Log->println("Querying lock battery state"); while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; - Log->print(F("Querying lock battery state: ")); + Log->print(F("Result (attempt ")); + Log->print(_retryCount + 1); + Log->print("): "); result = _nukiLock.requestBatteryReport(&_batteryReport); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } printCommandResult(result); @@ -482,6 +512,13 @@ void NukiWrapper::updateConfig() { if(_preferences->getUInt(preference_nuki_id_lock, 0) == 0 || _retryConfigCount == 10) { + char uidString[20]; + itoa(_nukiConfig.nukiId, uidString, 16); + Log->print(F("Saving Nuki ID to preferences (")); + Log->print(_nukiConfig.nukiId); + Log->print(" / "); + Log->print(uidString); + Log->println(")"); _preferences->putUInt(preference_nuki_id_lock, _nukiConfig.nukiId); } @@ -498,37 +535,30 @@ void NukiWrapper::updateConfig() const int pinStatus = _preferences->getInt(preference_lock_pin_status, 4); if(isPinSet()) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; + Log->println(F("Nuki Lock PIN is set")); while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; result = _nukiLock.verifySecurityPin(); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if(result != Nuki::CmdResult::Success) { - if(pinStatus != 2) { + Log->println(F("Nuki Lock PIN is invalid")); + if(pinStatus != 2) { _preferences->putInt(preference_lock_pin_status, 2); } } else { + Log->println(F("Nuki Lock PIN is valid")); if(pinStatus != 1) { _preferences->putInt(preference_lock_pin_status, 1); } @@ -536,6 +566,7 @@ void NukiWrapper::updateConfig() } else { + Log->println(F("Nuki Lock PIN is not set")); if(pinStatus != 0) { _preferences->putInt(preference_lock_pin_status, 0); } @@ -543,12 +574,14 @@ void NukiWrapper::updateConfig() } else { + Log->println(F("Invalid/Unexpected config recieved, retrying")); expectedConfig = false; ++_retryConfigCount; } } else { + Log->println(F("Invalid/Unexpected config recieved, retrying")); expectedConfig = false; ++_retryConfigCount; } @@ -559,6 +592,7 @@ void NukiWrapper::updateConfig() } else { + Log->println(F("Invalid/Unexpected advanced config recieved, retrying")); expectedConfig = false; ++_retryConfigCount; } @@ -573,38 +607,27 @@ void NukiWrapper::updateAuthData(bool retrieved) { if(!isPinValid()) { - Log->println(F("No valid PIN set")); + Log->println(F("No valid Nuki Lock PIN set")); return; } if(!retrieved) { delay(250); - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Retrieve log entries: ")); result = _nukiLock.retrieveLogEntries(0, _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 1, false); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } - Log->println(result); printCommandResult(result); if(result == Nuki::CmdResult::Success) { @@ -657,28 +680,18 @@ void NukiWrapper::updateKeypad(bool retrieved) if(!retrieved) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Querying lock keypad: ")); result = _nukiLock.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } printCommandResult(result); @@ -728,28 +741,18 @@ void NukiWrapper::updateTimeControl(bool retrieved) if(!retrieved) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; Log->print(F("Querying lock time control: ")); result = _nukiLock.retrieveTimeControlEntries(); - _taskRunning = false; + delay(250); if(result != Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } printCommandResult(result); @@ -977,7 +980,7 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) _statusUpdated = true; _network->publishStatusUpdated(_statusUpdated); NukiLock::lockstateToString((NukiLock::LockState)_network->_offState, str); - _network->publishString(mqtt_topic_lock_state, str); + _network->publishString(mqtt_topic_lock_state, str, true); Log->print(F("Lockstate: ")); Log->println(str); @@ -997,7 +1000,7 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) Log->print(F("Doorsensor state: ")); Log->println(str); - _network->publishString(mqtt_topic_lock_door_sensor_state, str); + _network->publishString(mqtt_topic_lock_door_sensor_state, str, true); } else if(strcmp(topic, mqtt_topic_official_batteryCritical) == 0) { @@ -1006,7 +1009,7 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) Log->print(F("Battery critical: ")); Log->println(_network->_offCritical); - if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_critical, _network->_offCritical); + if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_critical, _network->_offCritical, true); publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_batteryCharging) == 0) @@ -1016,7 +1019,7 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) Log->print(F("Battery charging: ")); Log->println(_network->_offCharging); - if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_charging, _network->_offCharging); + if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_charging, _network->_offCharging, true); publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_batteryChargeState) == 0) @@ -1026,19 +1029,19 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) Log->print(F("Battery level: ")); Log->println(_network->_offChargeState); - if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishInt(mqtt_topic_battery_level, _network->_offChargeState); + if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishInt(mqtt_topic_battery_level, _network->_offChargeState, true); publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_keypadBatteryCritical) == 0) { _network->_offKeypadCritical = (strcmp(value, "true") == 0 ? 1 : 0); - if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_keypad_critical, _network->_offKeypadCritical); + if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_keypad_critical, _network->_offKeypadCritical, true); publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_doorsensorBatteryCritical) == 0) { _network->_offDoorsensorCritical = (strcmp(value, "true") == 0 ? 1 : 0); - if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_doorsensor_critical, _network->_offDoorsensorCritical); + if(!_preferences->getBool(preference_disable_non_json, false)) _network->publishBool(mqtt_topic_battery_doorsensor_critical, _network->_offDoorsensorCritical, true); publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_commandResponse) == 0) @@ -1068,11 +1071,11 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) memset(&str, 0, sizeof(str)); lockactionToString((NukiLock::LockAction)_network->_offLockAction, str); - _network->publishString(mqtt_topic_lock_last_lock_action, str); + _network->publishString(mqtt_topic_lock_last_lock_action, str, true); memset(&str, 0, sizeof(str)); triggerToString((NukiLock::Trigger)_network->_offTrigger, str); - _network->publishString(mqtt_topic_lock_trigger, str); + _network->publishString(mqtt_topic_lock_trigger, str, true); if(_network->_offAuthId > 0 || _network->_offCodeId > 0) { @@ -1098,7 +1101,7 @@ void NukiWrapper::onOfficialUpdateReceived(const char *topic, const char *value) jsonBattery["keypadCritical"] = _network->_offKeypadCritical ? "1" : "0"; jsonBattery["doorSensorCritical"] = _network->_offDoorsensorCritical ? "1" : "0"; serializeJson(jsonBattery, _resbuf, sizeof(_resbuf)); - _network->publishString(mqtt_topic_battery_basic_json, _resbuf); + _network->publishString(mqtt_topic_battery_basic_json, _resbuf, true); } } @@ -1147,16 +1150,6 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) nukiLockPreferences->getBytes(preference_conf_lock_basic_acl, &basicLockConfigAclPrefs, sizeof(basicLockConfigAclPrefs)); nukiLockPreferences->getBytes(preference_conf_lock_advanced_acl, &advancedLockConfigAclPrefs, sizeof(advancedLockConfigAclPrefs)); - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; - for(int i=0; i < 16; i++) { if(json[basicKeys[i]]) @@ -1176,14 +1169,6 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(basicKeys[i], "name") == 0) { if(strlen(jsonchar) <= 32) @@ -1359,12 +1344,11 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) else jsonResult[basicKeys[i]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + delay(250); + if(!cmdResult == Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if(cmdResult == Nuki::CmdResult::Success) basicUpdated = true; @@ -1398,14 +1382,6 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(advancedKeys[j], "unlockedPositionOffsetDegrees") == 0) { const int16_t keyvalue = atoi(jsonchar); @@ -1653,12 +1629,11 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) else jsonResult[advancedKeys[j]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + delay(250); + if(!cmdResult == Nuki::CmdResult::Success) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if(cmdResult == Nuki::CmdResult::Success) advancedUpdated = true; @@ -1673,8 +1648,6 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) } } - _taskRunning = false; - nukiLockPreferences->end(); if(basicUpdated || advancedUpdated) jsonResult["general"] = "success"; @@ -1791,14 +1764,6 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(command, "add") == 0) { if(name == "" || name == "--") @@ -1822,9 +1787,8 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c size_t nameLen = name.length(); memcpy(&entry.name, name.c_str(), nameLen > 20 ? 20 : nameLen); entry.code = codeInt; - _taskRunning = true; result = _nukiLock.addKeypadEntry(entry); - _taskRunning = false; + delay(250); Log->print("Add keypad code: "); Log->println((int)result); updateKeypad(false); } @@ -1836,9 +1800,8 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c return; } - _taskRunning = true; result = _nukiLock.deleteKeypadEntry(id); - _taskRunning = false; + delay(250); Log->print("Delete keypad code: "); Log->println((int)result); updateKeypad(false); } @@ -1872,13 +1835,12 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c memcpy(&entry.name, name.c_str(), nameLen > 20 ? 20 : nameLen); entry.code = codeInt; entry.enabled = enabled == 0 ? 0 : 1; - _taskRunning = true; result = _nukiLock.updateKeypadEntry(entry); - _taskRunning = false; + delay(250); Log->print("Update keypad code: "); Log->println((int)result); updateKeypad(false); } - else if(command == "--") + else if(strcmp(command, "--") == 0) { return; } @@ -1892,8 +1854,6 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if((int)result != -1) @@ -1989,20 +1949,11 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(action, "delete") == 0) { if(idExists) { - _taskRunning = true; result = _nukiLock.deleteKeypadEntry(codeId); - _taskRunning = false; + delay(250); Log->print(F("Delete keypad code: ")); Log->println((int)result); } @@ -2188,9 +2139,8 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) entry.allowedUntilTimeMin = allowedUntilTimeAr[1]; } - _taskRunning = true; result = _nukiLock.addKeypadEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Add keypad code: ")); Log->println((int)result); } @@ -2208,17 +2158,8 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) return; } - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; Nuki::CmdResult resultKp = _nukiLock.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - _taskRunning = false; + delay(250); bool foundExisting = false; if(resultKp == Nuki::CmdResult::Success) @@ -2346,9 +2287,8 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) } } - _taskRunning = true; result = _nukiLock.updateKeypadEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Update keypad code: ")); Log->println((int)result); } @@ -2363,8 +2303,6 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } updateKeypad(false); @@ -2453,20 +2391,11 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - if(strcmp(action, "delete") == 0) { if(idExists) { - _taskRunning = true; result = _nukiLock.removeTimeControlEntry(entryId); - _taskRunning = false; + delay(250); Log->print(F("Delete time control: ")); Log->println((int)result); } @@ -2525,9 +2454,8 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) entry.lockAction = timeControlLockAction; - _taskRunning = true; result = _nukiLock.addTimeControlEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Add time control: ")); Log->println((int)result); } @@ -2539,17 +2467,8 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) return; } - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - - _taskRunning = true; Nuki::CmdResult resultTc = _nukiLock.retrieveTimeControlEntries(); - _taskRunning = false; + delay(250); bool foundExisting = false; if(resultTc == Nuki::CmdResult::Success) @@ -2570,7 +2489,7 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) timeAr[0] = entry.timeHour; timeAr[1] = entry.timeMin; } - if(lockAction.length() < 1) timeControlLockAction = entry.lockAction; + if(lockAction.length() < 1) timeControlLockAction = entry.lockAction; } if(!foundExisting) @@ -2599,9 +2518,8 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) entry.lockAction = timeControlLockAction; - _taskRunning = true; result = _nukiLock.updateTimeControlEntry(entry); - _taskRunning = false; + delay(250); Log->print(F("Update time control: ")); Log->println((int)result); } @@ -2616,8 +2534,6 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } if((int)result != -1) @@ -2658,6 +2574,7 @@ void NukiWrapper::notify(Nuki::EventType eventType) { if(_preferences->getBool(preference_official_hybrid, false) && _intervalHybridLockstate > 0 && millis() > (_intervalHybridLockstate * 1000)) { + Log->println("OffKeyTurnerStatusUpdated"); _statusUpdated = true; _nextHybridLockStateUpdateTs = millis() + _intervalHybridLockstate * 1000; } @@ -2665,6 +2582,7 @@ void NukiWrapper::notify(Nuki::EventType eventType) { if(eventType == Nuki::EventType::KeyTurnerStatusUpdated) { + Log->println("KeyTurnerStatusUpdated"); _statusUpdated = true; _network->publishStatusUpdated(_statusUpdated); } @@ -2674,29 +2592,22 @@ void NukiWrapper::notify(Nuki::EventType eventType) void NukiWrapper::readConfig() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; - Log->print(F("Reading config. Result: ")); result = _nukiLock.requestConfig(&_nukiConfig); - _taskRunning = false; + delay(250); _nukiConfigValid = result == Nuki::CmdResult::Success; + + Log->print(F("Config valid: ")); + Log->println(_nukiConfigValid); if(!_nukiConfigValid) { ++_retryCount; + Log->println("Retrying in 1s"); } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } char resultStr[20]; @@ -2706,29 +2617,19 @@ void NukiWrapper::readConfig() void NukiWrapper::readAdvancedConfig() { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; result = _nukiLock.requestAdvancedConfig(&_nukiAdvancedConfig); - _taskRunning = false; + delay(250); _nukiAdvancedConfigValid = result == Nuki::CmdResult::Success; if(!_nukiAdvancedConfigValid) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } char resultStr[20]; @@ -2760,31 +2661,21 @@ bool NukiWrapper::hasDoorSensor() const void NukiWrapper::disableHASS() { - if(!_nukiConfigValid) // only ask for config once to save battery life + if(!_nukiConfigValid) { - Nuki::CmdResult result; + Nuki::CmdResult result = (Nuki::CmdResult)-1; _retryCount = 0; while(_retryCount < _nrOfRetries + 1) { - int loop = 0; - while(_taskRunning && loop < 600) - { - Log->println("Waiting to run Nuki BLE command"); - vTaskDelay( 50 / portTICK_PERIOD_MS); - ++loop; - } - _taskRunning = true; result = _nukiLock.requestConfig(&_nukiConfig); - _taskRunning = false; + delay(250); _nukiConfigValid = result == Nuki::CmdResult::Success; if(!_nukiConfigValid) { ++_retryCount; } else break; - - vTaskDelay( 1000 / portTICK_PERIOD_MS); } } diff --git a/src/NukiWrapper.h b/src/NukiWrapper.h index 49618e0..ea0cb7e 100644 --- a/src/NukiWrapper.h +++ b/src/NukiWrapper.h @@ -1,6 +1,6 @@ #pragma once -#include "NetworkLock.h" +#include "NukiNetworkLock.h" #include "NukiConstants.h" #include "NukiDataTypes.h" #include "BleScanner.h" @@ -12,7 +12,7 @@ class NukiWrapper : public Nuki::SmartlockEventHandler { public: - NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NetworkLock* network, Gpio* gpio, Preferences* preferences); + NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkLock* network, Gpio* gpio, Preferences* preferences); virtual ~NukiWrapper(); void initialize(const bool& firstStart); @@ -86,7 +86,7 @@ private: NukiDeviceId* _deviceId = nullptr; NukiLock::NukiLock _nukiLock; BleScanner::Scanner* _bleScanner = nullptr; - NetworkLock* _network = nullptr; + NukiNetworkLock* _network = nullptr; Gpio* _gpio = nullptr; Preferences* _preferences; int _intervalLockstate = 0; // seconds @@ -97,7 +97,6 @@ private: int _restartBeaconTimeout = 0; // seconds bool _publishAuthData = false; bool _clearAuthData = false; - bool _taskRunning = false; std::vector _keypadCodeIds; std::vector _timeControlIds; diff --git a/src/PreferencesKeys.h b/src/PreferencesKeys.h index 1e32147..109410b 100644 --- a/src/PreferencesKeys.h +++ b/src/PreferencesKeys.h @@ -44,7 +44,6 @@ #define preference_hostname (char*)"hostname" #define preference_network_timeout (char*)"nettmout" #define preference_restart_on_disconnect (char*)"restdisc" -#define preference_restart_timer (char*)"resttmr" #define preference_restart_ble_beacon_lost (char*)"rstbcn" #define preference_query_interval_lockstate (char*)"lockStInterval" #define preference_query_interval_configuration (char*)"configInterval" @@ -93,43 +92,66 @@ #define preference_official_hybrid_actions (char*)"hybridAct" #define preference_official_hybrid_retry (char*)"hybridRtry" #define preference_query_interval_hybrid_lockstate (char*)"hybridTimer" +#define preference_ota_main_url (char*)"otaMainUrl" +#define preference_ota_updater_url (char*)"otaUpdUrl" +#define preference_update_from_mqtt (char*)"updMqtt" +#define preference_show_secrets (char*)"showSecr" class DebugPreferences { private: std::vector _keys = { - preference_started_before, preference_config_version, preference_device_id_lock, preference_device_id_opener, preference_nuki_id_lock, preference_nuki_id_opener, preference_mqtt_broker, preference_mqtt_broker_port, preference_mqtt_user, preference_mqtt_password, preference_mqtt_log_enabled, preference_check_updates, preference_webserver_enabled, - preference_lock_enabled, preference_lock_pin_status, preference_mqtt_lock_path, preference_opener_enabled, preference_opener_pin_status, - preference_opener_continuous_mode, preference_mqtt_opener_path, preference_lock_max_keypad_code_count, preference_opener_max_keypad_code_count, preference_lock_max_timecontrol_entry_count, - preference_opener_max_timecontrol_entry_count, preference_enable_bootloop_reset, preference_mqtt_ca, preference_mqtt_crt, preference_mqtt_key, preference_mqtt_hass_discovery, - preference_mqtt_hass_cu_url, preference_buffer_size, preference_ip_dhcp_enabled, preference_ip_address, preference_ip_subnet, preference_ip_gateway, preference_ip_dns_server, - preference_network_hardware, preference_network_wifi_fallback_disabled, preference_rssi_publish_interval, preference_hostname, preference_find_best_rssi, - preference_network_timeout, preference_restart_on_disconnect, preference_restart_ble_beacon_lost, preference_query_interval_lockstate, preference_timecontrol_topic_per_entry, - preference_keypad_topic_per_entry, preference_query_interval_configuration, preference_query_interval_battery, preference_query_interval_keypad, preference_keypad_control_enabled, + preference_started_before, preference_config_version, preference_device_id_lock, preference_device_id_opener, preference_nuki_id_lock, preference_nuki_id_opener, + preference_mqtt_broker, preference_mqtt_broker_port, preference_mqtt_user, preference_mqtt_password, preference_mqtt_log_enabled, preference_check_updates, + preference_webserver_enabled, preference_lock_enabled, preference_lock_pin_status, preference_mqtt_lock_path, preference_opener_enabled, preference_opener_pin_status, + preference_opener_continuous_mode, preference_mqtt_opener_path, preference_lock_max_keypad_code_count, preference_opener_max_keypad_code_count, + preference_lock_max_timecontrol_entry_count, preference_opener_max_timecontrol_entry_count, preference_enable_bootloop_reset, preference_mqtt_ca, preference_mqtt_crt, + preference_mqtt_key, preference_mqtt_hass_discovery, preference_mqtt_hass_cu_url, preference_buffer_size, preference_ip_dhcp_enabled, preference_ip_address, + preference_ip_subnet, preference_ip_gateway, preference_ip_dns_server, preference_network_hardware, preference_network_wifi_fallback_disabled, + preference_rssi_publish_interval, preference_hostname, preference_find_best_rssi, preference_network_timeout, preference_restart_on_disconnect, + preference_restart_ble_beacon_lost, preference_query_interval_lockstate, preference_timecontrol_topic_per_entry, preference_keypad_topic_per_entry, + preference_query_interval_configuration, preference_query_interval_battery, preference_query_interval_keypad, preference_keypad_control_enabled, preference_keypad_info_enabled, preference_keypad_publish_code, preference_timecontrol_control_enabled, preference_timecontrol_info_enabled, preference_conf_info_enabled, - preference_register_as_app, preference_register_opener_as_app, preference_command_nr_of_retries, preference_command_retry_delay, preference_cred_user, preference_cred_password, - preference_disable_non_json, preference_publish_authdata, preference_publish_debug_info, preference_presence_detection_timeout, preference_official_hybrid, preference_query_interval_hybrid_lockstate, - preference_official_hybrid_actions, preference_official_hybrid_retry, preference_has_mac_saved, preference_has_mac_byte_0, preference_has_mac_byte_1, preference_has_mac_byte_2, - preference_latest_version, preference_task_size_network, preference_task_size_nuki, preference_authlog_max_entries, preference_keypad_max_entries, - preference_timecontrol_max_entries + preference_register_as_app, preference_register_opener_as_app, preference_command_nr_of_retries, preference_command_retry_delay, preference_cred_user, + preference_cred_password, preference_disable_non_json, preference_publish_authdata, preference_publish_debug_info, preference_presence_detection_timeout, + preference_official_hybrid, preference_query_interval_hybrid_lockstate, preference_official_hybrid_actions, preference_official_hybrid_retry, preference_has_mac_saved, + preference_has_mac_byte_0, preference_has_mac_byte_1, preference_has_mac_byte_2, preference_latest_version, preference_task_size_network, preference_task_size_nuki, + preference_authlog_max_entries, preference_keypad_max_entries, preference_timecontrol_max_entries, preference_update_from_mqtt, preference_show_secrets }; std::vector _redact = { - preference_mqtt_user, preference_mqtt_password, - preference_mqtt_ca, preference_mqtt_crt, preference_mqtt_key, - preference_cred_user, preference_cred_password, + preference_mqtt_user, preference_mqtt_password, preference_mqtt_ca, preference_mqtt_crt, preference_mqtt_key, preference_cred_user, preference_cred_password, preference_nuki_id_lock, preference_nuki_id_opener, }; std::vector _boolPrefs = { preference_started_before, preference_mqtt_log_enabled, preference_check_updates, preference_lock_enabled, preference_opener_enabled, preference_opener_continuous_mode, - preference_timecontrol_topic_per_entry, preference_keypad_topic_per_entry, preference_enable_bootloop_reset, preference_webserver_enabled, preference_find_best_rssi, preference_restart_on_disconnect, - preference_keypad_control_enabled, preference_keypad_info_enabled, preference_keypad_publish_code, preference_timecontrol_control_enabled, preference_timecontrol_info_enabled, - preference_register_as_app, preference_register_opener_as_app, preference_ip_dhcp_enabled, preference_publish_authdata, preference_has_mac_saved, preference_publish_debug_info, - preference_network_wifi_fallback_disabled, preference_official_hybrid, preference_official_hybrid_actions, preference_official_hybrid_retry, preference_conf_info_enabled, preference_disable_non_json + preference_timecontrol_topic_per_entry, preference_keypad_topic_per_entry, preference_enable_bootloop_reset, preference_webserver_enabled, preference_find_best_rssi, + preference_restart_on_disconnect, preference_keypad_control_enabled, preference_keypad_info_enabled, preference_keypad_publish_code, preference_show_secrets, + preference_timecontrol_control_enabled, preference_timecontrol_info_enabled, preference_register_as_app, preference_register_opener_as_app, preference_ip_dhcp_enabled, + preference_publish_authdata, preference_has_mac_saved, preference_publish_debug_info, preference_network_wifi_fallback_disabled, preference_official_hybrid, + preference_official_hybrid_actions, preference_official_hybrid_retry, preference_conf_info_enabled, preference_disable_non_json, preference_update_from_mqtt + }; + std::vector _bytePrefs = + { + preference_acl, preference_conf_info_enabled, preference_conf_lock_basic_acl, preference_conf_lock_advanced_acl, preference_conf_opener_basic_acl, + preference_conf_opener_advanced_acl, preference_gpio_configuration + }; + std::vector _intPrefs = + { + preference_config_version, preference_device_id_lock, preference_device_id_opener, preference_nuki_id_lock, preference_nuki_id_opener, preference_mqtt_broker_port, + preference_lock_pin_status, preference_opener_pin_status, preference_lock_max_keypad_code_count, preference_opener_max_keypad_code_count, + preference_lock_max_timecontrol_entry_count, preference_opener_max_timecontrol_entry_count, preference_buffer_size, preference_network_hardware, + preference_rssi_publish_interval, preference_network_timeout, preference_restart_ble_beacon_lost, preference_query_interval_lockstate, + preference_query_interval_configuration, preference_query_interval_battery, preference_query_interval_keypad, preference_command_nr_of_retries, + preference_command_retry_delay, preference_presence_detection_timeout, preference_query_interval_hybrid_lockstate, preference_latest_version, + preference_task_size_network, preference_task_size_nuki, preference_authlog_max_entries, preference_keypad_max_entries, preference_timecontrol_max_entries + }; + std::vector _charPrefs = + { + preference_has_mac_byte_0, preference_has_mac_byte_1, preference_has_mac_byte_2 }; - const bool isRedacted(const char* key) const { return std::find(_redact.begin(), _redact.end(), key) != _redact.end(); @@ -270,6 +292,30 @@ private: } public: + const std::vector getPreferencesKeys() + { + return _keys; + } + const std::vector getPreferencesRedactedKeys() + { + return _redact; + } + const std::vector getPreferencesBoolKeys() + { + return _boolPrefs; + } + const std::vector getPreferencesByteKeys() + { + return _bytePrefs; + } + const std::vector getPreferencesIntKeys() + { + return _intPrefs; + } + const std::vector getPreferencesCharKeys() + { + return _charPrefs; + } const String preferencesToString(Preferences *preferences) { String s = ""; diff --git a/src/PresenceDetection.cpp b/src/PresenceDetection.cpp index 64cac63..b766fee 100644 --- a/src/PresenceDetection.cpp +++ b/src/PresenceDetection.cpp @@ -213,6 +213,24 @@ void PresenceDetection::onResult(NimBLEAdvertisedDevice *device) // } } } + else + { + std::string nameStr = "-"; + i=0; + len = nameStr.length(); + while(i < len && i < sizeof(pdDevice->name)-1) + { + pdDevice->name[i] = nameStr.at(i); + ++i; + } + + pdDevice->timestamp = millis(); + + { + std::lock_guard lock(mtx); + _devices[addr] = pdDevice; + } + } } // if(device->haveName()) @@ -232,4 +250,4 @@ void PresenceDetection::onResult(NimBLEAdvertisedDevice *device) bool PresenceDetection::enabled() { return _timeout > 0; -} +} \ No newline at end of file diff --git a/src/RestartReason.h b/src/RestartReason.h index cf13a0e..36c6e71 100644 --- a/src/RestartReason.h +++ b/src/RestartReason.h @@ -19,6 +19,8 @@ enum class RestartReason OTATimeout, OTAAborted, OTAUnknownState, + OTAReboot, + ImportCompleted, DeviceUnpaired, NukiHubReset, NotApplicable @@ -99,6 +101,10 @@ inline static String getRestartReason() return "OTAAborted"; case RestartReason::OTAUnknownState: return "OTAUnknownState"; + case RestartReason::OTAReboot: + return "RebootToOTA"; + case RestartReason::ImportCompleted: + return "ConfigImportCompleted"; case RestartReason::DeviceUnpaired: return "DeviceUnpaired"; case RestartReason::NukiHubReset: @@ -142,9 +148,11 @@ inline static String getEspRestartReason() } } +#ifndef NUKI_HUB_UPDATER inline bool rebuildGpio() { bool rebGpio = rebuildGpioRequested; rebuildGpioRequested = false; return restartReason_isValid && rebGpio; -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/src/WebCfgServer.cpp b/src/WebCfgServer.cpp index 830b7f6..77a0ab1 100644 --- a/src/WebCfgServer.cpp +++ b/src/WebCfgServer.cpp @@ -7,18 +7,28 @@ #include "RestartReason.h" #include #include -#include -WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, Network* network, Gpio* gpio, EthServer* ethServer, Preferences* preferences, bool allowRestartToPortal) +#ifndef NUKI_HUB_UPDATER +#include "ArduinoJson.h" + +WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, EthServer* ethServer, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType) : _server(ethServer), _nuki(nuki), _nukiOpener(nukiOpener), _network(network), _gpio(gpio), _preferences(preferences), - _allowRestartToPortal(allowRestartToPortal) + _allowRestartToPortal(allowRestartToPortal), + _partitionType(partitionType) +#else +WebCfgServer::WebCfgServer(NukiNetwork* network, EthServer* ethServer, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType) +: _server(ethServer), + _network(network), + _preferences(preferences), + _allowRestartToPortal(allowRestartToPortal), + _partitionType(partitionType) +#endif { - _confirmCode = generateConfirmCode(); _hostname = _preferences->getString(preference_hostname); String str = _preferences->getString(preference_cred_user); @@ -36,6 +46,8 @@ WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, Net memcpy(&_credPassword, pass, str.length()); } + #ifndef NUKI_HUB_UPDATER + _confirmCode = generateConfirmCode(); _pinsConfigured = true; if(_nuki != nullptr && !_nuki->isPinSet()) @@ -48,6 +60,7 @@ WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, Net } _brokerConfigured = _preferences->getString(preference_mqtt_broker).length() > 0 && _preferences->getInt(preference_mqtt_broker_port) > 0; + #endif } void WebCfgServer::initialize() @@ -57,7 +70,11 @@ void WebCfgServer::initialize() return _server.requestAuthentication(); } String response = ""; + #ifndef NUKI_HUB_UPDATER buildHtml(response); + #else + buildOtaHtml(response, _server.arg("errored") != ""); + #endif _server.send(200, "text/html", response); }); _server.on("/style.css", [&]() { @@ -66,6 +83,52 @@ void WebCfgServer::initialize() } sendCss(); }); + _server.on("/favicon.ico", HTTP_GET, [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + sendFavicon(); + }); + #ifndef NUKI_HUB_UPDATER + _server.on("/import", [&]() + { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + String message = ""; + bool restart = processImport(message); + if(restart) + { + String response = ""; + buildConfirmHtml(response, message); + _server.send(200, "text/html", response); + Log->println(F("Restarting")); + + waitAndProcess(true, 1000); + restartEsp(RestartReason::ImportCompleted); + } + else + { + String response = ""; + buildConfirmHtml(response, message, 3); + _server.send(200, "text/html", response); + waitAndProcess(false, 1000); + } + }); + _server.on("/export", HTTP_GET, [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + sendSettings(); + }); + _server.on("/impexpcfg", [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + String response = ""; + buildImportExportHtml(response); + _server.send(200, "text/html", response); + }); _server.on("/status", HTTP_GET, [&]() { if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { return _server.requestAuthentication(); @@ -74,12 +137,6 @@ void WebCfgServer::initialize() buildStatusHtml(response); _server.send(200, "application/json", response); }); - _server.on("/favicon.ico", HTTP_GET, [&]() { - if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { - return _server.requestAuthentication(); - } - sendFavicon(); - }); _server.on("/acclvl", [&]() { if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { return _server.requestAuthentication(); @@ -210,38 +267,6 @@ void WebCfgServer::initialize() waitAndProcess(true, 1000); restartEsp(RestartReason::GpioConfigurationUpdated); }); - - _server.on("/ota", [&]() { - if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { - return _server.requestAuthentication(); - } - String response = ""; - buildOtaHtml(response, _server.arg("errored") != ""); - _server.send(200, "text/html", response); - }); - _server.on("/uploadota", HTTP_POST, [&]() { - if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { - return _server.requestAuthentication(); - } - - if (_ota.updateStarted() && _ota.updateCompleted()) { - String response = ""; - buildOtaCompletedHtml(response); - _server.send(200, "text/html", response); - delay(2000); - restartEsp(RestartReason::OTACompleted); - } else { - _ota.restart(); - _server.sendHeader("Location", "/ota?errored=true"); - _server.send(302, "text/plain", ""); - } - }, [&]() { - if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { - return _server.requestAuthentication(); - } - - handleOtaUpload(); - }); _server.on("/info", [&]() { if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { return _server.requestAuthentication(); @@ -272,6 +297,65 @@ void WebCfgServer::initialize() waitAndProcess(true, 1000); restartEsp(RestartReason::ConfigurationUpdated); }); + #endif + _server.on("/ota", [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + String response = ""; + buildOtaHtml(response, _server.arg("errored") != ""); + _server.send(200, "text/html", response); + }); + _server.on("/reboottoota", [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + String response = ""; + buildConfirmHtml(response, "Rebooting to other partition", 2); + _server.send(200, "text/html", response); + esp_ota_set_boot_partition(esp_ota_get_next_update_partition(NULL)); + restartEsp(RestartReason::OTAReboot); + }); + #if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) + _server.on("/autoupdate", [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + String response = ""; + buildConfirmHtml(response, "Rebooting to update Nuki Hub and Nuki Hub updater", 2); + _server.send(200, "text/html", response); + _preferences->putString(preference_ota_updater_url, GITHUB_LATEST_UPDATER_BINARY_URL); + _preferences->putString(preference_ota_main_url, GITHUB_LATEST_RELEASE_BINARY_URL); + restartEsp(RestartReason::OTAReboot); + }); + #endif + _server.on("/uploadota", HTTP_POST, [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + + if (_ota.updateStarted() && _ota.updateCompleted()) { + String response = ""; + buildOtaCompletedHtml(response); + _server.send(200, "text/html", response); + delay(2000); + restartEsp(RestartReason::OTACompleted); + } else { + _ota.restart(); + _server.sendHeader("Location", "/ota?errored=true"); + _server.send(302, "text/plain", ""); + } + }, [&]() { + if (_hasCredentials && !_server.authenticate(_credUser, _credPassword)) { + return _server.requestAuthentication(); + } + + handleOtaUpload(); + }); + + const char *headerkeys[] = {"Content-Length"}; + size_t headerkeyssize = sizeof(headerkeys) / sizeof(char *); + _server.collectHeaders(headerkeys, headerkeyssize); _server.begin(); @@ -281,12 +365,436 @@ void WebCfgServer::initialize() }); } +void WebCfgServer::update() +{ + if(_otaStartTs > 0 && (millis() - _otaStartTs) > 120000) + { + Log->println(F("OTA time out, restarting")); + delay(200); + restartEsp(RestartReason::OTATimeout); + } + + if(!_enabled) return; + + _server.handleClient(); +} + +void WebCfgServer::buildOtaHtml(String &response, bool errored) +{ + buildHtmlHeader(response); + + if(errored) response.concat("
Over-the-air update errored. Please check the logs for more info

"); + + if(_partitionType == 0) + { + response.concat("

You are currently running Nuki Hub with an outdated partition scheme. Because of this you cannot use OTA to update to 8.36 or higher. Please check GitHub for instructions on how to update to 8.36 and the new partition scheme

"); + response.concat(""); + return; + } + + response.concat("
Initiating Over-the-air update. This will take about two minutes, please be patient.
You will be forwarded automatically when the update is complete.
"); + + #if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) + response.concat("

Auto update Nuki Hub

"); + response.concat("Click on the button to reboot and automatically update Nuki Hub and the Nuki Hub updater to the latest versions from GitHub"); + response.concat("



"); + #endif + + if(_partitionType == 1) + { + response.concat("

Reboot to Nuki Hub Updater

"); + response.concat("Click on the button to reboot to the Nuki Hub updater, where you can select the latest Nuki Hub binary to update"); + response.concat("



"); + response.concat("

Update Nuki Hub Updater

"); + response.concat("Select the latest Nuki Hub updater binary to update the Nuki Hub updater"); + response.concat("
Choose the nuki_hub_updater.bin file to upload:
"); + } + else + { + response.concat("

Reboot to Nuki Hub

"); + response.concat("Click on the button to reboot to Nuki Hub"); + response.concat("


"); + response.concat("

Update Nuki Hub

"); + response.concat("Select the latest Nuki Hub binary to update Nuki Hub"); + response.concat("
Choose the nuki_hub.bin file to upload:
"); + } + response.concat("


"); + response.concat("
"); + response.concat("

GitHub


"); + response.concat(""); + response.concat("

"); + response.concat("

"); + response.concat(""); + response.concat(""); +} + +void WebCfgServer::buildOtaCompletedHtml(String &response) +{ + buildHtmlHeader(response); + + response.concat("
Over-the-air update completed.
You will be forwarded automatically.
"); + response.concat(""); + response.concat(""); +} + +void WebCfgServer::buildHtmlHeader(String &response, String additionalHeader) +{ + response.concat(""); + response.concat(""); + if(strcmp(additionalHeader.c_str(), "") != 0) response.concat(additionalHeader); + response.concat(""); + response.concat("Nuki Hub"); + + srand(millis()); +} + +void WebCfgServer::waitAndProcess(const bool blocking, const uint32_t duration) +{ + unsigned long timeout = millis() + duration; + while(millis() < timeout) + { + _server.handleClient(); + if(blocking) + { + delay(10); + } + else + { + vTaskDelay( 50 / portTICK_PERIOD_MS); + } + } +} + +void WebCfgServer::handleOtaUpload() +{ + if (_server.uri() != "/uploadota") + { + return; + } + + HTTPUpload& upload = _server.upload(); + + if(upload.filename == "") + { + Log->println("Invalid file for OTA upload"); + return; + } + + if(_partitionType == 1 && _server.header("Content-Length").toInt() > 1600000) + { + if(upload.totalSize < 2000) Log->println("Uploaded OTA file too large, are you trying to upload a Nuki Hub binary instead of a Nuki Hub updater binary?"); + return; + } + else if(_partitionType == 2 && _server.header("Content-Length").toInt() < 1600000) + { + if(upload.totalSize < 2000) Log->println("Uploaded OTA file is too small, are you trying to upload a Nuki Hub updater binary instead of a Nuki Hub binary?"); + return; + } + + if (upload.status == UPLOAD_FILE_START) + { + String filename = upload.filename; + if (!filename.startsWith("/")) + { + filename = "/" + filename; + } + _otaStartTs = millis(); + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) + esp_task_wdt_init(30, false); + #else + esp_task_wdt_config_t twdt_config = { + .timeout_ms = 30000, + .idle_core_mask = 0, + .trigger_panic = false, + }; + esp_task_wdt_init(&twdt_config); + #endif + + #ifndef NUKI_HUB_UPDATER + _network->disableAutoRestarts(); + _network->disableMqtt(); + if(_nuki != nullptr) + { + _nuki->disableWatchdog(); + } + if(_nukiOpener != nullptr) + { + _nukiOpener->disableWatchdog(); + } + #endif + Log->print("handleFileUpload Name: "); Log->println(filename); + } + else if (upload.status == UPLOAD_FILE_WRITE) + { + _transferredSize = _transferredSize + upload.currentSize; + Log->println(_transferredSize); + _ota.updateFirmware(upload.buf, upload.currentSize); + } else if (upload.status == UPLOAD_FILE_END) + { + Log->println(); + Log->print("handleFileUpload Size: "); Log->println(upload.totalSize); + } + else if(upload.status == UPLOAD_FILE_ABORTED) + { + Log->println(); + Log->println("OTA aborted, restarting ESP."); + restartEsp(RestartReason::OTAAborted); + } + else + { + Log->println(); + Log->print("OTA unknown state: "); + Log->println((int)upload.status); + restartEsp(RestartReason::OTAUnknownState); + } +} + +void WebCfgServer::buildConfirmHtml(String &response, const String &message, uint32_t redirectDelay) +{ + String delay(redirectDelay); + String header = ""; + + buildHtmlHeader(response, header); + response.concat(message); + response.concat(""); +} + +void WebCfgServer::sendCss() +{ + // escaped by https://www.cescaper.com/ + _server.sendHeader("Cache-Control", "public, max-age=3600"); + _server.send(200, "text/css", stylecss, sizeof(stylecss)); +} + +void WebCfgServer::sendFavicon() +{ + _server.sendHeader("Cache-Control", "public, max-age=604800"); + _server.send(200, "image/png", (const char*)favicon_32x32, sizeof(favicon_32x32)); +} + +#ifndef NUKI_HUB_UPDATER +void WebCfgServer::sendSettings() +{ + bool redacted = false; + bool pairing = false; + String key = _server.argName(0); + String value = _server.arg(0); + + if(key == "redacted" && value == "1") + { + redacted = true; + } + + String key2 = _server.argName(1); + String value2 = _server.arg(1); + + if(key2 == "pairing" && value2 == "1") + { + pairing = true; + } + + JsonDocument json; + String jsonPretty; + + DebugPreferences debugPreferences; + + const std::vector keysPrefs = debugPreferences.getPreferencesKeys(); + const std::vector boolPrefs = debugPreferences.getPreferencesBoolKeys(); + const std::vector redactedPrefs = debugPreferences.getPreferencesRedactedKeys(); + const std::vector bytePrefs = debugPreferences.getPreferencesByteKeys(); + const std::vector charPrefs = debugPreferences.getPreferencesCharKeys(); + + for(const auto& key : keysPrefs) + { + if(strcmp(key, preference_show_secrets) == 0) continue; + if(strcmp(key, preference_latest_version) == 0) continue; + if(strcmp(key, preference_has_mac_saved) == 0) continue; + if(strcmp(key, preference_device_id_lock) == 0) continue; + if(strcmp(key, preference_device_id_opener) == 0) continue; + if(!redacted) if(std::find(redactedPrefs.begin(), redactedPrefs.end(), key) != redactedPrefs.end()) continue; + if(std::find(charPrefs.begin(), charPrefs.end(), key) != charPrefs.end()) continue; + if(!_preferences->isKey(key)) json[key] = ""; + else if(std::find(boolPrefs.begin(), boolPrefs.end(), key) != boolPrefs.end()) json[key] = _preferences->getBool(key) ? "1" : "0"; + else + { + switch(_preferences->getType(key)) + { + case PT_I8: + json[key] = String(_preferences->getChar(key)); + break; + case PT_I16: + json[key] = String(_preferences->getShort(key)); + break; + case PT_I32: + json[key] = String(_preferences->getInt(key)); + break; + case PT_I64: + json[key] = String(_preferences->getLong64(key)); + break; + case PT_U8: + json[key] = String(_preferences->getUChar(key)); + break; + case PT_U16: + json[key] = String(_preferences->getUShort(key)); + break; + case PT_U32: + json[key] = String(_preferences->getUInt(key)); + break; + case PT_U64: + json[key] = String(_preferences->getULong64(key)); + break; + case PT_STR: + json[key] = _preferences->getString(key); + break; + default: + json[key] = _preferences->getString(key); + break; + } + } + } + + if(pairing && _preferences->getBool(preference_show_secrets)) + { + if(_nuki != nullptr) + { + unsigned char currentBleAddress[6]; + unsigned char authorizationId[4] = {0x00}; + unsigned char secretKeyK[32] = {0x00}; + uint16_t storedPincode = 0000; + Preferences nukiBlePref; + nukiBlePref.begin("NukiHub", false); + nukiBlePref.getBytes("bleAddress", currentBleAddress, 6); + nukiBlePref.getBytes("secretKeyK", secretKeyK, 32); + nukiBlePref.getBytes("authorizationId", authorizationId, 4); + nukiBlePref.getBytes("securityPinCode", &storedPincode, 2); + nukiBlePref.end(); + char text[255]; + text[0] = '\0'; + for(int i = 0 ; i < 6 ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", currentBleAddress[i]); + } + json["bleAddressLock"] = text; + memset(text, 0, sizeof(text)); + text[0] = '\0'; + for(int i = 0 ; i < 32 ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", secretKeyK[i]); + } + json["secretKeyKLock"] = text; + memset(text, 0, sizeof(text)); + text[0] = '\0'; + for(int i = 0 ; i < 4 ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", authorizationId[i]); + } + json["authorizationIdLock"] = text; + memset(text, 0, sizeof(text)); + json["securityPinCodeLock"] = storedPincode; + } + if(_nukiOpener != nullptr) + { + unsigned char currentBleAddressOpn[6]; + unsigned char authorizationIdOpn[4] = {0x00}; + unsigned char secretKeyKOpn[32] = {0x00}; + uint16_t storedPincodeOpn = 0000; + Preferences nukiBlePref; + nukiBlePref.begin("NukiHubopener", false); + nukiBlePref.getBytes("bleAddress", currentBleAddressOpn, 6); + nukiBlePref.getBytes("secretKeyK", secretKeyKOpn, 32); + nukiBlePref.getBytes("authorizationId", authorizationIdOpn, 4); + nukiBlePref.getBytes("securityPinCode", &storedPincodeOpn, 2); + nukiBlePref.end(); + char text[255]; + text[0] = '\0'; + for(int i = 0 ; i < 6 ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", currentBleAddressOpn[i]); + } + json["bleAddressOpener"] = text; + memset(text, 0, sizeof(text)); + text[0] = '\0'; + for(int i = 0 ; i < 32 ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", secretKeyKOpn[i]); + } + json["secretKeyKOpener"] = text; + memset(text, 0, sizeof(text)); + text[0] = '\0'; + for(int i = 0 ; i < 4 ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", authorizationIdOpn[i]); + } + json["authorizationIdOpener"] = text; + memset(text, 0, sizeof(text)); + json["securityPinCodeOpener"] = storedPincodeOpn; + } + } + + for(const auto& key : bytePrefs) + { + size_t storedLength = _preferences->getBytesLength(key); + if(storedLength == 0) continue; + uint8_t serialized[storedLength]; + memset(serialized, 0, sizeof(serialized)); + size_t size = _preferences->getBytes(key, serialized, sizeof(serialized)); + if(size == 0) continue; + char text[255]; + text[0] = '\0'; + for(int i = 0 ; i < size ; i++) { + size_t offset = strlen(text); + sprintf(&(text[offset]), "%02x", serialized[i]); + } + json[key] = text; + memset(text, 0, sizeof(text)); + } + + serializeJsonPretty(json, jsonPretty); + + _server.sendHeader("Content-Disposition", "attachment; filename=nuki_hub.json"); + _server.send(200, "application/json", jsonPretty); +} + bool WebCfgServer::processArgs(String& message) { bool configChanged = false; bool aclLvlChanged = false; bool clearMqttCredentials = false; bool clearCredentials = false; + bool manPairLck = false; + bool manPairOpn = false; + unsigned char currentBleAddress[6]; + unsigned char authorizationId[4] = {0x00}; + unsigned char secretKeyK[32] = {0x00}; + unsigned char pincode[2] = {0x00}; + unsigned char currentBleAddressOpn[6]; + unsigned char authorizationIdOpn[4] = {0x00}; + unsigned char secretKeyKOpn[32] = {0x00}; + uint32_t aclPrefs[17] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint32_t basicLockConfigAclPrefs[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint32_t basicOpenerConfigAclPrefs[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; @@ -430,6 +938,11 @@ bool WebCfgServer::processArgs(String& message) _preferences->putBool(preference_check_updates, (value == "1")); configChanged = true; } + else if(key == "UPDATEMQTT") + { + _preferences->putBool(preference_update_from_mqtt, (value == "1")); + configChanged = true; + } else if(key == "OFFHYBRID") { _preferences->putBool(preference_official_hybrid, (value == "1")); @@ -451,7 +964,7 @@ bool WebCfgServer::processArgs(String& message) { _preferences->putBool(preference_official_hybrid_retry, (value == "1")); configChanged = true; - } + } else if(key == "DISNONJSON") { _preferences->putBool(preference_disable_non_json, (value == "1")); @@ -575,6 +1088,21 @@ bool WebCfgServer::processArgs(String& message) _preferences->putBool(preference_enable_bootloop_reset, (value == "1")); configChanged = true; } + else if(key == "OTAUPD") + { + _preferences->putString(preference_ota_updater_url, value); + configChanged = true; + } + else if(key == "OTAMAIN") + { + _preferences->putString(preference_ota_main_url, value); + configChanged = true; + } + else if(key == "SHOWSECRETS") + { + _preferences->putBool(preference_show_secrets, (value == "1")); + configChanged = true; + } else if(key == "ACLLVLCHANGED") { aclLvlChanged = true; @@ -1032,6 +1560,7 @@ bool WebCfgServer::processArgs(String& message) message = "Nuki Lock PIN saved"; _nuki->setPin(value.toInt()); } + configChanged = true; } else if(key == "NUKIOPPIN" && _nukiOpener != nullptr) { @@ -1045,7 +1574,65 @@ bool WebCfgServer::processArgs(String& message) message = "Nuki Opener PIN saved"; _nukiOpener->setPin(value.toInt()); } + configChanged = true; } + else if(key == "LCKMANPAIR" && (value == "1")) + { + manPairLck = true; + } + else if(key == "OPNMANPAIR" && (value == "1")) + { + manPairOpn = true; + } + else if(key == "LCKBLEADDR") + { + if(value.length() == 12) for(int i=0; iprintln(F("Changing lock pairing")); + Preferences nukiBlePref; + nukiBlePref.begin("NukiHub", false); + nukiBlePref.putBytes("bleAddress", currentBleAddress, 6); + nukiBlePref.putBytes("secretKeyK", secretKeyK, 32); + nukiBlePref.putBytes("authorizationId", authorizationId, 4); + nukiBlePref.putBytes("securityPinCode", pincode, 2); + + nukiBlePref.end(); + } + + if(manPairOpn) + { + Log->println(F("Changing opener pairing")); + Preferences nukiBlePref; + nukiBlePref.begin("NukiHubopener", false); + nukiBlePref.putBytes("bleAddress", currentBleAddressOpn, 6); + nukiBlePref.putBytes("secretKeyK", secretKeyKOpn, 32); + nukiBlePref.putBytes("authorizationId", authorizationIdOpn, 4); + nukiBlePref.putBytes("securityPinCode", pincode, 2); + nukiBlePref.end(); } if(pass1 != "" && pass1 == pass2) @@ -1088,6 +1675,171 @@ bool WebCfgServer::processArgs(String& message) return configChanged; } +bool WebCfgServer::processImport(String& message) +{ + bool configChanged = false; + unsigned char currentBleAddress[6]; + unsigned char authorizationId[4] = {0x00}; + unsigned char secretKeyK[32] = {0x00}; + unsigned char currentBleAddressOpn[6]; + unsigned char authorizationIdOpn[4] = {0x00}; + unsigned char secretKeyKOpn[32] = {0x00}; + + int count = _server.args(); + + for(int index = 0; index < count; index++) + { + String postKey = _server.argName(index); + String postValue = _server.arg(index); + + if(postKey == "importjson") + { + JsonDocument doc; + + DeserializationError error = deserializeJson(doc, postValue); + if (error) + { + Log->println("Invalid JSON for import"); + message = "Invalid JSON, config not changed"; + return configChanged; + } + + DebugPreferences debugPreferences; + + const std::vector keysPrefs = debugPreferences.getPreferencesKeys(); + const std::vector boolPrefs = debugPreferences.getPreferencesBoolKeys(); + const std::vector bytePrefs = debugPreferences.getPreferencesByteKeys(); + const std::vector charPrefs = debugPreferences.getPreferencesCharKeys(); + const std::vector intPrefs = debugPreferences.getPreferencesIntKeys(); + + for(const auto& key : keysPrefs) + { + if(doc[key].isNull()) continue; + if(strcmp(key, preference_show_secrets) == 0) continue; + if(strcmp(key, preference_latest_version) == 0) continue; + if(strcmp(key, preference_has_mac_saved) == 0) continue; + if(strcmp(key, preference_device_id_lock) == 0) continue; + if(strcmp(key, preference_device_id_opener) == 0) continue; + if(std::find(charPrefs.begin(), charPrefs.end(), key) != charPrefs.end()) continue; + if(std::find(boolPrefs.begin(), boolPrefs.end(), key) != boolPrefs.end()) + { + if (doc[key].as().length() > 0) _preferences->putBool(key, (doc[key].as() == "1" ? true : false)); + else _preferences->remove(key); + continue; + } + if(std::find(intPrefs.begin(), intPrefs.end(), key) != intPrefs.end()) + { + if (doc[key].as().length() > 0) _preferences->putInt(key, doc[key].as()); + else _preferences->remove(key); + continue; + } + + if (doc[key].as().length() > 0) _preferences->putString(key, doc[key].as()); + else _preferences->remove(key); + } + + for(const auto& key : bytePrefs) + { + if(!doc[key].isNull() && doc[key].is()) + { + String value = doc[key].as(); + unsigned char tmpchar[32]; + for(int i=0; iputBytes(key, (byte*)(&tmpchar), (value.length() / 2)); + memset(tmpchar, 0, sizeof(tmpchar)); + } + } + + Preferences nukiBlePref; + nukiBlePref.begin("NukiHub", false); + + if(!doc["bleAddressLock"].isNull()) + { + if (doc["bleAddressLock"].as().length() == 12) + { + String value = doc["bleAddressLock"].as(); + for(int i=0; iremove("bleAddressLock"); + } + if(!doc["secretKeyKLock"].isNull()) + { + if (doc["secretKeyKLock"].as().length() == 64) + { + String value = doc["secretKeyKLock"].as(); + for(int i=0; iremove("secretKeyKLock"); + } + if(!doc["authorizationIdLock"].isNull()) + { + if (doc["authorizationIdLock"].as().length() == 8) + { + String value = doc["authorizationIdLock"].as(); + for(int i=0; iremove("authorizationIdLock"); + } + nukiBlePref.end(); + if(!doc["securityPinCodeLock"].isNull()) + { + if(doc["securityPinCodeLock"].as().length() > 0) _nuki->setPin(doc["securityPinCodeLock"].as()); + else _nuki->setPin(0xffff); + } + nukiBlePref.begin("NukiHubopener", false); + if(!doc["bleAddressOpener"].isNull()) + { + if (doc["bleAddressOpener"].as().length() == 12) + { + String value = doc["bleAddressOpener"].as(); + for(int i=0; iremove("bleAddressOpener"); + } + if(!doc["secretKeyKOpener"].isNull()) + { + if (doc["secretKeyKOpener"].as().length() == 64) + { + String value = doc["secretKeyKOpener"].as(); + for(int i=0; iremove("secretKeyKOpener"); + } + if(!doc["authorizationIdOpener"].isNull()) + { + if (doc["authorizationIdOpener"].as().length() == 8) + { + String value = doc["authorizationIdOpener"].as(); + for(int i=0; iremove("authorizationIdOpener"); + } + nukiBlePref.end(); + if(!doc["securityPinCodeOpener"].isNull()) + { + if(doc["securityPinCodeOpener"].as().length() > 0) _nukiOpener->setPin(doc["securityPinCodeOpener"].as()); + else _nukiOpener->setPin(0xffff); + } + + configChanged = true; + } + } + + if(configChanged) + { + message = "Configuration saved ... restarting."; + _enabled = false; + _preferences->end(); + } + + return configChanged; +} void WebCfgServer::processGpioArgs() { @@ -1113,19 +1865,32 @@ void WebCfgServer::processGpioArgs() _gpio->savePinConfiguration(pinConfiguration); } - -void WebCfgServer::update() +void WebCfgServer::buildImportExportHtml(String &response) { - if(_otaStartTs > 0 && (millis() - _otaStartTs) > 120000) - { - Log->println(F("OTA time out, restarting")); - delay(200); - restartEsp(RestartReason::OTATimeout); + buildHtmlHeader(response); + + response.concat("

Import configuration

"); + response.concat("

"); + response.concat("


"); + response.concat("
"); + response.concat("

Export configuration


"); + response.concat(""); + response.concat("

");if( _preferences->getBool(preference_show_secrets)) { + response.concat("

"); } - - if(!_enabled) return; - - _server.handleClient(); + response.concat("
Initiating config update. Please be patient.
You will be forwarded automatically when the import is complete.
"); + response.concat(""); + response.concat(""); } void WebCfgServer::buildHtml(String& response) @@ -1179,6 +1944,7 @@ void WebCfgServer::buildHtml(String& response) buildNavigationMenuEntry(response, "Credentials", "/cred", _pinsConfigured ? "" : "Please configure PIN"); buildNavigationMenuEntry(response, "GPIO Configuration", "/gpiocfg"); buildNavigationMenuEntry(response, "Firmware update", "/ota"); + buildNavigationMenuEntry(response, "Import/Export Configuration", "/impexpcfg"); // buildNavigationButton(response, "Edit", "/mqttconfig", _brokerConfigured ? "" : "(!) Please configure MQTT broker"); // buildNavigationButton(response, "Edit", "/cred", _pinsConfigured ? "" : "(!) Please configure PIN"); @@ -1274,57 +2040,6 @@ void WebCfgServer::buildCredHtml(String &response) response.concat(""); } -void WebCfgServer::buildOtaHtml(String &response, bool errored) -{ - buildHtmlHeader(response); - - if(millis() < 60000) - { - response.concat("OTA functionality not ready. Please wait a moment and reload."); - response.concat(""); - return; - } - - if (errored) { - response.concat("
Over-the-air update errored. Please check the logs for more info

"); - } - - response.concat("
Choose the updated nuki_hub.bin file to upload:
"); - response.concat("
"); - response.concat("
"); - response.concat("

"); - response.concat("
Initiating Over-the-air update. This will take about two minutes, please be patient.
You will be forwarded automatically when the update is complete.
"); - response.concat(""); - response.concat(""); -} - -void WebCfgServer::buildOtaCompletedHtml(String &response) -{ - buildHtmlHeader(response); - - response.concat("
Over-the-air update completed.
You will be forwarded automatically.
"); - response.concat(""); - response.concat(""); -} - void WebCfgServer::buildMqttConfigHtml(String &response) { buildHtmlHeader(response); @@ -1350,15 +2065,16 @@ void WebCfgServer::buildMqttConfigHtml(String &response) printCheckBox(response, "NWHWWIFIFB", "Disable fallback to Wi-Fi / Wi-Fi config portal", _preferences->getBool(preference_network_wifi_fallback_disabled), ""); printCheckBox(response, "BESTRSSI", "Connect to AP with the best signal in an environment with multiple APs with the same SSID", _preferences->getBool(preference_find_best_rssi), ""); printInputField(response, "RSSI", "RSSI Publish interval (seconds; -1 to disable)", _preferences->getInt(preference_rssi_publish_interval), 6, ""); - printInputField(response, "NETTIMEOUT", "Network Timeout until restart (seconds; -1 to disable)", _preferences->getInt(preference_network_timeout), 5, ""); + printInputField(response, "NETTIMEOUT", "MQTT Timeout until restart (seconds; -1 to disable)", _preferences->getInt(preference_network_timeout), 5, ""); printCheckBox(response, "RSTDISC", "Restart on disconnect", _preferences->getBool(preference_restart_on_disconnect), ""); printCheckBox(response, "MQTTLOG", "Enable MQTT logging", _preferences->getBool(preference_mqtt_log_enabled), ""); printCheckBox(response, "CHECKUPDATE", "Check for Firmware Updates every 24h", _preferences->getBool(preference_check_updates), ""); + printCheckBox(response, "UPDATEMQTT", "Allow updating using MQTT", _preferences->getBool(preference_update_from_mqtt), ""); printCheckBox(response, "DISNONJSON", "Disable some extraneous non-JSON topics", _preferences->getBool(preference_disable_non_json), ""); printCheckBox(response, "OFFHYBRID", "Enable hybrid official MQTT and Nuki Hub setup", _preferences->getBool(preference_official_hybrid), ""); printCheckBox(response, "HYBRIDACT", "Enable sending actions through official MQTT", _preferences->getBool(preference_official_hybrid_actions), ""); printInputField(response, "HYBRIDTIMER", "Time between status updates when official MQTT is offline (seconds)", _preferences->getInt(preference_query_interval_hybrid_lockstate), 5, ""); - printCheckBox(response, "HYBRIDRETRY", "Retry command sent using official MQTT over BLE if failed", _preferences->getBool(preference_official_hybrid_retry), ""); + printCheckBox(response, "HYBRIDRETRY", "Retry command sent using official MQTT over BLE if failed", _preferences->getBool(preference_official_hybrid_retry), ""); response.concat(""); response.concat("* If no encryption is configured for the MQTT broker, leave empty. Only supported for Wi-Fi connections.

"); @@ -1388,13 +2104,31 @@ void WebCfgServer::buildAdvancedConfigHtml(String &response) response.concat(""); printCheckBox(response, "BTLPRST", "Enable Bootloop prevention (Try to reset these settings to default on bootloop)", true, ""); printInputField(response, "BUFFSIZE", "Char buffer size (min 4096, max 32768)", _preferences->getInt(preference_buffer_size, CHAR_BUFFER_SIZE), 6, ""); + response.concat("Advised minimum char buffer size based on current settings"); printInputField(response, "TSKNTWK", "Task size Network (min 12288, max 32768)", _preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), 6, ""); + response.concat("Advised minimum network task size based on current settings"); printInputField(response, "TSKNUKI", "Task size Nuki (min 8192, max 32768)", _preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), 6, ""); printInputField(response, "ALMAX", "Max auth log entries (min 1, max 50)", _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 3, "inputmaxauthlog"); printInputField(response, "KPMAX", "Max keypad entries (min 1, max 100)", _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD), 3, "inputmaxkeypad"); printInputField(response, "TCMAX", "Max timecontrol entries (min 1, max 50)", _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL), 3, "inputmaxtimecontrol"); - response.concat("Advised minimum char buffer size based on current settings"); - response.concat("Advised minimum network task size based on current settings"); + printCheckBox(response, "SHOWSECRETS", "Show Pairing secrets on Info page (for 120s after next boot)", _preferences->getBool(preference_show_secrets), ""); + + if(_nuki != nullptr) + { + printCheckBox(response, "LCKMANPAIR", "Manually set lock pairing data (enable to save values below)", false, ""); + printInputField(response, "LCKBLEADDR", "currentBleAddress", "", 12, ""); + printInputField(response, "LCKSECRETK", "secretKeyK", "", 64, ""); + printInputField(response, "LCKAUTHID", "authorizationId", "", 8, ""); + } + if(_nukiOpener != nullptr) + { + printCheckBox(response, "OPNMANPAIR", "Manually set opener pairing data (enable to save values below)", false, ""); + printInputField(response, "OPNBLEADDR", "currentBleAddress", "", 12, ""); + printInputField(response, "OPNSECRETK", "secretKeyK", "", 64, ""); + printInputField(response, "OPNAUTHID", "authorizationId", "", 8, ""); + } + printInputField(response, "OTAUPD", "Custom URL to update Nuki Hub updater", "", 255, ""); + printInputField(response, "OTAMAIN", "Custom URL to update Nuki Hub", "", 255, ""); response.concat(""); response.concat("
"); @@ -1500,7 +2234,7 @@ void WebCfgServer::buildAccLvlHtml(String &response) { printCheckBox(response, "KPPUB", "Publish keypad entries information", _preferences->getBool(preference_keypad_info_enabled), ""); printCheckBox(response, "KPPER", "Publish a topic per keypad entry and create HA sensor", _preferences->getBool(preference_keypad_topic_per_entry), ""); - printCheckBox(response, "KPCODE", "Also publish keypad codes (Disadvised for security reasons)", _preferences->getBool(preference_keypad_publish_code, false), ""); + printCheckBox(response, "KPCODE", "Also publish keypad codes (Disadvised for security reasons)", _preferences->getBool(preference_keypad_publish_code, false), ""); printCheckBox(response, "KPENA", "Add, modify and delete keypad codes", _preferences->getBool(preference_keypad_control_enabled), ""); } printCheckBox(response, "TCPUB", "Publish time control entries information", _preferences->getBool(preference_timecontrol_info_enabled), ""); @@ -1721,16 +2455,6 @@ void WebCfgServer::buildGpioConfigHtml(String &response) response.concat(""); } -void WebCfgServer::buildConfirmHtml(String &response, const String &message, uint32_t redirectDelay) -{ - String delay(redirectDelay); - String header = ""; - - buildHtmlHeader(response, header); - response.concat(message); - response.concat(""); -} - void WebCfgServer::buildConfigureWifiHtml(String &response) { buildHtmlHeader(response); @@ -1980,6 +2704,68 @@ void WebCfgServer::buildInfoHtml(String &response) response.concat((int)advancedOpenerConfigAclPrefs[19] ? "Allowed\n" : "Disallowed\n"); } + if(_preferences->getBool(preference_show_secrets)) + { + if(_nuki != nullptr) + { + char tmp[16]; + unsigned char currentBleAddress[6]; + unsigned char authorizationId[4] = {0x00}; + unsigned char secretKeyK[32] = {0x00}; + Preferences nukiBlePref; + nukiBlePref.begin("NukiHub", false); + nukiBlePref.getBytes("bleAddress", currentBleAddress, 6); + nukiBlePref.getBytes("secretKeyK", secretKeyK, 32); + nukiBlePref.getBytes("authorizationId", authorizationId, 4); + nukiBlePref.end(); + response.concat("Lock bleAddress: "); + for (int i = 0; i < 6; i++) { + sprintf(tmp, "%02x", currentBleAddress[i]); + response.concat(tmp); + } + response.concat("\nLock secretKeyK: "); + for (int i = 0; i < 32; i++) { + sprintf(tmp, "%02x", secretKeyK[i]); + response.concat(tmp); + } + response.concat("\nLock authorizationId: "); + for (int i = 0; i < 4; i++) { + sprintf(tmp, "%02x", authorizationId[i]); + response.concat(tmp); + } + response.concat("\n"); + } + if(_nukiOpener != nullptr) + { + char tmp[16]; + unsigned char currentBleAddressOpn[6]; + unsigned char authorizationIdOpn[4] = {0x00}; + unsigned char secretKeyKOpn[32] = {0x00}; + Preferences nukiBlePref; + nukiBlePref.begin("NukiHubopener", false); + nukiBlePref.getBytes("bleAddress", currentBleAddressOpn, 6); + nukiBlePref.getBytes("secretKeyK", secretKeyKOpn, 32); + nukiBlePref.getBytes("authorizationId", authorizationIdOpn, 4); + nukiBlePref.end(); + response.concat("Opener bleAddress: "); + for (int i = 0; i < 6; i++) { + sprintf(tmp, "%02x", currentBleAddressOpn[i]); + response.concat(tmp); + } + response.concat("\nOpener secretKeyK: "); + for (int i = 0; i < 32; i++) { + sprintf(tmp, "%02x", secretKeyKOpn[i]); + response.concat(tmp); + } + response.concat("\nOpener authorizationId: "); + for (int i = 0; i < 4; i++) { + sprintf(tmp, "%02x", authorizationIdOpn[i]); + response.concat(tmp); + } + response.concat("\n"); + } + } + response.concat("Network device: "); response.concat(_network->networkDeviceName()); response.concat("\n"); @@ -2003,12 +2789,6 @@ void WebCfgServer::buildInfoHtml(String &response) response.concat(uxTaskGetStackHighWaterMark(networkTaskHandle)); response.concat(", nuki: "); response.concat(uxTaskGetStackHighWaterMark(nukiTaskHandle)); - - if(_preferences->getInt(preference_presence_detection_timeout) >= 0) - { - response.concat(", pd: "); - response.concat(uxTaskGetStackHighWaterMark(presenceDetectionTaskHandle)); - } response.concat("\n"); _gpio->getConfigurationText(response, _gpio->pinConfiguration()); @@ -2125,17 +2905,6 @@ void WebCfgServer::processFactoryReset() restartEsp(RestartReason::NukiHubReset); } -void WebCfgServer::buildHtmlHeader(String &response, String additionalHeader) -{ - response.concat(""); - response.concat(""); - if(strcmp(additionalHeader.c_str(), "") != 0) response.concat(additionalHeader); - response.concat(""); - response.concat("Nuki Hub"); - - srand(millis()); -} - void WebCfgServer::printInputField(String& response, const char *token, const char *description, @@ -2162,14 +2931,17 @@ void WebCfgServer::printInputField(String& response, response.concat(""); response.concat(""); - for(const auto option : options) + for(const auto& option : options) { if(option.first == preselectedValue) { @@ -2339,101 +3111,6 @@ String WebCfgServer::generateConfirmCode() return String(code); } -void WebCfgServer::waitAndProcess(const bool blocking, const uint32_t duration) -{ - unsigned long timeout = millis() + duration; - while(millis() < timeout) - { - _server.handleClient(); - if(blocking) - { - delay(10); - } - else - { - vTaskDelay( 50 / portTICK_PERIOD_MS); - } - } -} - -void WebCfgServer::handleOtaUpload() -{ - if (_server.uri() != "/uploadota") - { - return; - } - if(millis() < 60000) - { - return; - } - - HTTPUpload& upload = _server.upload(); - - if(upload.filename == "") - { - Log->println("Invalid file for OTA upload"); - return; - } - - if (upload.status == UPLOAD_FILE_START) - { - String filename = upload.filename; - if (!filename.startsWith("/")) - { - filename = "/" + filename; - } - _otaStartTs = millis(); - esp_task_wdt_init(30, false); - _network->disableAutoRestarts(); - _network->disableMqtt(); - if(_nuki != nullptr) - { - _nuki->disableWatchdog(); - } - if(_nukiOpener != nullptr) - { - _nukiOpener->disableWatchdog(); - } - Log->print("handleFileUpload Name: "); Log->println(filename); - } - else if (upload.status == UPLOAD_FILE_WRITE) - { - _transferredSize = _transferredSize + upload.currentSize; - Log->println(_transferredSize); - _ota.updateFirmware(upload.buf, upload.currentSize); - } else if (upload.status == UPLOAD_FILE_END) - { - Log->println(); - Log->print("handleFileUpload Size: "); Log->println(upload.totalSize); - } - else if(upload.status == UPLOAD_FILE_ABORTED) - { - Log->println(); - Log->println("OTA aborted, restarting ESP."); - restartEsp(RestartReason::OTAAborted); - } - else - { - Log->println(); - Log->print("OTA unknown state: "); - Log->println((int)upload.status); - restartEsp(RestartReason::OTAUnknownState); - } -} - -void WebCfgServer::sendCss() -{ - // escaped by https://www.cescaper.com/ - _server.sendHeader("Cache-Control", "public, max-age=3600"); - _server.send(200, "text/css", stylecss, sizeof(stylecss)); -} - -void WebCfgServer::sendFavicon() -{ - _server.sendHeader("Cache-Control", "public, max-age=604800"); - _server.send(200, "image/png", (const char*)favicon_32x32, sizeof(favicon_32x32)); -} - const std::vector> WebCfgServer::getNetworkDetectionOptions() const { std::vector> options; @@ -2446,7 +3123,7 @@ const std::vector> WebCfgServer::getNetworkDetectionOp options.push_back(std::make_pair("6", "M5STACK PoESP32 Unit")); options.push_back(std::make_pair("7", "LilyGO T-ETH-POE")); options.push_back(std::make_pair("8", "GL-S10")); - + return options; } @@ -2478,3 +3155,4 @@ String WebCfgServer::getPreselectionForGpio(const uint8_t &pin) return String((int8_t)PinRole::Disabled); } +#endif \ No newline at end of file diff --git a/src/WebCfgServer.h b/src/WebCfgServer.h index 40df2a7..eddf90d 100644 --- a/src/WebCfgServer.h +++ b/src/WebCfgServer.h @@ -2,15 +2,15 @@ #include #include -#include "NukiWrapper.h" -#include "NetworkLock.h" -#include "NukiOpenerWrapper.h" #include "Ota.h" + +#ifndef NUKI_HUB_UPDATER +#include "NukiWrapper.h" +#include "NukiNetworkLock.h" +#include "NukiOpenerWrapper.h" #include "Gpio.h" -extern TaskHandle_t networkTaskHandle; extern TaskHandle_t nukiTaskHandle; -extern TaskHandle_t presenceDetectionTaskHandle; enum class TokenType { @@ -24,36 +24,44 @@ enum class TokenType QueryIntervalBattery, }; +#else +#include "NukiNetwork.h" +#endif + +extern TaskHandle_t networkTaskHandle; + class WebCfgServer { public: - WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, Network* network, Gpio* gpio, EthServer* ethServer, Preferences* preferences, bool allowRestartToPortal); + #ifndef NUKI_HUB_UPDATER + WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, EthServer* ethServer, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType); + #else + WebCfgServer(NukiNetwork* network, EthServer* ethServer, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType); + #endif ~WebCfgServer() = default; void initialize(); void update(); private: + #ifndef NUKI_HUB_UPDATER + void sendSettings(); bool processArgs(String& message); + bool processImport(String& message); void processGpioArgs(); void buildHtml(String& response); void buildAccLvlHtml(String& response); void buildCredHtml(String& response); - void buildOtaHtml(String& response, bool errored); - void buildOtaCompletedHtml(String& response); + void buildImportExportHtml(String& response); void buildMqttConfigHtml(String& response); void buildStatusHtml(String& response); void buildAdvancedConfigHtml(String& response); void buildNukiConfigHtml(String& response); void buildGpioConfigHtml(String& response); - void buildConfirmHtml(String& response, const String &message, uint32_t redirectDelay = 5); void buildConfigureWifiHtml(String& response); void buildInfoHtml(String& response); - void sendCss(); - void sendFavicon(); void processUnpair(bool opener); void processFactoryReset(); - void buildHtmlHeader(String& response, String additionalHeader = ""); void printInputField(String& response, const char* token, const char* description, const char* value, const size_t& maxLength, const char* id, const bool& isPassword = false, const bool& showLengthRestriction = false); void printInputField(String& response, const char* token, const char* description, const int value, size_t maxLength, const char* id); void printCheckBox(String& response, const char* token, const char* description, const bool value, const char* htmlClass); @@ -70,14 +78,26 @@ private: void printParameter(String& response, const char* description, const char* value, const char *link = "", const char *id = ""); String generateConfirmCode(); + + NukiWrapper* _nuki = nullptr; + NukiOpenerWrapper* _nukiOpener = nullptr; + Gpio* _gpio = nullptr; + bool _pinsConfigured = false; + bool _brokerConfigured = false; + String _confirmCode = "----"; + #endif + + void buildConfirmHtml(String& response, const String &message, uint32_t redirectDelay = 5); + void buildOtaHtml(String& response, bool errored); + void buildOtaCompletedHtml(String& response); + void sendCss(); + void sendFavicon(); + void buildHtmlHeader(String& response, String additionalHeader = ""); void waitAndProcess(const bool blocking, const uint32_t duration); void handleOtaUpload(); WebServer _server; - NukiWrapper* _nuki = nullptr; - NukiOpenerWrapper* _nukiOpener = nullptr; - Network* _network = nullptr; - Gpio* _gpio = nullptr; + NukiNetwork* _network = nullptr; Preferences* _preferences = nullptr; Ota _ota; @@ -85,13 +105,9 @@ private: char _credUser[31] = {0}; char _credPassword[31] = {0}; bool _allowRestartToPortal = false; - bool _pinsConfigured = false; - bool _brokerConfigured = false; + uint8_t _partitionType = 0; uint32_t _transferredSize = 0; unsigned long _otaStartTs = 0; String _hostname; - - String _confirmCode = "----"; - bool _enabled = true; }; diff --git a/src/WebCfgServerConstants.h b/src/WebCfgServerConstants.h index 4ed2a2a..41bcb28 100644 --- a/src/WebCfgServerConstants.h +++ b/src/WebCfgServerConstants.h @@ -3,7 +3,7 @@ // escaped by https://www.cescaper.com/ // source: https://cdn.jsdelivr.net/npm/@exampledev/new.css@1.1.2/new.min.css -const char stylecss[] = ":root{--nc-font-sans:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Open Sans','Helvetica Neue',sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol';--nc-font-mono:Consolas,monaco,'Ubuntu Mono','Liberation Mono','Courier New',Courier,monospace;--nc-tx-1:#000;--nc-tx-2:#1a1a1a;--nc-bg-1:#fff;--nc-bg-2:#f6f8fa;--nc-bg-3:#e5e7eb;--nc-lk-1:#0070f3;--nc-lk-2:#0366d6;--nc-lk-tx:#fff;--nc-ac-1:#79ffe1;--nc-ac-tx:#0c4047}@media(prefers-color-scheme:dark){:root{--nc-tx-1:#fff;--nc-tx-2:#eee;--nc-bg-1:#000;--nc-bg-2:#111;--nc-bg-3:#222;--nc-lk-1:#3291ff;--nc-lk-2:#0070f3;--nc-lk-tx:#fff;--nc-ac-1:#7928ca;--nc-ac-tx:#fff}}*{margin:0;padding:0}img,input,option,p,table,textarea,ul{margin-bottom:1rem}button,html,input,select{font-family:var(--nc-font-sans)}body{margin:0 auto;max-width:750px;padding:2rem;border-radius:6px;overflow-x:hidden;word-break:normal;overflow-wrap:anywhere;background:var(--nc-bg-1);color:var(--nc-tx-2);font-size:1.03rem;line-height:1.5}::selection{background:var(--nc-ac-1);color:var(--nc-ac-tx)}h1,h2,h3,h4,h5,h6{line-height:1;color:var(--nc-tx-1);padding-top:.875rem}h1,h2,h3{color:var(--nc-tx-1);padding-bottom:2px;margin-bottom:8px;border-bottom:1px solid var(--nc-bg-2)}h4,h5,h6{margin-bottom:.3rem}h1{font-size:2.25rem}h2{font-size:1.85rem}h3{font-size:1.55rem}h4{font-size:1.25rem}h5{font-size:1rem}h6{font-size:.875rem}a{color:var(--nc-lk-1)}a:hover{color:var(--nc-lk-2)}abbr{cursor:help}abbr:hover{cursor:help}a button,button,input[type=button],input[type=reset],input[type=submit]{font-size:1rem;display:inline-block;padding:6px 12px;text-align:center;text-decoration:none;white-space:nowrap;background:var(--nc-lk-1);color:var(--nc-lk-tx);border:0;border-radius:4px;box-sizing:border-box;cursor:pointer;color:var(--nc-lk-tx)}a button[disabled],button[disabled],input[type=button][disabled],input[type=reset][disabled],input[type=submit][disabled]{cursor:default;opacity:.5;cursor:not-allowed}.button:focus,.button:hover,button:focus,button:hover,input[type=button]:focus,input[type=button]:hover,input[type=reset]:focus,input[type=reset]:hover,input[type=submit]:focus,input[type=submit]:hover{background:var(--nc-lk-2)}table{border-collapse:collapse;width:100%}td,th{border:1px solid var(--nc-bg-3);text-align:left;padding:.5rem}th{background:var(--nc-bg-2)}tr:nth-child(even){background:var(--nc-bg-2)}textarea{max-width:100%}input,select,textarea{padding:6px 12px;margin-bottom:.5rem;background:var(--nc-bg-2);color:var(--nc-tx-2);border:1px solid var(--nc-bg-3);border-radius:4px;box-shadow:none;box-sizing:border-box}img{max-width:100%}td>input{margin-top:0;margin-bottom:0}td>textarea{margin-top:0;margin-bottom:0}td>select{margin-top:0;margin-bottom:0}.warning{color:red}@media only screen and (max-width:600px){.adapt td{display:block}.adapt input[type=text],.adapt input[type=password],.adapt input[type=submit],.adapt textarea,.adapt select{width:100%}.adapt td:has(input[type=checkbox]){text-align:center}.adapt input[type=checkbox]{width:1.5em;height:1.5em}.adapt table td:first-child{border-bottom:0}.adapt table td:last-child{border-top:0}#tblnav a li>span{max-width:140px}}#tblnav a{border:0;border-bottom:1px solid;display:block;font-size:1rem;font-weight:bold;padding:.6rem 0;line-height:1;color:var(--nc-tx-1);text-decoration:none;background:linear-gradient(to left,transparent 50%,rgba(255,255,255,0.4) 50%) right;background-size:200% 100%;transition:all .2s ease}#tblnav a:nth-child(even){background:linear-gradient(to left,var(--nc-bg-2) 50%,rgba(255,255,255,0.4) 50%) right;background-size:200% 100%}#tblnav a:hover{background-position:left;transition:all .45s ease}#tblnav a:active{background:var(--nc-lk-1);transition:all .15s ease}#tblnav a li{list-style:none;padding:.5rem;display:inline-block;width:100%}#tblnav a li>span{float:right;text-align:right;margin-right:10px;color:#f70;font-weight:100;font-style:italic;display:block}.tdbtn{text-align:center;vertical-align:middle}"; +const char stylecss[] = ":root{--nc-font-sans:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Open Sans','Helvetica Neue',sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol';--nc-font-mono:Consolas,monaco,'Ubuntu Mono','Liberation Mono','Courier New',Courier,monospace;--nc-tx-1:#000;--nc-tx-2:#1a1a1a;--nc-bg-1:#fff;--nc-bg-2:#f6f8fa;--nc-bg-3:#e5e7eb;--nc-lk-1:#0070f3;--nc-lk-2:#0366d6;--nc-lk-tx:#fff;--nc-ac-1:#79ffe1;--nc-ac-tx:#0c4047}@media(prefers-color-scheme:dark){:root{--nc-tx-1:#fff;--nc-tx-2:#eee;--nc-bg-1:#000;--nc-bg-2:#111;--nc-bg-3:#222;--nc-lk-1:#3291ff;--nc-lk-2:#0070f3;--nc-lk-tx:#fff;--nc-ac-1:#7928ca;--nc-ac-tx:#fff}}*{margin:0;padding:0}img,input,option,p,table,textarea,ul{margin-bottom:1rem}button,html,input,select{font-family:var(--nc-font-sans)}body{margin:0 auto;max-width:750px;padding:2rem;border-radius:6px;overflow-x:hidden;word-break:normal;overflow-wrap:anywhere;background:var(--nc-bg-1);color:var(--nc-tx-2);font-size:1.03rem;line-height:1.5}::selection{background:var(--nc-ac-1);color:var(--nc-ac-tx)}h1,h2,h3,h4,h5,h6{line-height:1;color:var(--nc-tx-1);padding-top:.875rem}h1,h2,h3{color:var(--nc-tx-1);padding-bottom:2px;margin-bottom:8px;border-bottom:1px solid var(--nc-bg-2)}h4,h5,h6{margin-bottom:.3rem}h1{font-size:2.25rem}h2{font-size:1.85rem}h3{font-size:1.55rem}h4{font-size:1.25rem}h5{font-size:1rem}h6{font-size:.875rem}a{color:var(--nc-lk-1)}a:hover{color:var(--nc-lk-2) !important;}abbr{cursor:help}abbr:hover{cursor:help}a button,button,input[type=button],input[type=reset],input[type=submit]{font-size:1rem;display:inline-block;padding:6px 12px;text-align:center;text-decoration:none;white-space:nowrap;background:var(--nc-lk-1);color:var(--nc-lk-tx);border:0;border-radius:4px;box-sizing:border-box;cursor:pointer;color:var(--nc-lk-tx)}a button[disabled],button[disabled],input[type=button][disabled],input[type=reset][disabled],input[type=submit][disabled]{cursor:default;opacity:.5;cursor:not-allowed}.button:focus,.button:hover,button:focus,button:hover,input[type=button]:focus,input[type=button]:hover,input[type=reset]:focus,input[type=reset]:hover,input[type=submit]:focus,input[type=submit]:hover{background:var(--nc-lk-2)}table{border-collapse:collapse;width:100%}td,th{border:1px solid var(--nc-bg-3);text-align:left;padding:.5rem}th{background:var(--nc-bg-2)}tr:nth-child(even){background:var(--nc-bg-2)}textarea{max-width:100%}input,select,textarea{padding:6px 12px;margin-bottom:.5rem;background:var(--nc-bg-2);color:var(--nc-tx-2);border:1px solid var(--nc-bg-3);border-radius:4px;box-shadow:none;box-sizing:border-box}img{max-width:100%}td>input{margin-top:0;margin-bottom:0}td>textarea{margin-top:0;margin-bottom:0}td>select{margin-top:0;margin-bottom:0}.warning{color:red}@media only screen and (max-width:600px){.adapt td{display:block}.adapt input[type=text],.adapt input[type=password],.adapt input[type=submit],.adapt textarea,.adapt select{width:100%}.adapt td:has(input[type=checkbox]){text-align:center}.adapt input[type=checkbox]{width:1.5em;height:1.5em}.adapt table td:first-child{border-bottom:0}.adapt table td:last-child{border-top:0}#tblnav a li>span{max-width:140px}}#tblnav a{border:0;border-bottom:1px solid;display:block;font-size:1rem;font-weight:bold;padding:.6rem 0;line-height:1;color:var(--nc-tx-1);text-decoration:none;background:linear-gradient(to left,transparent 50%,rgba(255,255,255,0.4) 50%) right;background-size:200% 100%;transition:all .2s ease}#tblnav a:nth-child(even){background:linear-gradient(to left,var(--nc-bg-2) 50%,rgba(255,255,255,0.4) 50%) right;background-size:200% 100%}#tblnav a:hover{background-position:left;transition:all .45s ease}#tblnav a:active{background:var(--nc-lk-1);transition:all .15s ease}#tblnav a li{list-style:none;padding:.5rem;display:inline-block;width:100%}#tblnav a li>span{float:right;text-align:right;margin-right:10px;color:#f70;font-weight:100;font-style:italic;display:block}.tdbtn{text-align:center;vertical-align:middle}"; // converted to char array by https://notisrac.github.io/FileToCArray/ const unsigned char favicon_32x32[] = { diff --git a/src/main.cpp b/src/main.cpp index e75f741..90f4861 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,40 +1,62 @@ -#include "Arduino.h" -#include "NukiWrapper.h" -#include "NetworkLock.h" -#include "WebCfgServer.h" -#include -#include "PreferencesKeys.h" -#include "PresenceDetection.h" -#include "hardware/W5500EthServer.h" -#include "hardware/WifiEthServer.h" -#include "NukiOpenerWrapper.h" -#include "Gpio.h" -#include "Logger.h" -#include "Config.h" -#include "RestartReason.h" -#include "CharBuffer.h" -#include "NukiDeviceId.h" - #define IS_VALID_DETECT 0xa00ab00bc00bd00d; -Network* network = nullptr; -NetworkLock* networkLock = nullptr; -NetworkOpener* networkOpener = nullptr; -WebCfgServer* webCfgServer = nullptr; +#include "Arduino.h" +#include "hardware/W5500EthServer.h" +#include "hardware/WifiEthServer.h" +#include "esp_crt_bundle.h" +#include "esp_ota_ops.h" +#include "esp_http_client.h" +#include "esp_https_ota.h" +#include "Config.h" + +#ifndef NUKI_HUB_UPDATER +#include "NukiWrapper.h" +#include "NukiNetworkLock.h" +#include "PresenceDetection.h" +#include "NukiOpenerWrapper.h" +#include "Gpio.h" +#include "CharBuffer.h" +#include "NukiDeviceId.h" +#include "WebCfgServer.h" +#include "Logger.h" +#include "PreferencesKeys.h" +#include "RestartReason.h" + +NukiNetworkLock* networkLock = nullptr; +NukiNetworkOpener* networkOpener = nullptr; BleScanner::Scanner* bleScanner = nullptr; NukiWrapper* nuki = nullptr; NukiOpenerWrapper* nukiOpener = nullptr; PresenceDetection* presenceDetection = nullptr; NukiDeviceId* deviceIdLock = nullptr; NukiDeviceId* deviceIdOpener = nullptr; -Preferences* preferences = nullptr; -EthServer* ethServer = nullptr; Gpio* gpio = nullptr; bool lockEnabled = false; bool openerEnabled = false; + +TaskHandle_t nukiTaskHandle = nullptr; +TaskHandle_t presenceDetectionTaskHandle = nullptr; + unsigned long restartTs = (2^32) - 5 * 60000; +#else +#include "../../src/WebCfgServer.h" +#include "../../src/Logger.h" +#include "../../src/PreferencesKeys.h" +#include "../../src/Config.h" +#include "../../src/RestartReason.h" +#include "../../src/NukiNetwork.h" + +unsigned long restartTs = 10 * 60000; + +#endif + +NukiNetwork* network = nullptr; +WebCfgServer* webCfgServer = nullptr; +Preferences* preferences = nullptr; +EthServer* ethServer = nullptr; + RTC_NOINIT_ATTR int restartReason; RTC_NOINIT_ATTR uint64_t restartReasonValidDetect; RTC_NOINIT_ATTR bool rebuildGpioRequested; @@ -45,9 +67,8 @@ RTC_NOINIT_ATTR int8_t bootloopCounter; bool restartReason_isValid; RestartReason currentRestartReason = RestartReason::NotApplicable; +TaskHandle_t otaTaskHandle = nullptr; TaskHandle_t networkTaskHandle = nullptr; -TaskHandle_t nukiTaskHandle = nullptr; -TaskHandle_t presenceDetectionTaskHandle = nullptr; void networkTask(void *pvParameters) { @@ -61,6 +82,8 @@ void networkTask(void *pvParameters) } bool connected = network->update(); + + #ifndef NUKI_HUB_UPDATER if(connected && openerEnabled) { networkOpener->update(); @@ -70,6 +93,9 @@ void networkTask(void *pvParameters) { webCfgServer->update(); } + #else + webCfgServer->update(); + #endif // millis() is about to overflow. Restart device to prevent problems with overflow if(millis() > restartTs) @@ -80,16 +106,10 @@ void networkTask(void *pvParameters) } delay(100); - -// if(wmts < millis()) -// { -// Serial.print("# "); -// Serial.println(uxTaskGetStackHighWaterMark(NULL)); -// wmts = millis() + 60000; -// } } } +#ifndef NUKI_HUB_UPDATER void nukiTask(void *pvParameters) { while(true) @@ -115,13 +135,120 @@ void nukiTask(void *pvParameters) } } +#endif -void setupTasks() +uint8_t checkPartition() +{ + const esp_partition_t* running_partition = esp_ota_get_running_partition(); + Log->print(F("Partition size: ")); + Log->println(running_partition->size); + Log->print(F("Partition subtype: ")); + Log->println(running_partition->subtype); + + if(running_partition->size == 1966080) return 0; //OLD PARTITION TABLE + else if(running_partition->subtype == ESP_PARTITION_SUBTYPE_APP_OTA_0) return 1; //NEW PARTITION TABLE, RUNNING MAIN APP + else return 2; //NEW PARTITION TABLE, RUNNING UPDATER APP +} + +esp_err_t _http_event_handler(esp_http_client_event_t *evt) +{ + switch (evt->event_id) { + case HTTP_EVENT_ERROR: + Log->println("HTTP_EVENT_ERROR"); + break; + case HTTP_EVENT_ON_CONNECTED: + Log->println("HTTP_EVENT_ON_CONNECTED"); + break; + case HTTP_EVENT_HEADER_SENT: + Log->println("HTTP_EVENT_HEADER_SENT"); + break; + case HTTP_EVENT_ON_HEADER: + Log->println("HTTP_EVENT_ON_HEADER"); + break; + case HTTP_EVENT_ON_DATA: + Log->println("HTTP_EVENT_ON_DATA"); + break; + case HTTP_EVENT_ON_FINISH: + Log->println("HTTP_EVENT_ON_FINISH"); + break; + case HTTP_EVENT_DISCONNECTED: + Log->println("HTTP_EVENT_DISCONNECTED"); + break; + #if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) + case HTTP_EVENT_REDIRECT: + Log->println("HTTP_EVENT_REDIRECT"); + break; + #endif + } + return ESP_OK; +} + +#if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) +void otaTask(void *pvParameter) +{ + uint8_t partitionType = checkPartition(); + String updateUrl; + + if(partitionType==1) + { + updateUrl = preferences->getString(preference_ota_updater_url); + preferences->putString(preference_ota_updater_url, ""); + } + else + { + updateUrl = preferences->getString(preference_ota_main_url); + preferences->putString(preference_ota_main_url, ""); + } + Log->println("Starting OTA task"); + esp_http_client_config_t config = { + .url = updateUrl.c_str(), + .event_handler = _http_event_handler, + .crt_bundle_attach = esp_crt_bundle_attach, + .keep_alive_enable = true, + }; + + esp_https_ota_config_t ota_config = { + .http_config = &config, + }; + Log->print(F("Attempting to download update from ")); + Log->println(config.url); + esp_err_t ret = esp_https_ota(&ota_config); + if (ret == ESP_OK) { + Log->println("OTA Succeeded, Rebooting..."); + esp_ota_set_boot_partition(esp_ota_get_next_update_partition(NULL)); + restartEsp(RestartReason::OTACompleted); + } else { + Log->println("Firmware upgrade failed"); + restartEsp(RestartReason::OTAAborted); + } + while (1) { + vTaskDelay(1000 / portTICK_PERIOD_MS); + } +} +#endif + +void setupTasks(bool ota) { // configMAX_PRIORITIES is 25 - xTaskCreatePinnedToCore(networkTask, "ntw", preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), NULL, 3, &networkTaskHandle, 1); - xTaskCreatePinnedToCore(nukiTask, "nuki", preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), NULL, 2, &nukiTaskHandle, 1); + if(ota) + { + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) + xTaskCreatePinnedToCore(networkTask, "ntw", preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), NULL, 3, &networkTaskHandle, 1); + #ifndef NUKI_HUB_UPDATER + xTaskCreatePinnedToCore(nukiTask, "nuki", preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), NULL, 2, &nukiTaskHandle, 1); + #endif + #else + xTaskCreatePinnedToCore(otaTask, "ota", 8192, NULL, 2, &otaTaskHandle, 1); + #endif + } + else + { + xTaskCreatePinnedToCore(networkTask, "ntw", preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), NULL, 3, &networkTaskHandle, 1); + #ifndef NUKI_HUB_UPDATER + xTaskCreatePinnedToCore(nukiTask, "nuki", preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), NULL, 2, &nukiTaskHandle, 1); + #endif + } } void initEthServer(const NetworkDeviceType device) @@ -145,24 +272,22 @@ bool initPreferences() preferences = new Preferences(); preferences->begin("nukihub", false); -// preferences->putBool(preference_network_wifi_fallback_disabled, false); - + #ifndef NUKI_HUB_UPDATER bool firstStart = !preferences->getBool(preference_started_before); if(firstStart) { preferences->putBool(preference_started_before, true); preferences->putBool(preference_lock_enabled, true); - preferences->putBool(preference_conf_info_enabled, true); uint32_t aclPrefs[17] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; preferences->putBytes(preference_acl, (byte*)(&aclPrefs), sizeof(aclPrefs)); - uint32_t basicLockConfigAclPrefs[16] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + uint32_t basicLockConfigAclPrefs[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; preferences->putBytes(preference_conf_lock_basic_acl, (byte*)(&basicLockConfigAclPrefs), sizeof(basicLockConfigAclPrefs)); - uint32_t basicOpenerConfigAclPrefs[14] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + uint32_t basicOpenerConfigAclPrefs[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; preferences->putBytes(preference_conf_opener_basic_acl, (byte*)(&basicOpenerConfigAclPrefs), sizeof(basicOpenerConfigAclPrefs)); - uint32_t advancedLockConfigAclPrefs[22] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + uint32_t advancedLockConfigAclPrefs[22] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; preferences->putBytes(preference_conf_lock_advanced_acl, (byte*)(&advancedLockConfigAclPrefs), sizeof(advancedLockConfigAclPrefs)); - uint32_t advancedOpenerConfigAclPrefs[20] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + uint32_t advancedOpenerConfigAclPrefs[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; preferences->putBytes(preference_conf_opener_advanced_acl, (byte*)(&advancedOpenerConfigAclPrefs), sizeof(advancedOpenerConfigAclPrefs)); } else @@ -182,7 +307,7 @@ bool initPreferences() preferences->putBool(preference_keypad_info_enabled, false); } - switch(preferences->getInt(preference_access_level)) + switch(preferences->getInt(preference_access_level, 10)) { case 0: { @@ -244,6 +369,21 @@ bool initPreferences() preferences->putBytes(preference_conf_opener_advanced_acl, (byte*)(&advancedOpenerConfigAclPrefs), sizeof(advancedOpenerConfigAclPrefs)); break; } + default: + { + preferences->putBool(preference_keypad_control_enabled, true); + uint32_t aclPrefs[17] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + preferences->putBytes(preference_acl, (byte*)(&aclPrefs), sizeof(aclPrefs)); + uint32_t basicLockConfigAclPrefs[16] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + preferences->putBytes(preference_conf_lock_basic_acl, (byte*)(&basicLockConfigAclPrefs), sizeof(basicLockConfigAclPrefs)); + uint32_t basicOpenerConfigAclPrefs[14] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + preferences->putBytes(preference_conf_opener_basic_acl, (byte*)(&basicOpenerConfigAclPrefs), sizeof(basicOpenerConfigAclPrefs)); + uint32_t advancedLockConfigAclPrefs[22] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + preferences->putBytes(preference_conf_lock_advanced_acl, (byte*)(&advancedLockConfigAclPrefs), sizeof(advancedLockConfigAclPrefs)); + uint32_t advancedOpenerConfigAclPrefs[20] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + preferences->putBytes(preference_conf_opener_advanced_acl, (byte*)(&advancedOpenerConfigAclPrefs), sizeof(advancedOpenerConfigAclPrefs)); + break; + } } } @@ -252,6 +392,9 @@ bool initPreferences() } return firstStart; + #else + return false; + #endif } void bootloopDetection() @@ -297,19 +440,30 @@ void setup() Serial.begin(115200); Log = &Serial; - Log->print(F("Nuki Hub version ")); Log->println(NUKI_HUB_VERSION); - Log->print(F("Nuki Hub build ")); Log->println(NUKI_HUB_BUILD); - bool firstStart = initPreferences(); preferences->remove(preference_bootloop_counter); + uint8_t partitionType = checkPartition(); initializeRestartReason(); - + if(preferences->getBool(preference_enable_bootloop_reset, false)) { bootloopDetection(); } + #ifdef NUKI_HUB_UPDATER + Log->print(F("Nuki Hub OTA version ")); Log->println(NUKI_HUB_VERSION); + Log->print(F("Nuki Hub OTA build ")); Log->println(NUKI_HUB_BUILD); + + network = new NukiNetwork(preferences); + network->initialize(); + initEthServer(network->networkDeviceType()); + webCfgServer = new WebCfgServer(network, ethServer, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType); + webCfgServer->initialize(); + #else + Log->print(F("Nuki Hub version ")); Log->println(NUKI_HUB_VERSION); + Log->print(F("Nuki Hub build ")); Log->println(NUKI_HUB_BUILD); + uint32_t devIdOpener = preferences->getUInt(preference_device_id_opener); deviceIdLock = new NukiDeviceId(preferences, preference_device_id_lock); @@ -319,16 +473,11 @@ void setup() { deviceIdOpener->assignId(deviceIdLock->get()); } - + char16_t buffer_size = preferences->getInt(preference_buffer_size, 4096); CharBuffer::initialize(buffer_size); - if(preferences->getInt(preference_restart_timer) != 0) - { - preferences->remove(preference_restart_timer); - } - gpio = new Gpio(preferences); String gpioDesc; gpio->getConfigurationText(gpioDesc, gpio->pinConfiguration(), "\n\r"); @@ -340,7 +489,7 @@ void setup() if(preferences->getInt(preference_presence_detection_timeout) >= 0) { - presenceDetection = new PresenceDetection(preferences, bleScanner, CharBuffer::get(), CHAR_BUFFER_SIZE); + presenceDetection = new PresenceDetection(preferences, bleScanner, CharBuffer::get(), buffer_size); presenceDetection->initialize(); } @@ -348,15 +497,16 @@ void setup() openerEnabled = preferences->getBool(preference_opener_enabled); const String mqttLockPath = preferences->getString(preference_mqtt_lock_path); - network = new Network(preferences, presenceDetection, gpio, mqttLockPath, CharBuffer::get(), buffer_size); + + network = new NukiNetwork(preferences, presenceDetection, gpio, mqttLockPath, CharBuffer::get(), buffer_size); network->initialize(); - networkLock = new NetworkLock(network, preferences, CharBuffer::get(), buffer_size); + networkLock = new NukiNetworkLock(network, preferences, CharBuffer::get(), buffer_size); networkLock->initialize(); if(openerEnabled) { - networkOpener = new NetworkOpener(network, preferences, CharBuffer::get(), buffer_size); + networkOpener = new NukiNetworkOpener(network, preferences, CharBuffer::get(), buffer_size); networkOpener->initialize(); } @@ -378,14 +528,24 @@ void setup() if(preferences->getBool(preference_webserver_enabled, true)) { - webCfgServer = new WebCfgServer(nuki, nukiOpener, network, gpio, ethServer, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi); + webCfgServer = new WebCfgServer(nuki, nukiOpener, network, gpio, ethServer, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType); webCfgServer->initialize(); } + #endif - setupTasks(); + if((partitionType==1 && preferences->getString(preference_ota_updater_url).length() > 0) || (partitionType==2 && preferences->getString(preference_ota_main_url).length() > 0)) setupTasks(true); + else setupTasks(false); } void loop() { vTaskDelete(NULL); +} + +void printBeforeSetupInfo() +{ +} + +void printAfterSetupInfo() +{ } \ No newline at end of file diff --git a/src/networkDevices/EthLan8720Device.cpp b/src/networkDevices/EthLan8720Device.cpp index d5018c9..8f66aaf 100644 --- a/src/networkDevices/EthLan8720Device.cpp +++ b/src/networkDevices/EthLan8720Device.cpp @@ -6,8 +6,10 @@ #include "EthLan8720Device.h" #include "../PreferencesKeys.h" #include "../Logger.h" +#ifndef NUKI_HUB_UPDATER #include "../MqttTopics.h" #include "espMqttClient.h" +#endif #include "../RestartReason.h" EthLan8720Device::EthLan8720Device(const String& hostname, Preferences* preferences, const IPConfiguration* ipConfiguration, const std::string& deviceName, uint8_t phy_addr, int power, int mdc, int mdio, eth_phy_type_t ethtype, eth_clock_mode_t clock_mode, bool use_mac_from_efuse) @@ -23,6 +25,7 @@ EthLan8720Device::EthLan8720Device(const String& hostname, Preferences* preferen { _restartOnDisconnect = preferences->getBool(preference_restart_on_disconnect); + #ifndef NUKI_HUB_UPDATER size_t caLength = preferences->getString(preference_mqtt_ca, _ca, TLS_CA_MAX_SIZE); size_t crtLength = preferences->getString(preference_mqtt_crt, _cert, TLS_CERT_MAX_SIZE); size_t keyLength = preferences->getString(preference_mqtt_key, _key, TLS_KEY_MAX_SIZE); @@ -59,6 +62,7 @@ EthLan8720Device::EthLan8720Device(const String& hostname, Preferences* preferen strcpy(_path, pathStr.c_str()); Log = new MqttLogger(*getMqttClient(), _path, MqttLoggerMode::MqttAndSerial); } + #endif } const String EthLan8720Device::deviceName() const @@ -71,23 +75,29 @@ void EthLan8720Device::initialize() delay(250); WiFi.setHostname(_hostname.c_str()); + + #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) _hardwareInitialized = ETH.begin(_phy_addr, _power, _mdc, _mdio, _type, _clock_mode, _use_mac_from_efuse); + #else + #ifdef CONFIG_IDF_TARGET_ESP32 + _hardwareInitialized = ETH.begin(_type, _phy_addr, _mdc, _mdio, ETH_RESET_PIN, _clock_mode); + #else + _hardwareInitialized = false; + #endif + #endif ETH.setHostname(_hostname.c_str()); if(!_ipConfiguration->dhcpEnabled()) { ETH.config(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); } - if(_restartOnDisconnect) + WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { - WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) { - if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) - { - onDisconnected(); - } - }); - } + onDisconnected(); + } + }); } void EthLan8720Device::reconfigure() @@ -128,10 +138,8 @@ ReconnectStatus EthLan8720Device::reconnect() void EthLan8720Device::onDisconnected() { - if(millis() > 60000) - { - restartEsp(RestartReason::RestartOnDisconnectWatchdog); - } + if(_restartOnDisconnect && (millis() > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); + reconnect(); } int8_t EthLan8720Device::signalStrength() diff --git a/src/networkDevices/EthLan8720Device.h b/src/networkDevices/EthLan8720Device.h index ef4f543..8530b3c 100644 --- a/src/networkDevices/EthLan8720Device.h +++ b/src/networkDevices/EthLan8720Device.h @@ -1,10 +1,38 @@ #pragma once +#if (ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 0, 0)) +#ifndef CONFIG_IDF_TARGET_ESP32 +typedef enum { + ETH_CLOCK_GPIO0_IN = 0, + ETH_CLOCK_GPIO16_OUT = 2, + ETH_CLOCK_GPIO17_OUT = 3 +} eth_clock_mode_t; + +#define ETH_PHY_TYPE ETH_PHY_MAX +#else +#define ETH_PHY_TYPE ETH_PHY_LAN8720 +#endif + +#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN + +#define ETH_PHY_ADDR 0 +#define ETH_PHY_MDC 23 +#define ETH_PHY_MDIO 18 +#define ETH_PHY_POWER -1 +#define ETH_RESET_PIN 1 +#endif + #include +#if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) #include +#else +#include +#endif #include #include "NetworkDevice.h" +#ifndef NUKI_HUB_UPDATER #include "espMqttClient.h" +#endif #include class EthLan8720Device : public NetworkDevice @@ -54,8 +82,9 @@ private: eth_phy_type_t _type; eth_clock_mode_t _clock_mode; bool _use_mac_from_efuse; - + #ifndef NUKI_HUB_UPDATER char _ca[TLS_CA_MAX_SIZE] = {0}; char _cert[TLS_CERT_MAX_SIZE] = {0}; char _key[TLS_KEY_MAX_SIZE] = {0}; -}; + #endif +}; \ No newline at end of file diff --git a/src/networkDevices/NetworkDevice.cpp b/src/networkDevices/NetworkDevice.cpp index 6ca5d30..9e65acd 100644 --- a/src/networkDevices/NetworkDevice.cpp +++ b/src/networkDevices/NetworkDevice.cpp @@ -8,6 +8,7 @@ void NetworkDevice::printError() Log->println(ESP.getFreeHeap()); } +#ifndef NUKI_HUB_UPDATER void NetworkDevice::update() { if (_mqttEnabled) @@ -40,6 +41,18 @@ void NetworkDevice::mqttSetCleanSession(bool cleanSession) } } +void NetworkDevice::mqttSetKeepAlive(uint16_t keepAlive) +{ + if (_useEncryption) + { + _mqttClientSecure->setKeepAlive(keepAlive); + } + else + { + _mqttClient->setKeepAlive(keepAlive); + } +} + uint16_t NetworkDevice::mqttPublish(const char *topic, uint8_t qos, bool retain, const char *payload) { return getMqttClient()->publish(topic, qos, retain, payload); @@ -158,4 +171,9 @@ MqttClient *NetworkDevice::getMqttClient() const { return _mqttClient; } -} \ No newline at end of file +} +#else +void NetworkDevice::update() +{ +} +#endif \ No newline at end of file diff --git a/src/networkDevices/NetworkDevice.h b/src/networkDevices/NetworkDevice.h index 3da29ad..26d15ba 100644 --- a/src/networkDevices/NetworkDevice.h +++ b/src/networkDevices/NetworkDevice.h @@ -1,7 +1,9 @@ #pragma once +#ifndef NUKI_HUB_UPDATER #include "espMqttClient.h" #include "MqttClientSetup.h" +#endif #include "IPConfiguration.h" enum class ReconnectStatus @@ -35,8 +37,10 @@ public: virtual String localIP() = 0; virtual String BSSIDstr() = 0; + #ifndef NUKI_HUB_UPDATER virtual void mqttSetClientId(const char* clientId); virtual void mqttSetCleanSession(bool cleanSession); + virtual void mqttSetKeepAlive(uint16_t keepAlive); virtual uint16_t mqttPublish(const char* topic, uint8_t qos, bool retain, const char* payload); virtual uint16_t mqttPublish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length); virtual bool mqttConnected() const; @@ -51,16 +55,19 @@ public: virtual void disableMqtt(); virtual uint16_t mqttSubscribe(const char* topic, uint8_t qos); + #endif protected: + #ifndef NUKI_HUB_UPDATER espMqttClient *_mqttClient = nullptr; espMqttClientSecure *_mqttClientSecure = nullptr; bool _useEncryption = false; bool _mqttEnabled = true; - + + MqttClient *getMqttClient() const; + #endif + const String _hostname; const IPConfiguration* _ipConfiguration = nullptr; - - MqttClient *getMqttClient() const; }; \ No newline at end of file diff --git a/src/networkDevices/W5500Device.cpp b/src/networkDevices/W5500Device.cpp index 0520b07..13e3374 100644 --- a/src/networkDevices/W5500Device.cpp +++ b/src/networkDevices/W5500Device.cpp @@ -3,7 +3,9 @@ #include "W5500Device.h" #include "../PreferencesKeys.h" #include "../Logger.h" +#ifndef NUKI_HUB_UPDATER #include "../MqttTopics.h" +#endif #include "sdkconfig.h" W5500Device::W5500Device(const String &hostname, Preferences* preferences, const IPConfiguration* ipConfiguration, int variant) @@ -27,8 +29,9 @@ W5500Device::W5500Device(const String &hostname, Preferences* preferences, const } } Log->println(); - + #ifndef NUKI_HUB_UPDATER _mqttClient = new espMqttClientW5500(); + #endif } W5500Device::~W5500Device() @@ -61,6 +64,7 @@ void W5500Device::initialize() break; } + #ifndef NUKI_HUB_UPDATER if(_preferences->getBool(preference_mqtt_log_enabled)) { String pathStr = _preferences->getString(preference_mqtt_lock_path); @@ -70,6 +74,7 @@ void W5500Device::initialize() strcpy(_path, pathStr.c_str()); Log = new MqttLogger(*getMqttClient(), _path, MqttLoggerMode::MqttAndSerial); } + #endif reconnect(); } diff --git a/src/networkDevices/W5500Device.h b/src/networkDevices/W5500Device.h index 4c5db6a..9c60f50 100644 --- a/src/networkDevices/W5500Device.h +++ b/src/networkDevices/W5500Device.h @@ -1,8 +1,10 @@ #pragma once #include "NetworkDevice.h" +#ifndef NUKI_HUB_UPDATER #include "espMqttClient.h" #include "espMqttClientW5500.h" +#endif #include #include diff --git a/src/networkDevices/WifiDevice.cpp b/src/networkDevices/WifiDevice.cpp index 616d7a9..fa0f479 100644 --- a/src/networkDevices/WifiDevice.cpp +++ b/src/networkDevices/WifiDevice.cpp @@ -2,8 +2,10 @@ #include "WifiDevice.h" #include "../PreferencesKeys.h" #include "../Logger.h" +#ifndef NUKI_HUB_UPDATER #include "../MqttTopics.h" #include "espMqttClient.h" +#endif #include "../RestartReason.h" RTC_NOINIT_ATTR char WiFiDevice_reconfdetect[17]; @@ -15,6 +17,7 @@ WifiDevice::WifiDevice(const String& hostname, Preferences* preferences, const I { _startAp = strcmp(WiFiDevice_reconfdetect, "reconfigure_wifi") == 0; + #ifndef NUKI_HUB_UPDATER _restartOnDisconnect = preferences->getBool(preference_restart_on_disconnect); size_t caLength = preferences->getString(preference_mqtt_ca, _ca, TLS_CA_MAX_SIZE); @@ -53,6 +56,7 @@ WifiDevice::WifiDevice(const String& hostname, Preferences* preferences, const I strcpy(_path, pathStr.c_str()); Log = new MqttLogger(*getMqttClient(), _path, MqttLoggerMode::MqttAndSerial); } + #endif } const String WifiDevice::deviceName() const @@ -94,9 +98,9 @@ void WifiDevice::initialize() if(!res) { - esp_wifi_disconnect (); - esp_wifi_stop (); - esp_wifi_deinit (); + esp_wifi_disconnect(); + esp_wifi_stop(); + esp_wifi_deinit(); Log->println(F("Failed to connect. Wait for ESP restart.")); delay(1000); @@ -107,16 +111,17 @@ void WifiDevice::initialize() Log->println(WiFi.localIP().toString()); } - if(_restartOnDisconnect) + WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { - WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) { - if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) - { - onDisconnected(); - } - }); - } + onDisconnected(); + } + else if(event == ARDUINO_EVENT_WIFI_STA_GOT_IP) + { + onConnected(); + } + }); } void WifiDevice::reconfigure() @@ -138,16 +143,30 @@ bool WifiDevice::isConnected() ReconnectStatus WifiDevice::reconnect() { - delay(3000); + if(!isConnected() && !_isReconnecting) + { + _isReconnecting = true; + _wm.autoConnect(); + delay(10000); + _isReconnecting = false; + } + + if(!isConnected() && _disconnectTs > millis() - 120000) _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled)); return isConnected() ? ReconnectStatus::Success : ReconnectStatus::Failure; } +void WifiDevice::onConnected() +{ + _isReconnecting = false; + _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled)); +} + void WifiDevice::onDisconnected() { - if(millis() > 60000) - { - restartEsp(RestartReason::RestartOnDisconnectWatchdog); - } + _disconnectTs = millis(); + if(_restartOnDisconnect && (millis() > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); + _wm.setEnableConfigPortal(false); + reconnect(); } int8_t WifiDevice::signalStrength() diff --git a/src/networkDevices/WifiDevice.h b/src/networkDevices/WifiDevice.h index 152fbc4..986f923 100644 --- a/src/networkDevices/WifiDevice.h +++ b/src/networkDevices/WifiDevice.h @@ -1,11 +1,17 @@ #pragma once #include +#if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)) #include +#else +#include +#endif #include #include "NetworkDevice.h" #include "WiFiManager.h" +#ifndef NUKI_HUB_UPDATER #include "espMqttClient.h" +#endif #include "IPConfiguration.h" class WifiDevice : public NetworkDevice @@ -31,15 +37,20 @@ private: static void clearRtcInitVar(WiFiManager*); void onDisconnected(); + void onConnected(); WiFiManager _wm; Preferences* _preferences = nullptr; bool _restartOnDisconnect = false; bool _startAp = false; + bool _isReconnecting = false; char* _path; + unsigned long _disconnectTs = 0; + #ifndef NUKI_HUB_UPDATER char _ca[TLS_CA_MAX_SIZE] = {0}; char _cert[TLS_CERT_MAX_SIZE] = {0}; char _key[TLS_KEY_MAX_SIZE] = {0}; + #endif }; diff --git a/updater/CMakeLists.txt b/updater/CMakeLists.txt new file mode 100644 index 0000000..98a9b7e --- /dev/null +++ b/updater/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.16.0) +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +list(APPEND EXTRA_COMPONENT_DIRS ../components) +project(updater) diff --git a/updater/partitions.csv b/updater/partitions.csv new file mode 100644 index 0000000..0f6f14e --- /dev/null +++ b/updater/partitions.csv @@ -0,0 +1 @@ +# Espressif ESP32 Partition Table # Name, Type, SubType, Offset, Size, Flags nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x150000, \ No newline at end of file diff --git a/updater/pio_package.py b/updater/pio_package.py new file mode 100644 index 0000000..01143bf --- /dev/null +++ b/updater/pio_package.py @@ -0,0 +1,44 @@ +""" PlatformIO POST script execution to copy updater """ + +Import("env") +import glob +import os +import shutil +from pathlib import Path + +def get_board_name(env): + board = env.get('BOARD_MCU') + if env.get('BOARD') == 'esp32-solo1': + board = env.get('BOARD').replace('-', '') + return board + +def create_target_dir(env): + board = get_board_name(env) + target_dir = env.GetProjectOption("custom_build") + '/' + board + if not os.path.exists(target_dir): + os.makedirs(target_dir) + return target_dir + +def copy_files(source, target, env): + file = Path(target[0].get_abspath()) + target_dir = create_target_dir(env) + board = get_board_name(env) + + if "firmware" in file.stem: + shutil.copy(file, f"{target_dir}/updater.bin") + +def remove_files(source, target, env): + for f in glob.glob("src/*.cpp"): + os.remove(f) + + for f in glob.glob("src/*.h"): + os.remove(f) + + for f in glob.glob("src/networkDevices/*.cpp"): + os.remove(f) + + for f in glob.glob("src/networkDevices/*.h"): + os.remove(f) + +env.AddPostAction("$BUILD_DIR/firmware.bin", copy_files) +env.AddPostAction("$BUILD_DIR/firmware.bin", remove_files) diff --git a/updater/pio_package_pre.py b/updater/pio_package_pre.py new file mode 100644 index 0000000..0417fb0 --- /dev/null +++ b/updater/pio_package_pre.py @@ -0,0 +1,3 @@ +import shutil + +shutil.copy("../src/main.cpp", "src/main.cpp") \ No newline at end of file diff --git a/updater/pio_package_pre_solo1.py b/updater/pio_package_pre_solo1.py new file mode 100644 index 0000000..36ab242 --- /dev/null +++ b/updater/pio_package_pre_solo1.py @@ -0,0 +1,32 @@ +import shutil +import os + +if not os.path.exists('src/networkDevices/'): + os.mkdir('src/networkDevices') + +shutil.copy("../src/main.cpp", "src/main.cpp") +shutil.copy("../src/Config.h", "src/Config.h") +shutil.copy("../src/Logger.h", "src/Logger.h") +shutil.copy("../src/NukiNetwork.h", "src/NukiNetwork.h") +shutil.copy("../src/Ota.h", "src/Ota.h") +shutil.copy("../src/PreferencesKeys.h", "src/PreferencesKeys.h") +shutil.copy("../src/RestartReason.h", "src/RestartReason.h") +shutil.copy("../src/WebCfgServer.h", "src/WebCfgServer.h") +shutil.copy("../src/WebCfgServerConstants.h", "src/WebCfgServerConstants.h") + +shutil.copy("../src/Logger.cpp", "src/Logger.cpp") +shutil.copy("../src/NukiNetwork.cpp", "src/NukiNetwork.cpp") +shutil.copy("../src/Ota.cpp", "src/Ota.cpp") +shutil.copy("../src/WebCfgServer.cpp", "src/WebCfgServer.cpp") + +shutil.copy("../src/networkDevices/EthLan8720Device.h", "src/networkDevices/EthLan8720Device.h") +shutil.copy("../src/networkDevices/IPConfiguration.h", "src/networkDevices/IPConfiguration.h") +shutil.copy("../src/networkDevices/NetworkDevice.h", "src/networkDevices/NetworkDevice.h") +shutil.copy("../src/networkDevices/W5500Device.h", "src/networkDevices/W5500Device.h") +shutil.copy("../src/networkDevices/WifiDevice.h", "src/networkDevices/WifiDevice.h") + +shutil.copy("../src/networkDevices/EthLan8720Device.cpp", "src/networkDevices/EthLan8720Device.cpp") +shutil.copy("../src/networkDevices/IPConfiguration.cpp", "src/networkDevices/IPConfiguration.cpp") +shutil.copy("../src/networkDevices/NetworkDevice.cpp", "src/networkDevices/NetworkDevice.cpp") +shutil.copy("../src/networkDevices/W5500Device.cpp", "src/networkDevices/W5500Device.cpp") +shutil.copy("../src/networkDevices/WifiDevice.cpp", "src/networkDevices/WifiDevice.cpp") \ No newline at end of file diff --git a/updater/platformio.ini b/updater/platformio.ini new file mode 100644 index 0000000..9e81029 --- /dev/null +++ b/updater/platformio.ini @@ -0,0 +1,85 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[platformio] +default_envs = updater_esp32dev +boards_dir = ../boards + +[env] +platform = https://github.com/tasmota/platform-espressif32/releases/download/2024.06.11/platform-espressif32.zip +platform_packages = +framework = arduino, espidf +build_type = release +custom_build = release +board_build.partitions = partitions.csv +build_unflags = + -Werror=all + -Wall +build_flags = + -fexceptions + -DESP_PLATFORM + -DESP32 + -DARDUINO_ARCH_ESP32 + -DNUKI_HUB_UPDATER + -Wno-ignored-qualifiers + -Wno-missing-field-initializers + -Wno-type-limits + -Wno-maybe-uninitialized + -Wno-implicit-fallthrough + -Wno-unused-result +lib_deps = + AsyncTCP=symlink://../lib/AsyncTCP + Ethernet=symlink://../lib/Ethernet + HTTPClient=symlink://../lib/HTTPClient + NetworkClientSecure=symlink://../lib/NetworkClientSecure + WebServer=symlink://../lib/WebServer + WiFiManager=symlink://../lib/WiFiManager + +monitor_speed = 115200 +monitor_filters = + esp32_exception_decoder + time + +[env:updater_esp32dev] +board = esp32dev +extra_scripts = + pre:pio_package_pre.py + post:pio_package.py + +[env:updater_esp32-c3] +extends = env:updater_esp32dev +board = esp32-c3-devkitc-02 + +[env:updater_esp32-s3] +extends = env:updater_esp32dev +board = nuki-esp32-s3 + +[env:updater_esp32-c6] +extends = env:updater_esp32dev +board = esp32-c6-devkitm-1 + +[env:updater_esp32solo1] +platform = https://github.com/tasmota/platform-espressif32/releases/download/2023.10.03/platform-espressif32-2023.10.03.zip +framework = arduino +board = esp32-solo1 +extra_scripts = + pre:pio_package_pre_solo1.py + post:pio_package.py +build_flags = + ${env.build_flags} + -DFRAMEWORK_ARDUINO_SOLO1 +lib_deps = + AsyncTCP=symlink://../lib/AsyncTCP + Ethernet=symlink://../lib/Ethernet + HTTPClient=symlink://../lib/HTTPClient + WebServer=symlink://../lib/WebServer + WiFiManager=symlink://../lib/WiFiManager +lib_ignore = + NetworkClientSecure \ No newline at end of file diff --git a/updater/sdkconfig.defaults b/updater/sdkconfig.defaults new file mode 100644 index 0000000..a9875d9 --- /dev/null +++ b/updater/sdkconfig.defaults @@ -0,0 +1,13 @@ +CONFIG_AUTOSTART_ARDUINO=y +CONFIG_FREERTOS_HZ=1000 +CONFIG_MBEDTLS_PSK_MODES=y +CONFIG_MBEDTLS_KEY_EXCHANGE_PSK=y +CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_BT_ENABLED=n +CONFIG_IEEE802154_ENABLED=n +CONFIG_ARDUINO_SELECTIVE_COMPILATION=y +CONFIG_ARDUINO_SELECTIVE_HTTPClient=n +CONFIG_ARDUINO_SELECTIVE_WebServer=n +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN=y \ No newline at end of file diff --git a/updater/src/CMakeLists.txt b/updater/src/CMakeLists.txt new file mode 100644 index 0000000..8f4a391 --- /dev/null +++ b/updater/src/CMakeLists.txt @@ -0,0 +1,28 @@ +list(APPEND app_sources ${CMAKE_SOURCE_DIR}/src/main.cpp) +list(APPEND app_sources ../../src/Config.h) +list(APPEND app_sources ../../src/Logger.h) +list(APPEND app_sources ../../src/NukiNetwork.h) +list(APPEND app_sources ../../src/Ota.h) +list(APPEND app_sources ../../src/PreferencesKeys.h) +list(APPEND app_sources ../../src/RestartReason.h) +list(APPEND app_sources ../../src/WebCfgServer.h) +list(APPEND app_sources ../../src/WebCfgServerConstants.h) + +list(APPEND app_sources ../../src/Logger.cpp) +list(APPEND app_sources ../../src/NukiNetwork.cpp) +list(APPEND app_sources ../../src/Ota.cpp) +list(APPEND app_sources ../../src/WebCfgServer.cpp) + +list(APPEND app_sources ../../src/networkDevices/EthLan8720Device.h) +list(APPEND app_sources ../../src/networkDevices/IPConfiguration.h) +list(APPEND app_sources ../../src/networkDevices/NetworkDevice.h) +list(APPEND app_sources ../../src/networkDevices/W5500Device.h) +list(APPEND app_sources ../../src/networkDevices/WifiDevice.h) + +list(APPEND app_sources ../../src/networkDevices/EthLan8720Device.cpp) +list(APPEND app_sources ../../src/networkDevices/IPConfiguration.cpp) +list(APPEND app_sources ../../src/networkDevices/NetworkDevice.cpp) +list(APPEND app_sources ../../src/networkDevices/W5500Device.cpp) +list(APPEND app_sources ../../src/networkDevices/WifiDevice.cpp) + +idf_component_register(SRCS ${app_sources})