diff --git a/.astylerc b/.astylerc new file mode 100644 index 0000000..d154129 --- /dev/null +++ b/.astylerc @@ -0,0 +1,5 @@ +--style=allman +--add-braces +--exclude=lib +--suffix=none + diff --git a/README.md b/README.md index e95a301..75e192a 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,8 @@ Unpack the zip archive and read the included how-to-flash.txt for installation i ## Initial setup (Network and MQTT) -Power up the ESP32 and a new Wi-Fi access point named "ESP32_(8 CHARACTER ALPHANUMERIC)" should appear.
+Power up the ESP32 and a new Wi-Fi access point named "NukiHub" should appear.
+The password of the access point is "NukiHubESP32".
Connect a client device to this access point and in a browser navigate to "http://192.168.4.1".
Use the web interface to connect the ESP to your preferred Wi-Fi network.

@@ -99,8 +100,9 @@ In that case leave all fields starting with "MQTT SSL" blank. Otherwise see the ## Pairing with a Nuki Lock or Opener -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.
+Make sure "Bluetooth pairing" is enabled for the Nuki device by enabling this setting in the official Nuki App in "Settings" > "Features & Configuration" > "Button and LED". +After enabling the setting press the button on the Nuki device for a few seconds.
+Pairing should be automatic when the ESP32 is powered on.

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.
@@ -138,7 +140,7 @@ PSRAM is usually 2, 4 or 8MB in size and thus greatly enlarges the 320kb of inte It is basically impossible to run out of RAM when PSRAM is available. You can check on the info page of the Web configurator if PSRAM is available. -Note that there are two build of Nuki Hub for the ESP32-S3 available.
+Note that there are two builds of Nuki Hub for the ESP32-S3 available.
One for devices with no or Quad SPI PSRAM and one for devices with Octal SPI PSRAM.
If your ESP32-S3 device has PSRAM but it is not detected please flash the other S3 binary. @@ -165,7 +167,6 @@ In a browser navigate to the IP address assigned to the ESP32. - MQTT SSL Client Certificate: Optionally set to the Client SSL certificate of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional)" section of this README. - MQTT SSL Client Key: Optionally set to the Client SSL key of the MQTT broker, see the "[MQTT Encryption](#mqtt-encryption-optional)" section of this README. - Network hardware: "Wi-Fi only" by default, set to one of the specified ethernet modules if available, see the "Supported Ethernet devices" and "[Connecting via Ethernet](#connecting-via-ethernet-optional)" section of this README. -- Disable fallback to Wi-Fi / Wi-Fi config portal: By default the Nuki Hub will fallback to Wi-Fi and open the Wi-Fi configuration portal when the network connection fails. Enable this setting to disable this fallback. - Connect to AP with the best signal in an environment with multiple APs with the same SSID: Enable to perform a scan for the Access Point with the best signal strenght for the specified SSID in a multi AP/Mesh environment. - 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. - 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. @@ -252,6 +253,21 @@ In a browser navigate to the IP address assigned to the ESP32. - Gpio [2-33]: See the "[GPIO lock control](#gpio-lock-control-optional)" section of this README. +### Import/Export Configuration + +The "Import/Export Configuration" menu option allows the importing and exporting of the NukiHub settings in JSON format.
+
+Create a (partial) backup of the current NukiHub settings by selecting any of the following:
+- Basic export: Will backup all settings that are not considered confidential (as such passwords and pincodes are not included in this export). +- Export with redacted settings: Will backup basic settings and redacted settings such as passwords and pincodes. + +Both of the above options will not backup pairing data, so you will have to manually pair Nuki devices when importing this export on a factory reset or new device. + +- Export with redacted settings and pairing data: Will backup all settings and pairing data. Can be used to completely restore a factory reset or new device based on the settings of this device. (Re)pairing Nuki devices will not be needed when importing this export. +
+To import settings copy and paste the contents of the JSON file that is created by any of the above export options and select "Import". +After importing the device will reboot. + ## Exposed MQTT Topics ### Lock @@ -659,9 +675,9 @@ Examples: ## GPIO lock control (optional) -The lock can be controlled via GPIO.
+The lock can be controlled via GPIO. To trigger actions, a connection to ground has to be present for at lease 300ms (or to +3.3V for "General input (pull-down)").

-To enable GPIO control, go the the "GPIO Configuration" page where each GPIO can be configured for a specific role: +To enable GPIO control, go the the "GPIO Configuration" page where each GPIO can e configured for a specific role: - Disabled: The GPIO is disabled - Input: Lock: When connect to Ground, a lock command is sent to the lock - Input: Unlock: When connect to Ground, an unlock command is sent to the lock diff --git a/clion/CMakeLists.txt b/clion/CMakeLists.txt index 66dbd1b..508f2a0 100644 --- a/clion/CMakeLists.txt +++ b/clion/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.16.0) -include($ENV{IDF_PATH}/tools/cmake/project.cmake) +# include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(nukihub) add_compile_definitions(CONFIG_IDF_TARGET_ESP32) @@ -32,10 +32,6 @@ set(SRCFILES ../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/nuki_ble/src/NukiBle.cpp ../lib/nuki_ble/src/NukiBle.hpp ../lib/nuki_ble/src/NukiLock.cpp @@ -50,28 +46,22 @@ set(SRCFILES ../lib/BleScanner/src/BleInterfaces.h ../lib/BleScanner/src/BleScanner.cpp ../lib/MqttLogger/src/MqttLogger.cpp - ../lib/AsyncTCP/src/AsyncTCP.cpp ../src/util/NetworkUtil.cpp ../src/enums/NetworkDeviceType.h ../src/util/NetworkDeviceInstantiator.cpp ../src/NukiOfficial.cpp ../src/NukiPublisher.cpp + ../src/EspMillis.h ) file(GLOB_RECURSE SRCFILESREC lib/NimBLE-Arduino/src/*.c lib/NimBLE-Arduino/src/*.cpp lib/NimBLE-Arduino/src/*.h - lib/ESP Async WebServer/src/*.cpp - lib/ESP Async WebServer/src/*.h - lib/espMqttClient/src/*.cpp - lib/espMqttClient/src/*.h - lib/espMqttClient/src/Packets/*.cpp - lib/espMqttClient/src/Packets/*.h - lib/espMqttClient/src/Transport/*.cpp - lib/espMqttClient/src/Transport/*.h lib/ArduinoJson/src/*.h lib/ArduinoJson/src/*.hpp + lib/PsychicHttp/src/*.cpp + lib/PsychicHttp/src/*.h ) add_executable(dummy diff --git a/lib/AsyncTCP/CMakeLists.txt b/lib/AsyncTCP/CMakeLists.txt deleted file mode 100644 index f52e1c9..0000000 --- a/lib/AsyncTCP/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/Kconfig.projbuild b/lib/AsyncTCP/Kconfig.projbuild deleted file mode 100644 index 1774926..0000000 --- a/lib/AsyncTCP/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/LICENSE b/lib/AsyncTCP/LICENSE deleted file mode 100644 index 65c5ca8..0000000 --- a/lib/AsyncTCP/LICENSE +++ /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/AsyncTCP/README.md b/lib/AsyncTCP/README.md deleted file mode 100644 index 61ccd09..0000000 --- a/lib/AsyncTCP/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# 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/ci.yml/badge.svg)](https://github.com/mathieucarbou/AsyncTCP/actions/workflows/ci.yml) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/AsyncTCP.svg)](https://registry.platformio.org/libraries/mathieucarbou/AsyncTCP) - -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/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 -- IPv6 support - -## Coordinates - -``` -mathieucarbou/AsyncTCP @ ^3.2.4 -``` - -## 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 deleted file mode 100644 index 174df7a..0000000 --- a/lib/AsyncTCP/arduino-cli-dev.yaml +++ /dev/null @@ -1,25 +0,0 @@ -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/arduino-cli.yaml b/lib/AsyncTCP/arduino-cli.yaml deleted file mode 100644 index 42365f4..0000000 --- a/lib/AsyncTCP/arduino-cli.yaml +++ /dev/null @@ -1,25 +0,0 @@ -board_manager: - additional_urls: - - https://espressif.github.io/arduino-esp32/package_esp32_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/examples/ClientServer/Client/Client.ino b/lib/AsyncTCP/examples/ClientServer/Client/Client.ino deleted file mode 100644 index 47d8bc7..0000000 --- a/lib/AsyncTCP/examples/ClientServer/Client/Client.ino +++ /dev/null @@ -1,42 +0,0 @@ -#include - -#include "config.h" - -static void replyToServer(void* arg) { - AsyncClient* client = reinterpret_cast(arg); - - // send reply - if (client->space() > 32 && client->canSend()) { - char message[32]; - 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); - -} - -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); - - AsyncClient* client = new AsyncClient; - client->onData(&handleData, client); - client->onConnect(&onConnect, client); - client->connect(SERVER_HOST_NAME, TCP_PORT); - -} - -void loop() { - -} diff --git a/lib/AsyncTCP/examples/ClientServer/Client/config.h b/lib/AsyncTCP/examples/ClientServer/Client/config.h deleted file mode 100644 index cf51e91..0000000 --- a/lib/AsyncTCP/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/AsyncTCP/library.json b/lib/AsyncTCP/library.json deleted file mode 100644 index c449f2a..0000000 --- a/lib/AsyncTCP/library.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "AsyncTCP", - "version": "3.2.4", - "description": "Asynchronous TCP Library for ESP32", - "keywords": "async,tcp", - "repository": { - "type": "git", - "url": "https://github.com/mathieucarbou/AsyncTCP.git" - }, - "authors": [ - { - "name": "Hristo Gochkov" - }, - { - "name": "Mathieu Carbou", - "maintainer": true - } - ], - "license": "LGPL-3.0", - "frameworks": "arduino", - "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 deleted file mode 100644 index 12a504c..0000000 --- a/lib/AsyncTCP/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=AsyncTCP -version=3.2.4 -author=Me-No-Dev -maintainer=Mathieu Carbou -sentence=Async TCP Library for ESP32 -paragraph=Async TCP Library for ESP32 -category=Other -url=https://github.com/mathieucarbou/AsyncTCP.git -architectures=* diff --git a/lib/AsyncTCP/platformio.ini b/lib/AsyncTCP/platformio.ini deleted file mode 100644 index 4cfad22..0000000 --- a/lib/AsyncTCP/platformio.ini +++ /dev/null @@ -1,48 +0,0 @@ -[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.3 - platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.3/esp32-arduino-libs-3.0.3.zip -board = esp32dev - -[env:pioarduino-esp32dev] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip -board = esp32dev - -[env:pioarduino-esp32-s2] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip -board = esp32-s2-saola-1 - -[env:pioarduino-esp32-s3] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip -board = esp32-s3-devkitc-1 - -[env:pioarduino-esp32-c3] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip -board = esp32-c3-devkitc-02 - -[env:pioarduino-esp32-c6] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.03/platform-espressif32.zip -board = esp32-c6-devkitc-1 diff --git a/lib/AsyncTCP/src/AsyncTCP.cpp b/lib/AsyncTCP/src/AsyncTCP.cpp deleted file mode 100644 index 2dae2cb..0000000 --- a/lib/AsyncTCP/src/AsyncTCP.cpp +++ /dev/null @@ -1,1557 +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 - -// Required for: -// https://github.com/espressif/arduino-esp32/blob/3.0.3/libraries/Network/src/NetworkInterface.cpp#L37-L47 -#if ESP_IDF_VERSION_MAJOR >= 5 -#include -#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 { - tcp_pcb * 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(CONFIG_ASYNC_TCP_QUEUE_SIZE, 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, CONFIG_ASYNC_TCP_PRIORITY, &_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(CONFIG_ASYNC_TCP_MAX_ACK_TIME) -, _connect_port(0) -, prev(NULL) -, next(NULL) -{ - _pcb = pcb; - _closed_slot = -1; - 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); - if(!_allocate_closed_slot()) { - _close(); - } - } -} - -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_d("already connected, state %d", _pcb->state); - return false; - } - if(!_start_async_task()){ - log_e("failed to start task"); - return false; - } - - if(!_allocate_closed_slot()) { - log_e("failed to allocate: closed slot full"); - return false; - } - - tcp_pcb* pcb = tcp_new_ip_type(addr.type); - 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); - esp_err_t err =_tcp_connect(pcb, _closed_slot, &addr, port,(tcp_connected_fn)&_tcp_connected); - return err == ESP_OK; -} - -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_d("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) { - 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(); - } - _free_closed_slot(); - _pcb = NULL; - if(_discard_cb) { - _discard_cb(_discard_cb_arg, this); - } - } - return err; -} - -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) { - 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); - 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(tcp_pcb* pcb, int8_t err){ - _pcb = reinterpret_cast(pcb); - if(_pcb){ - _rx_last_packet = millis(); - } - 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); - } - _free_closed_slot(); - _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_d("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_ack = _rx_last_packet = millis(); - if(_sent_cb) { - _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) { - 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 { - if(_recv_cb) { - _recv_cb(_recv_cb_arg, this, b->payload, b->len); - } - if(!_ack_pcb) { - _rx_ack_len += b->len; - } - } - pbuf_free(b); - } - return _tcp_recved(pcb, _closed_slot, total); -} - -int8_t AsyncClient::_poll(tcp_pcb* pcb){ - if(!_pcb){ - // log_d("pcb is NULL"); - return ERR_OK; - } - if(pcb != _pcb){ - log_d("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_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_timeout && (now - _rx_last_packet) >= (_rx_timeout * 1000)) { - log_d("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 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); - } - 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); -} - -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; - } - 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; -} -#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; - } - 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() { -#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() { - return getRemotePort(); -} - -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(); -} - -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, struct tcp_pcb * pcb, int8_t err){ - return reinterpret_cast(arg)->_connected(pcb, err); -} - -/* - Async TCP Server - */ - -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) -, _connect_cb(0) -, _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) -, _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; - _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; -#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) { - _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_d("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/src/AsyncTCP.h b/lib/AsyncTCP/src/AsyncTCP.h deleted file mode 100644 index feac4d2..0000000 --- a/lib/AsyncTCP/src/AsyncTCP.h +++ /dev/null @@ -1,279 +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_ - -#define ASYNCTCP_VERSION "3.2.4" -#define ASYNCTCP_VERSION_MAJOR 3 -#define ASYNCTCP_VERSION_MINOR 2 -#define ASYNCTCP_VERSION_REVISION 4 -#define ASYNCTCP_FORK_mathieucarbou - -#include "IPAddress.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 -#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 - -#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_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(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(); - 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(); - - 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(); - 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, 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; - - 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(); - 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); - 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); -#if ESP_IDF_VERSION_MAJOR < 5 - AsyncServer(IPv6Address addr, uint16_t port); -#endif - 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; -#if ESP_IDF_VERSION_MAJOR < 5 - IPv6Address _addr6; -#endif - 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/ESPAsyncWebServer/LICENSE b/lib/ESPAsyncWebServer/LICENSE deleted file mode 100644 index 153d416..0000000 --- a/lib/ESPAsyncWebServer/LICENSE +++ /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. \ No newline at end of file diff --git a/lib/ESPAsyncWebServer/README.md b/lib/ESPAsyncWebServer/README.md deleted file mode 100644 index 6ca1d1e..0000000 --- a/lib/ESPAsyncWebServer/README.md +++ /dev/null @@ -1,126 +0,0 @@ -# ESPAsyncWebServer - -[![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/ESPAsyncWebServer.svg)](https://registry.platformio.org/libraries/mathieucarbou/ESPAsyncWebServer) - -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. - -## Coordinate and dependencies: - -**WARNING** The library name was changed from `ESP Async WebServer` to `ESPAsyncWebServer` as per the Arduino Lint recommendations. - -``` -mathieucarbou/ESPAsyncWebServer @ 3.1.5 -``` - -Dependency: - -- **ESP32**: `mathieucarbou/AsyncTCP @ 3.2.4` (Arduino IDE: [https://github.com/mathieucarbou/AsyncTCP#v3.2.4](https://github.com/mathieucarbou/AsyncTCP/releases/tag/v3.2.0)) -- **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)) - -## 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/AsyncTCP @ 3.2.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): MessagePack Support ([#62](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/62)) -- [@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)) - -## 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/ESPAsyncWebServer/docs/_config.yml b/lib/ESPAsyncWebServer/docs/_config.yml deleted file mode 100644 index 3636597..0000000 --- a/lib/ESPAsyncWebServer/docs/_config.yml +++ /dev/null @@ -1,8 +0,0 @@ -# bundle exec jekyll serve --host=0.0.0.0 - -title: ESPAsyncWebServer -description: "Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040" -remote_theme: pages-themes/cayman@v0.2.0 -plugins: - - jekyll-remote-theme - \ No newline at end of file diff --git a/lib/ESPAsyncWebServer/docs/index.md b/lib/ESPAsyncWebServer/docs/index.md deleted file mode 100644 index 6ca1d1e..0000000 --- a/lib/ESPAsyncWebServer/docs/index.md +++ /dev/null @@ -1,126 +0,0 @@ -# ESPAsyncWebServer - -[![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/ESPAsyncWebServer.svg)](https://registry.platformio.org/libraries/mathieucarbou/ESPAsyncWebServer) - -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. - -## Coordinate and dependencies: - -**WARNING** The library name was changed from `ESP Async WebServer` to `ESPAsyncWebServer` as per the Arduino Lint recommendations. - -``` -mathieucarbou/ESPAsyncWebServer @ 3.1.5 -``` - -Dependency: - -- **ESP32**: `mathieucarbou/AsyncTCP @ 3.2.4` (Arduino IDE: [https://github.com/mathieucarbou/AsyncTCP#v3.2.4](https://github.com/mathieucarbou/AsyncTCP/releases/tag/v3.2.0)) -- **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)) - -## 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/AsyncTCP @ 3.2.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): MessagePack Support ([#62](https://github.com/mathieucarbou/ESPAsyncWebServer/pull/62)) -- [@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)) - -## 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/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino b/lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino deleted file mode 100644 index 2d0de89..0000000 --- a/lib/ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino +++ /dev/null @@ -1,57 +0,0 @@ -#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/ESPAsyncWebServer/examples/Draft/Draft.ino b/lib/ESPAsyncWebServer/examples/Draft/Draft.ino deleted file mode 100644 index f10a9e7..0000000 --- a/lib/ESPAsyncWebServer/examples/Draft/Draft.ino +++ /dev/null @@ -1,37 +0,0 @@ -#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/ESPAsyncWebServer/examples/Filters/Filters.ino b/lib/ESPAsyncWebServer/examples/Filters/Filters.ino deleted file mode 100644 index f031a1f..0000000 --- a/lib/ESPAsyncWebServer/examples/Filters/Filters.ino +++ /dev/null @@ -1,111 +0,0 @@ -// 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/ESPAsyncWebServer/examples/SimpleServer/SimpleServer.ino b/lib/ESPAsyncWebServer/examples/SimpleServer/SimpleServer.ino deleted file mode 100644 index f3a1605..0000000 --- a/lib/ESPAsyncWebServer/examples/SimpleServer/SimpleServer.ino +++ /dev/null @@ -1,134 +0,0 @@ -// -// 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 - -#include -#include -#include - -AsyncWebServer server(80); - -const char* PARAM_MESSAGE = "message"; - -void notFound(AsyncWebServerRequest* request) { - request->send(404, "text/plain", "Not found"); -} - -AsyncCallbackJsonWebHandler* jsonHandler = new AsyncCallbackJsonWebHandler("/json2"); -AsyncCallbackMessagePackWebHandler* msgPackHandler = new AsyncCallbackMessagePackWebHandler("/msgpack2"); - -void setup() { - - Serial.begin(115200); - - // WiFi.mode(WIFI_STA); - // WiFi.begin("YOUR_SSID", "YOUR_PASSWORD"); - // if (WiFi.waitForConnectResult() != WL_CONNECTED) { - // Serial.printf("WiFi Failed!\n"); - // return; - // } - // Serial.print("IP Address: "); - // Serial.println(WiFi.localIP()); - - WiFi.mode(WIFI_AP); - WiFi.softAP("esp-captive"); - - 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); - }); - - // JSON - - // receives JSON and sends JSON - jsonHandler->onRequest([](AsyncWebServerRequest* request, JsonVariant& json) { - JsonObject jsonObj = json.as(); - // ... - - AsyncJsonResponse* response = new AsyncJsonResponse(); - JsonObject root = response->getRoot().to(); - root["hello"] = "world"; - response->setLength(); - request->send(response); - }); - - // sends JSON - server.on("/json1", HTTP_GET, [](AsyncWebServerRequest* request) { - AsyncJsonResponse* response = new AsyncJsonResponse(); - JsonObject root = response->getRoot().to(); - root["hello"] = "world"; - response->setLength(); - request->send(response); - }); - - // MessagePack - - // receives MessagePack and sends MessagePack - msgPackHandler->onRequest([](AsyncWebServerRequest* request, JsonVariant& json) { - JsonObject jsonObj = json.as(); - // ... - - AsyncMessagePackResponse* response = new AsyncMessagePackResponse(); - JsonObject root = response->getRoot().to(); - root["hello"] = "world"; - response->setLength(); - request->send(response); - }); - - // sends MessagePack - server.on("/msgpack1", HTTP_GET, [](AsyncWebServerRequest* request) { - AsyncMessagePackResponse* response = new AsyncMessagePackResponse(); - JsonObject root = response->getRoot().to(); - root["hello"] = "world"; - response->setLength(); - request->send(response); - }); - - server.addHandler(jsonHandler); - server.addHandler(msgPackHandler); - - server.onNotFound(notFound); - - server.begin(); -} - -void loop() { -} \ No newline at end of file diff --git a/lib/ESPAsyncWebServer/examples/StreamFiles/StreamConcat.h b/lib/ESPAsyncWebServer/examples/StreamFiles/StreamConcat.h deleted file mode 100644 index c1e1927..0000000 --- a/lib/ESPAsyncWebServer/examples/StreamFiles/StreamConcat.h +++ /dev/null @@ -1,37 +0,0 @@ -#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/ESPAsyncWebServer/examples/StreamFiles/StreamFiles.ino b/lib/ESPAsyncWebServer/examples/StreamFiles/StreamFiles.ino deleted file mode 100644 index 2a2c1b6..0000000 --- a/lib/ESPAsyncWebServer/examples/StreamFiles/StreamFiles.ino +++ /dev/null @@ -1,84 +0,0 @@ -#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/ESPAsyncWebServer/examples/StreamFiles/StreamString.h b/lib/ESPAsyncWebServer/examples/StreamFiles/StreamString.h deleted file mode 100644 index a6e0655..0000000 --- a/lib/ESPAsyncWebServer/examples/StreamFiles/StreamString.h +++ /dev/null @@ -1,40 +0,0 @@ -#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/ESPAsyncWebServer/examples/issues/Issue14/Issue14.ino b/lib/ESPAsyncWebServer/examples/issues/Issue14/Issue14.ino deleted file mode 100644 index f62084a..0000000 --- a/lib/ESPAsyncWebServer/examples/issues/Issue14/Issue14.ino +++ /dev/null @@ -1,107 +0,0 @@ -#include -#ifdef ESP32 - #include - #include -#elif defined(ESP8266) - #include - #include -#elif defined(TARGET_RP2040) - #include - #include -#endif - -#include "ESPAsyncWebServer.h" - -const char appWebPage[] PROGMEM = R"rawliteral( - - - - -)rawliteral"; - -AsyncWebServer server(80); -AsyncEventSource events("/events"); - -const uint32_t interval = 1000; -const int button1Pin = 4; - -uint32_t lastSend = 0; - -void prepareJson(String& buffer) { - buffer.reserve(512); - buffer.concat("{\"button1\":"); - buffer.concat(digitalRead(button1Pin) == LOW); - buffer.concat(",\"1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij\":"); - buffer.concat(random(0, 999999999)); - buffer.concat("}"); -} - -void setup() { - Serial.begin(115200); -#if ARDUINO_USB_CDC_ON_BOOT - Serial.setTxTimeoutMs(0); - delay(100); -#else - while (!Serial) - yield(); -#endif - - randomSeed(micros()); - - pinMode(button1Pin, OUTPUT); - digitalWrite(button1Pin, HIGH); - - WiFi.softAP("esp-captive"); - - server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { - request->send(200, "text/html", appWebPage); - }); - - server.on("/button1", HTTP_GET, [](AsyncWebServerRequest* request) { - request->send(200, "text/plain", "OK"); - digitalWrite(button1Pin, digitalRead(button1Pin) == LOW ? HIGH : LOW); - - String buffer; - prepareJson(buffer); - ESP_LOGI("async_tcp", "Sending from handler..."); - events.send(buffer.c_str(), "state", millis()); - ESP_LOGI("async_tcp", "Sent from handler!"); - }); - - events.onConnect([](AsyncEventSourceClient* client) { - String buffer; - prepareJson(buffer); - ESP_LOGI("async_tcp", "Sending from onConnect..."); - client->send(buffer.c_str(), "state", millis(), 5000); - ESP_LOGI("async_tcp", "Sent from onConnect!"); - }); - - server.addHandler(&events); - DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); - - server.begin(); -} - -void loop() { - if (millis() - lastSend >= interval) { - String buffer; - prepareJson(buffer); - ESP_LOGI("loop", "Sending..."); - events.send(buffer.c_str(), "state", millis()); - ESP_LOGI("loop", "Sent!"); - lastSend = millis(); - } -} diff --git a/lib/ESPAsyncWebServer/library.json b/lib/ESPAsyncWebServer/library.json deleted file mode 100644 index eb946c6..0000000 --- a/lib/ESPAsyncWebServer/library.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "name": "ESPAsyncWebServer", - "version": "3.1.5", - "description": "Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040. Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc.", - "keywords": "http,async,websocket,webserver", - "homepage": "https://github.com/mathieucarbou/ESPAsyncWebServer", - "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": "AsyncTCP", - "version": "^3.2.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/ESPAsyncWebServer/library.properties b/lib/ESPAsyncWebServer/library.properties deleted file mode 100644 index 3036044..0000000 --- a/lib/ESPAsyncWebServer/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ESPAsyncWebServer -version=3.1.5 -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/ESPAsyncWebServer/platformio.ini b/lib/ESPAsyncWebServer/platformio.ini deleted file mode 100644 index 6f68d0d..0000000 --- a/lib/ESPAsyncWebServer/platformio.ini +++ /dev/null @@ -1,80 +0,0 @@ -[env] -framework = arduino -build_flags = - -Wall -Wextra - -D CONFIG_ARDUHAL_LOG_COLORS - -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE - -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 -upload_protocol = esptool -monitor_speed = 115200 -monitor_filters = esp32_exception_decoder, log2file - -[platformio] -lib_dir = . -; src_dir = examples/CaptivePortal -src_dir = examples/SimpleServer -; src_dir = examples/StreamFiles -; src_dir = examples/Filters -; src_dir = examples/Draft -; src_dir = examples/issues/Issue14 - -[env:arduino] -platform = espressif32 -board = esp32dev -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - mathieucarbou/AsyncTCP @ 3.2.4 - -[env:arduino-2] -platform = espressif32@6.8.1 -board = esp32dev -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - mathieucarbou/AsyncTCP @ 3.2.4 - -[env:arduino-3] -platform = espressif32 -platform_packages= - platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.4 - platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.4/esp32-arduino-libs-3.0.4.zip -board = esp32dev -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - mathieucarbou/AsyncTCP @ 3.2.4 - -[env:esp8266] -platform = espressif8266 -board = huzzah -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - esphome/ESPAsyncTCP-esphome @ 2.0.0 - -; PlatformIO support for Raspberry Pi Pico is not official -; https://github.com/platformio/platform-raspberrypi/pull/36 -; https://github.com/earlephilhower/arduino-pico/blob/master/docs/platformio.rst -; board settings: https://github.com/earlephilhower/arduino-pico/blob/master/tools/json/rpipico.json -[env:rpipicow] -upload_protocol = picotool -platform = https://github.com/maxgerhardt/platform-raspberrypi.git -board = rpipicow -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - khoih-prog/AsyncTCP_RP2040W @ 1.2.0 - -[env:pioarduino-esp32dev] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.04/platform-espressif32.zip -board = esp32dev -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - mathieucarbou/AsyncTCP @ 3.2.4 - -[env:pioarduino-c6] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.04/platform-espressif32.zip -board = esp32-c6-devkitc-1 -lib_deps = - bblanchon/ArduinoJson @ 7.1.0 - mathieucarbou/AsyncTCP @ 3.2.4 diff --git a/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp b/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp deleted file mode 100644 index 639fd56..0000000 --- a/lib/ESPAsyncWebServer/src/AsyncEventSource.cpp +++ /dev/null @@ -1,405 +0,0 @@ -/* - 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" -#include "literals.h" - -using namespace asyncsrv; - -static String generateEventMessage(const char* message, const char* event, uint32_t id, uint32_t reconnect) { - String ev; - - if (reconnect) { - ev += T_retry_; - ev += reconnect; - ev += T_rn; - } - - if (id) { - ev += T_id__; - ev += id; - ev += T_rn; - } - - if (event != NULL) { - ev += T_event_; - ev += event; - ev += T_rn; - } - - 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 += T_data_; - ev += ldata; - ev += T_rnrn; - 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 += T_data_; - ev += ldata; - ev += T_rn; - free(ldata); - } - lineStart = nextLine; - if (lineStart == ((char*)message + messageLen)) - ev += T_rn; - } - } 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(T_Last_Event_ID)) - _lastId = atoi(request->getHeader(T_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(T_Last_Event_ID); - request->addInterestingHeader(T_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 = T_text_event_stream; - _sendContentLength = false; - addHeader(T_Cache_Control, T_no_cache); - addHeader(T_Connection, T_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/ESPAsyncWebServer/src/AsyncEventSource.h b/lib/ESPAsyncWebServer/src/AsyncEventSource.h deleted file mode 100644 index 0289ebf..0000000 --- a/lib/ESPAsyncWebServer/src/AsyncEventSource.h +++ /dev/null @@ -1,158 +0,0 @@ -/* - 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/ESPAsyncWebServer/src/AsyncJson.h b/lib/ESPAsyncWebServer/src/AsyncJson.h deleted file mode 100644 index bca3f24..0000000 --- a/lib/ESPAsyncWebServer/src/AsyncJson.h +++ /dev/null @@ -1,255 +0,0 @@ -// 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 "ChunkPrint.h" - -#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 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 = nullptr, 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 = nullptr) - : _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/ESPAsyncWebServer/src/AsyncMessagePack.h b/lib/ESPAsyncWebServer/src/AsyncMessagePack.h deleted file mode 100644 index 57a8824..0000000 --- a/lib/ESPAsyncWebServer/src/AsyncMessagePack.h +++ /dev/null @@ -1,145 +0,0 @@ -#pragma once - -/* - server.on("/msg_pack", HTTP_ANY, [](AsyncWebServerRequest * request) { - AsyncMessagePackResponse * response = new AsyncMessagePackResponse(); - JsonObject& root = response->getRoot(); - root["key1"] = "key number one"; - JsonObject& nested = root.createNestedObject("nested"); - nested["key1"] = "key number one"; - response->setLength(); - request->send(response); - }); - - -------------------- - - AsyncCallbackMessagePackWebHandler* handler = new AsyncCallbackMessagePackWebHandler("/msg_pack/endpoint"); - handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) { - JsonObject jsonObj = json.as(); - // ... - }); - server.addHandler(handler); -*/ - -#include -#include - -#include "ChunkPrint.h" -#include "literals.h" - -class AsyncMessagePackResponse : public AsyncAbstractResponse { - protected: - JsonDocument _jsonBuffer; - JsonVariant _root; - bool _isValid; - - public: - AsyncMessagePackResponse(bool isArray = false) : _isValid{false} { - _code = 200; - _contentType = asyncsrv::T_application_msgpack; - if (isArray) - _root = _jsonBuffer.add(); - else - _root = _jsonBuffer.add(); - } - - JsonVariant& getRoot() { return _root; } - - bool _sourceValid() const { return _isValid; } - - size_t setLength() { - _contentLength = measureMsgPack(_root); - if (_contentLength) { - _isValid = true; - } - return _contentLength; - } - - size_t getSize() const { return _jsonBuffer.size(); } - - size_t _fillBuffer(uint8_t* data, size_t len) { - ChunkPrint dest(data, _sentLength, len); - serializeMsgPack(_root, dest); - return len; - } -}; - -class AsyncCallbackMessagePackWebHandler : public AsyncWebHandler { - public: - typedef std::function ArJsonRequestHandlerFunction; - - protected: - const String _uri; - WebRequestMethodComposite _method; - ArJsonRequestHandlerFunction _onRequest; - size_t _contentLength; - size_t _maxContentLength; - - public: - AsyncCallbackMessagePackWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest = nullptr) - : _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {} - - 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(asyncsrv::T_application_msgpack)) - 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) { - JsonDocument jsonBuffer; - DeserializationError error = deserializeMsgPack(jsonBuffer, (uint8_t*)(request->_tempObject)); - - if (!error) { - JsonVariant json = jsonBuffer.as(); - _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; } -}; diff --git a/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp b/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp deleted file mode 100644 index 88d88ec..0000000 --- a/lib/ESPAsyncWebServer/src/AsyncWebSocket.cpp +++ /dev/null @@ -1,1207 +0,0 @@ -/* - 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 - -using namespace asyncsrv; - - -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; -} - -#ifdef ESP8266 -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()); -} - -#ifdef ESP8266 -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 // ESP8266 - -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()); -} - -#ifdef ESP8266 -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()); -} - -#ifdef ESP8266 -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 // ESP8266 - -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()); -} -#ifdef ESP8266 -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 // ESP8266 -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()); -} - -#ifdef ESP8266 -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 // ESP8266 - -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()); -} - -#ifdef ESP8266 -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 // ESP8266 - -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; -} - -#ifdef ESP8266 -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, T_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, T_WS); - 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/ESPAsyncWebServer/src/AsyncWebSocket.h b/lib/ESPAsyncWebServer/src/AsyncWebSocket.h deleted file mode 100644 index 34256a7..0000000 --- a/lib/ESPAsyncWebServer/src/AsyncWebSocket.h +++ /dev/null @@ -1,379 +0,0 @@ -/* - 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))); - - 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); - 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); - 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); - -#ifdef ESP8266 - size_t printf_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); - void text(const __FlashStringHelper* message); - void binary(const __FlashStringHelper* message, size_t len); -#endif -}; - -using AwsHandshakeHandler = std::function; -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); - 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); - 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); - 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); - 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))); - -#ifdef ESP8266 - void text(uint32_t id, const __FlashStringHelper* message); - void textAll(const __FlashStringHelper* message); - void binary(uint32_t id, const __FlashStringHelper* message, size_t len); - void binaryAll(const __FlashStringHelper* message, size_t len); - size_t printf_P(uint32_t id, PGM_P formatP, ...) __attribute__((format(printf, 3, 4))); - size_t printfAll_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3))); -#endif - - // 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/ESPAsyncWebServer/src/ChunkPrint.h b/lib/ESPAsyncWebServer/src/ChunkPrint.h deleted file mode 100644 index 2f40741..0000000 --- a/lib/ESPAsyncWebServer/src/ChunkPrint.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef CHUNKPRINT_H -#define CHUNKPRINT_H - -#include - -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); - } -}; -#endif diff --git a/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h b/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h deleted file mode 100644 index de08bc0..0000000 --- a/lib/ESPAsyncWebServer/src/ESPAsyncWebServer.h +++ /dev/null @@ -1,714 +0,0 @@ -/* - 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 - -#include "literals.h" - -#define ASYNCWEBSERVER_VERSION "3.1.5" -#define ASYNCWEBSERVER_VERSION_MAJOR 3 -#define ASYNCWEBSERVER_VERSION_MINOR 1 -#define ASYNCWEBSERVER_VERSION_REVISION 5 -#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 char* name, const char* value) : _name(name), _value(value) {} - AsyncWebHeader(const String& name, const String& value) : _name(name), _value(value) {} - AsyncWebHeader(const String& data) { - if (!data) - 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 { - String str = _name; - str.concat((char)0x3a); - str.concat((char)0x20); - str.concat(_value); - str.concat(asyncsrv::T_rn); - return str; - } -}; - -/* - * 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 char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, callback)); } - void send(int code, const String& contentType, const String& content = emptyString, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, callback)); } - - void send(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, len, callback)); } - void send(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, len, callback)); } - - void send(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) { - if (fs.exists(path) || (!download && fs.exists(path + asyncsrv::T__gz))) { - send(beginResponse(fs, path, contentType, download, callback)); - } else - send(404); - } - void send(FS& fs, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { send(fs, path, contentType.c_str(), download, callback); } - - void send(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) { - if (content) { - send(beginResponse(content, path, contentType, download, callback)); - } else - send(404); - } - void send(File content, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { send(content, path, contentType.c_str(), download, callback); } - - void send(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(stream, contentType, len, callback)); } - void send(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) { send(beginResponse(stream, contentType, len, callback)); } - - void send(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginResponse(contentType, len, callback, templateCallback)); } - void send(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginResponse(contentType, len, callback, templateCallback)); } - - void sendChunked(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginChunkedResponse(contentType, callback, templateCallback)); } - void sendChunked(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { send(beginChunkedResponse(contentType, callback, templateCallback)); } - - [[deprecated("Replaced by send(...)")]] - void send_P(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { - 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); - } - -#ifdef ESP8266 - void send(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) { send(beginResponse(code, contentType, content, callback)); } -#endif - - AsyncWebServerResponse* beginResponse(int code, const char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr); - AsyncWebServerResponse* beginResponse(int code, const String& contentType, const String& content = emptyString, AwsTemplateProcessor callback = nullptr) { return beginResponse(code, contentType.c_str(), content.c_str(), callback); } - - AsyncWebServerResponse* beginResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr); - AsyncWebServerResponse* beginResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { return beginResponse(code, contentType.c_str(), content, len, callback); } - - AsyncWebServerResponse* beginResponse(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); - AsyncWebServerResponse* beginResponse(FS& fs, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { return beginResponse(fs, path, contentType.c_str(), download, callback); } - - AsyncWebServerResponse* beginResponse(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); - AsyncWebServerResponse* beginResponse(File content, const String& path, const String& contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) { return beginResponse(content, path, contentType.c_str(), download, callback); } - - AsyncWebServerResponse* beginResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr); - AsyncWebServerResponse* beginResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) { return beginResponse(stream, contentType.c_str(), len, callback); } - - AsyncWebServerResponse* beginResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); - AsyncWebServerResponse* beginResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) { return beginResponse(contentType.c_str(), len, callback, templateCallback); } - - AsyncWebServerResponse* beginChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); - AsyncWebServerResponse* beginChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); - - AsyncResponseStream* beginResponseStream(const char* contentType, size_t bufferSize = 1460); - AsyncResponseStream* beginResponseStream(const String& contentType, size_t bufferSize = 1460) { return beginResponseStream(contentType.c_str(), bufferSize); } - - [[deprecated("Replaced by beginResponse(...)")]] - AsyncWebServerResponse* beginResponse_P(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) { - 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); - } - -#ifdef ESP8266 - AsyncWebServerResponse* beginResponse(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback = nullptr); -#endif - - size_t headers() const; // get header count - - // check if header exists - 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 char* name, bool post = false, bool file = false) const; - bool hasParam(const String& name, bool post = false, bool file = false) const { return hasParam(name.c_str(), post, file); }; -#ifdef ESP8266 - bool hasParam(const __FlashStringHelper* data, bool post = false, bool file = false) const { return hasParam(String(data).c_str(), post, file); }; -#endif - - /** - * @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; - - public: -#ifndef ESP8266 - static const char* responseCodeToString(int code); -#else - static const __FlashStringHelper* responseCodeToString(int code); -#endif - - public: - AsyncWebServerResponse(); - virtual ~AsyncWebServerResponse(); - virtual void setCode(int code); - virtual void setContentLength(size_t len); - void setContentType(const String& type) { setContentType(type.c_str()); } - virtual void setContentType(const char* type); - virtual void addHeader(const char* name, const char* value); - void addHeader(const String& name, const String& value) { addHeader(name.c_str(), value.c_str()); } - virtual String _assembleHead(uint8_t version); - virtual bool _started() const; - virtual bool _finished() const; - 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/ESPAsyncWebServer/src/WebAuthentication.cpp b/lib/ESPAsyncWebServer/src/WebAuthentication.cpp deleted file mode 100644 index b5962fc..0000000 --- a/lib/ESPAsyncWebServer/src/WebAuthentication.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* - 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 -#include "literals.h" - -using namespace asyncsrv; - -// 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(T_realm__); - if (realm == NULL) - header.concat(T_asyncesp); - else - header.concat(realm); - header.concat(T_auth_nonce); - header.concat(genRandomMD5()); - header.concat(T__opaque); - header.concat(genRandomMD5()); - header += (char)0x22; // '"' - 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 += (char)0x2c; // ',' - myHeader += (char)0x20; // ' ' - 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(T_username)) { - if (!avLine.equals(username)) { - // os_printf("AUTH FAIL: username\n"); - return false; - } - myUsername = avLine; - } else if (varName.equals(T_realm)) { - if (realm != NULL && !avLine.equals(realm)) { - // os_printf("AUTH FAIL: realm\n"); - return false; - } - myRealm = avLine; - } else if (varName.equals(T_nonce)) { - if (nonce != NULL && !avLine.equals(nonce)) { - // os_printf("AUTH FAIL: nonce\n"); - return false; - } - myNonce = avLine; - } else if (varName.equals(T_opaque)) { - if (opaque != NULL && !avLine.equals(opaque)) { - // os_printf("AUTH FAIL: opaque\n"); - return false; - } - } else if (varName.equals(T_uri)) { - if (uri != NULL && !avLine.equals(uri)) { - // os_printf("AUTH FAIL: uri\n"); - return false; - } - myUri = avLine; - } else if (varName.equals(T_response)) { - myResponse = avLine; - } else if (varName.equals(T_qop)) { - myQop = avLine; - } else if (varName.equals(T_nc)) { - myNc = avLine; - } else if (varName.equals(T_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/ESPAsyncWebServer/src/WebAuthentication.h b/lib/ESPAsyncWebServer/src/WebAuthentication.h deleted file mode 100644 index d519777..0000000 --- a/lib/ESPAsyncWebServer/src/WebAuthentication.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - 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/ESPAsyncWebServer/src/WebHandlerImpl.h b/lib/ESPAsyncWebServer/src/WebHandlerImpl.h deleted file mode 100644 index 22757d7..0000000 --- a/lib/ESPAsyncWebServer/src/WebHandlerImpl.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - 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/ESPAsyncWebServer/src/WebHandlers.cpp b/lib/ESPAsyncWebServer/src/WebHandlers.cpp deleted file mode 100644 index d904a39..0000000 --- a/lib/ESPAsyncWebServer/src/WebHandlers.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/* - 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" - -using namespace asyncsrv; - - -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(T_IMS)) { - request->_tempFile.close(); - request->send(304); // Not modified - } else if (_cache_control.length() && request->hasHeader(T_INM) && request->header(T_INM).equals(etag)) { - request->_tempFile.close(); - AsyncWebServerResponse* response = new AsyncBasicResponse(304); // Not modified - response->addHeader(T_Cache_Control, _cache_control.c_str()); - response->addHeader(T_ETag, etag.c_str()); - request->send(response); - } else { - AsyncWebServerResponse* response = new AsyncFileResponse(request->_tempFile, filename, String(), false, _callback); - if (_last_modified.length()) - response->addHeader(T_Last_Modified, _last_modified.c_str()); - if (_cache_control.length()) { - response->addHeader(T_Cache_Control, _cache_control.c_str()); - response->addHeader(T_ETag, etag.c_str()); - } - request->send(response); - } - } else { - request->send(404); - } -} diff --git a/lib/ESPAsyncWebServer/src/WebRequest.cpp b/lib/ESPAsyncWebServer/src/WebRequest.cpp deleted file mode 100644 index 95fda7e..0000000 --- a/lib/ESPAsyncWebServer/src/WebRequest.cpp +++ /dev/null @@ -1,985 +0,0 @@ -/* - 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" -#include "literals.h" -#include - -#define __is_param_char(c) ((c) && ((c) != '{') && ((c) != '[') && ((c) != '&') && ((c) != '=')) - -using namespace asyncsrv; - -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(T_app_xform_urlencoded)) { - _isPlainPost = true; - } else if (_contentType == T_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(T_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 == T_GET) { - _method = HTTP_GET; - } else if (m == T_POST) { - _method = HTTP_POST; - } else if (m == T_DELETE) { - _method = HTTP_DELETE; - } else if (m == T_PUT) { - _method = HTTP_PUT; - } else if (m == T_PATCH) { - _method = HTTP_PATCH; - } else if (m == T_HEAD) { - _method = HTTP_HEAD; - } else if (m == T_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(T_HTTP_1_0)) - _version = 1; - - _temp = emptyString; - return true; -} - -bool AsyncWebServerRequest::_parseReqHeader() { - int index = _temp.indexOf(':'); - if (index) { - String name(_temp.substring(0, index)); - String value(_temp.substring(index + 2)); - if (name.equalsIgnoreCase(T_Host)) { - _host = value; - } else if (name.equalsIgnoreCase(T_Content_Type)) { - _contentType = value.substring(0, value.indexOf(';')); - if (value.startsWith(T_MULTIPART_)) { - _boundary = value.substring(value.indexOf('=') + 1); - _boundary.replace(String('"'), String()); - _isMultipart = true; - } - } else if (name.equalsIgnoreCase(T_Content_Length)) { - _contentLength = atoi(value.c_str()); - } else if (name.equalsIgnoreCase(T_EXPECT) && value == T_100_CONTINUE) { - _expectingContinue = true; - } else if (name.equalsIgnoreCase(T_AUTH)) { - if (value.length() > 5 && value.substring(0, 5).equalsIgnoreCase(T_BASIC)) { - _authorization = value.substring(6); - } else if (value.length() > 6 && value.substring(0, 6).equalsIgnoreCase(T_DIGEST)) { - _isDigest = true; - _authorization = value.substring(7); - } - } else { - if (name.equalsIgnoreCase(T_UPGRADE) && value.equalsIgnoreCase(T_WS)) { - // WebSocket request can be uniquely identified by header: [Upgrade: websocket] - _reqconntype = RCT_WS; - } else if (name.equalsIgnoreCase(T_ACCEPT)) { - String lowcase(value); - lowcase.toLowerCase(); -#ifndef ESP8266 - const char* substr = std::strstr(lowcase.c_str(), T_text_event_stream); -#else - const char* substr = std::strstr(lowcase.c_str(), String(T_text_event_stream).c_str()); -#endif - if (substr != NULL) { - // WebEvent request can be uniquely identified by header: [Accept: text/event-stream] - _reqconntype = RCT_EVENT; - } - } - } - _headers.emplace_back(name, value); - } -#ifndef TARGET_RP2040 - _temp.clear(); -#else - // Ancient PRI core does not have String::clear() method 8-() - _temp = emptyString; -#endif - return true; -} - -void AsyncWebServerRequest::_parsePlainPostChar(uint8_t data) { - if (data && (char)data != '&') - _temp += (char)data; - if (!data || (char)data == '&' || _parsedLength == _contentLength) { - String name(T_BODY); - String value(_temp); - if (!(_temp.charAt(0) == '{') && !(_temp.charAt(0) == '[') && _temp.indexOf('=') > 0) { - name = _temp.substring(0, _temp.indexOf('=')); - value = _temp.substring(_temp.indexOf('=') + 1); - } - _params.emplace_back(urlDecode(name), urlDecode(value), true); - -#ifndef TARGET_RP2040 - _temp.clear(); -#else - // Ancient PRI core does not have String::clear() method 8-() - _temp = emptyString; -#endif - } -} - -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 = emptyString; - _itemName = emptyString; - _itemFilename = emptyString; - _itemType = emptyString; - } - - 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(T_Content_Type)) { - _itemType = _temp.substring(14); - _itemIsFile = true; - } else if (_temp.length() > 19 && _temp.substring(0, 19).equalsIgnoreCase(T_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 == T_name) { - _itemName = nameVal; - } else if (name == T_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 == T_name) { - _itemName = nameVal; - } else if (name == T_filename) { - _itemFilename = nameVal; - _itemIsFile = true; - } - } - _temp = emptyString; - } else { - _multiParseState = WAIT_FOR_RETURN1; - // value starts from here - _itemSize = 0; - _itemStartIndex = _parsedLength; - _itemValue = emptyString; - 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(T_HTTP_100_CONT); - _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 char* name, bool post, bool file) const { - for (const auto& p : _params) { - if (p.name().equals(name) && p.isPost() == post && p.isFile() == file) { - return true; - } - } - return false; -} - -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 char* contentType, const char* content, AwsTemplateProcessor callback) { - if (callback) - return new AsyncProgmemResponse(code, contentType, (const uint8_t*)content, strlen(content), callback); - return new AsyncBasicResponse(code, contentType, content); -} - -AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback) { - return new AsyncProgmemResponse(code, contentType, content, len, callback); -} - -AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(FS& fs, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) { - if (fs.exists(path) || (!download && fs.exists(path + T__gz))) - return new AsyncFileResponse(fs, path, contentType, download, callback); - return NULL; -} - -AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(File content, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) { - if (content == true) - return new AsyncFileResponse(content, path, contentType, download, callback); - return NULL; -} - -AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback) { - return new AsyncStreamResponse(stream, contentType, len, callback); -} - -AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) { - return new AsyncCallbackResponse(contentType, len, callback, templateCallback); -} - -AsyncWebServerResponse* AsyncWebServerRequest::beginChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback) { - if (_version) - return new AsyncChunkedResponse(contentType, callback, templateCallback); - return new AsyncCallbackResponse(contentType, 0, callback, templateCallback); -} - -AsyncResponseStream* AsyncWebServerRequest::beginResponseStream(const char* contentType, size_t bufferSize) { - return new AsyncResponseStream(contentType, bufferSize); -} - -#ifdef ESP8266 -AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback) { - return new AsyncProgmemResponse(code, contentType, (const uint8_t*)content, strlen_P(content), callback); -} -#endif - -void AsyncWebServerRequest::send(AsyncWebServerResponse* response) { - _response = response; - if (_response == NULL) { - _client->close(true); - _onDisconnect(); - return; - } - if (!_response->_sourceValid()) { - delete response; - _response = NULL; - send(500); - } else { - _client->setRxTimeout(0); - _response->_respond(this); - } -} - -void AsyncWebServerRequest::redirect(const char* url) { - AsyncWebServerResponse* response = beginResponse(302); - response->addHeader(T_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(T_WWW_AUTH, T_BASIC_REALM_LOGIN_REQ); - } else if (!isDigest) { - String header(T_BASIC_REALM); - header.concat(realm); - header += '"'; - r->addHeader(T_WWW_AUTH, header.c_str()); - } else { - String header(T_DIGEST_); - header.concat(requestDigestAuthentication(realm)); - r->addHeader(T_WWW_AUTH, header.c_str()); - } - 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 T_ANY; - if (_method & HTTP_GET) - return T_GET; - if (_method & HTTP_POST) - return T_POST; - if (_method & HTTP_DELETE) - return T_DELETE; - if (_method & HTTP_PUT) - return T_PUT; - if (_method & HTTP_PATCH) - return T_PATCH; - if (_method & HTTP_HEAD) - return T_HEAD; - if (_method & HTTP_OPTIONS) - return T_OPTIONS; - return T_UNKNOWN; -} -#else // ESP8266 -const __FlashStringHelper* AsyncWebServerRequest::methodToString() const { - if (_method == HTTP_ANY) - return FPSTR(T_ANY); - if (_method & HTTP_GET) - return FPSTR(T_GET); - if (_method & HTTP_POST) - return FPSTR(T_POST); - if (_method & HTTP_DELETE) - return FPSTR(T_DELETE); - if (_method & HTTP_PUT) - return FPSTR(T_PUT); - if (_method & HTTP_PATCH) - return FPSTR(T_PATCH); - if (_method & HTTP_HEAD) - return FPSTR(T_HEAD); - if (_method & HTTP_OPTIONS) - return FPSTR(T_OPTIONS); - return FPSTR(T_UNKNOWN); -} -#endif // ESP8266 - -#ifndef ESP8266 -const char* AsyncWebServerRequest::requestedConnTypeToString() const { - switch (_reqconntype) { - case RCT_NOT_USED: - return T_RCT_NOT_USED; - case RCT_DEFAULT: - return T_RCT_DEFAULT; - case RCT_HTTP: - return T_RCT_HTTP; - case RCT_WS: - return T_RCT_WS; - case RCT_EVENT: - return T_RCT_EVENT; - default: - return T_ERROR; - } -} -#else // ESP8266 -const __FlashStringHelper* AsyncWebServerRequest::requestedConnTypeToString() const { - switch (_reqconntype) { - case RCT_NOT_USED: - return FPSTR(T_RCT_NOT_USED); - case RCT_DEFAULT: - return FPSTR(T_RCT_DEFAULT); - case RCT_HTTP: - return FPSTR(T_RCT_HTTP); - case RCT_WS: - return FPSTR(T_RCT_WS); - case RCT_EVENT: - return FPSTR(T_RCT_EVENT); - default: - return FPSTR(T_ERROR); - } -} -#endif // ESP8266 - -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/ESPAsyncWebServer/src/WebResponseImpl.h b/lib/ESPAsyncWebServer/src/WebResponseImpl.h deleted file mode 100644 index a6f71bb..0000000 --- a/lib/ESPAsyncWebServer/src/WebResponseImpl.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - 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 -#include "literals.h" - -// 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: - explicit AsyncBasicResponse(int code, const char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty); - AsyncBasicResponse(int code, const String& contentType, const String& content = emptyString) : AsyncBasicResponse(code, contentType.c_str(), content.c_str()) {} - void _respond(AsyncWebServerRequest* request); - size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time); - bool _sourceValid() const { return true; } -}; - -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 _setContentTypeFromPath(const String& path); - - public: - AsyncFileResponse(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); - AsyncFileResponse(FS& fs, const String& path, const String& contentType, bool download = false, AwsTemplateProcessor callback = nullptr) : AsyncFileResponse(fs, path, contentType.c_str(), download, callback) {} - AsyncFileResponse(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr); - AsyncFileResponse(File content, const String& path, const String& contentType, bool download = false, AwsTemplateProcessor callack = nullptr) : AsyncFileResponse(content, path, contentType.c_str(), download, callack) {} - ~AsyncFileResponse(); - bool _sourceValid() const { return !!(_content); } - virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; -}; - -class AsyncStreamResponse : public AsyncAbstractResponse { - private: - Stream* _content; - - public: - AsyncStreamResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr); - AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) : AsyncStreamResponse(stream, contentType.c_str(), len, callback) {} - bool _sourceValid() const { return !!(_content); } - virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; -}; - -class AsyncCallbackResponse : public AsyncAbstractResponse { - private: - AwsResponseFiller _content; - size_t _filledLength; - - public: - AsyncCallbackResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); - AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) : AsyncCallbackResponse(contentType.c_str(), len, callback, templateCallback) {} - bool _sourceValid() const { return !!(_content); } - virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; -}; - -class AsyncChunkedResponse : public AsyncAbstractResponse { - private: - AwsResponseFiller _content; - size_t _filledLength; - - public: - AsyncChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr); - AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) : AsyncChunkedResponse(contentType.c_str(), callback, templateCallback) {} - bool _sourceValid() const { return !!(_content); } - virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; -}; - -class AsyncProgmemResponse : public AsyncAbstractResponse { - private: - const uint8_t* _content; - size_t _readLength; - - public: - AsyncProgmemResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr); - AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) : AsyncProgmemResponse(code, contentType.c_str(), content, len, callback) {} - bool _sourceValid() const { return true; } - virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; -}; - -class cbuf; - -class AsyncResponseStream : public AsyncAbstractResponse, public Print { - private: - std::unique_ptr _content; - - public: - AsyncResponseStream(const char* contentType, size_t bufferSize); - AsyncResponseStream(const String& contentType, size_t bufferSize) : AsyncResponseStream(contentType.c_str(), bufferSize) {} - ~AsyncResponseStream(); - bool _sourceValid() const { return (_state < RESPONSE_END); } - virtual size_t _fillBuffer(uint8_t* buf, size_t maxLen) override; - 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/ESPAsyncWebServer/src/WebResponses.cpp b/lib/ESPAsyncWebServer/src/WebResponses.cpp deleted file mode 100644 index f1994b1..0000000 --- a/lib/ESPAsyncWebServer/src/WebResponses.cpp +++ /dev/null @@ -1,849 +0,0 @@ -/* - 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" - -using namespace asyncsrv; - -// 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 - * - */ - -#ifndef ESP8266 -const char* AsyncWebServerResponse::responseCodeToString(int code) { - switch (code) { - case 100: - return T_HTTP_CODE_100; - case 101: - return T_HTTP_CODE_101; - case 200: - return T_HTTP_CODE_200; - case 201: - return T_HTTP_CODE_201; - case 202: - return T_HTTP_CODE_202; - case 203: - return T_HTTP_CODE_203; - case 204: - return T_HTTP_CODE_204; - case 205: - return T_HTTP_CODE_205; - case 206: - return T_HTTP_CODE_206; - case 300: - return T_HTTP_CODE_300; - case 301: - return T_HTTP_CODE_301; - case 302: - return T_HTTP_CODE_302; - case 303: - return T_HTTP_CODE_303; - case 304: - return T_HTTP_CODE_304; - case 305: - return T_HTTP_CODE_305; - case 307: - return T_HTTP_CODE_307; - case 400: - return T_HTTP_CODE_400; - case 401: - return T_HTTP_CODE_401; - case 402: - return T_HTTP_CODE_402; - case 403: - return T_HTTP_CODE_403; - case 404: - return T_HTTP_CODE_404; - case 405: - return T_HTTP_CODE_405; - case 406: - return T_HTTP_CODE_406; - case 407: - return T_HTTP_CODE_407; - case 408: - return T_HTTP_CODE_408; - case 409: - return T_HTTP_CODE_409; - case 410: - return T_HTTP_CODE_410; - case 411: - return T_HTTP_CODE_411; - case 412: - return T_HTTP_CODE_412; - case 413: - return T_HTTP_CODE_413; - case 414: - return T_HTTP_CODE_414; - case 415: - return T_HTTP_CODE_415; - case 416: - return T_HTTP_CODE_416; - case 417: - return T_HTTP_CODE_417; - case 500: - return T_HTTP_CODE_500; - case 501: - return T_HTTP_CODE_501; - case 502: - return T_HTTP_CODE_502; - case 503: - return T_HTTP_CODE_503; - case 504: - return T_HTTP_CODE_504; - case 505: - return T_HTTP_CODE_505; - default: - return T_HTTP_CODE_ANY; - } -} -#else // ESP8266 -const __FlashStringHelper* AsyncWebServerResponse::responseCodeToString(int code) -{ - switch (code) { - case 100: - return FPSTR(T_HTTP_CODE_100); - case 101: - return FPSTR(T_HTTP_CODE_101); - case 200: - return FPSTR(T_HTTP_CODE_200); - case 201: - return FPSTR(T_HTTP_CODE_201); - case 202: - return FPSTR(T_HTTP_CODE_202); - case 203: - return FPSTR(T_HTTP_CODE_203); - case 204: - return FPSTR(T_HTTP_CODE_204); - case 205: - return FPSTR(T_HTTP_CODE_205); - case 206: - return FPSTR(T_HTTP_CODE_206); - case 300: - return FPSTR(T_HTTP_CODE_300); - case 301: - return FPSTR(T_HTTP_CODE_301); - case 302: - return FPSTR(T_HTTP_CODE_302); - case 303: - return FPSTR(T_HTTP_CODE_303); - case 304: - return FPSTR(T_HTTP_CODE_304); - case 305: - return FPSTR(T_HTTP_CODE_305); - case 307: - return FPSTR(T_HTTP_CODE_307); - case 400: - return FPSTR(T_HTTP_CODE_400); - case 401: - return FPSTR(T_HTTP_CODE_401); - case 402: - return FPSTR(T_HTTP_CODE_402); - case 403: - return FPSTR(T_HTTP_CODE_403); - case 404: - return FPSTR(T_HTTP_CODE_404); - case 405: - return FPSTR(T_HTTP_CODE_405); - case 406: - return FPSTR(T_HTTP_CODE_406); - case 407: - return FPSTR(T_HTTP_CODE_407); - case 408: - return FPSTR(T_HTTP_CODE_408); - case 409: - return FPSTR(T_HTTP_CODE_409); - case 410: - return FPSTR(T_HTTP_CODE_410); - case 411: - return FPSTR(T_HTTP_CODE_411); - case 412: - return FPSTR(T_HTTP_CODE_412); - case 413: - return FPSTR(T_HTTP_CODE_413); - case 414: - return FPSTR(T_HTTP_CODE_414); - case 415: - return FPSTR(T_HTTP_CODE_415); - case 416: - return FPSTR(T_HTTP_CODE_416); - case 417: - return FPSTR(T_HTTP_CODE_417); - case 500: - return FPSTR(T_HTTP_CODE_500); - case 501: - return FPSTR(T_HTTP_CODE_501); - case 502: - return FPSTR(T_HTTP_CODE_502); - case 503: - return FPSTR(T_HTTP_CODE_503); - case 504: - return FPSTR(T_HTTP_CODE_504); - case 505: - return FPSTR(T_HTTP_CODE_505); - default: - return FPSTR(T_HTTP_CODE_ANY); - } -} -#endif // ESP8266 - -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 char* type) { - if (_state == RESPONSE_SETUP) - _contentType = type; -} - -void AsyncWebServerResponse::addHeader(const char* name, const char* value) { - _headers.emplace_back(name, value); -} - -String AsyncWebServerResponse::_assembleHead(uint8_t version) { - if (version) { - addHeader(T_Accept_Ranges, T_none); - if (_chunked) - addHeader(Transfer_Encoding, T_chunked); - } - String out; - int bufSize = 300; - char buf[bufSize]; - -#ifndef ESP8266 - snprintf(buf, bufSize, "HTTP/1.%d %d %s\r\n", version, _code, responseCodeToString(_code)); -#else - snprintf_P(buf, bufSize, PSTR("HTTP/1.%d %d %s\r\n"), version, _code, String(responseCodeToString(_code)).c_str()); -#endif - 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(T_rn); - _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 char* contentType, const char* content) { - _code = code; - _content = content; - _contentType = contentType; - if (_content.length()) { - _contentLength = _content.length(); - if (!_contentType.length()) - _contentType = T_text_plain; - } - addHeader(T_Connection, T_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 = emptyString; - _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(T_Connection, T_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 = emptyString; - } - - 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::_setContentTypeFromPath(const String& path) { -#if HAVE_EXTERN_GET_Content_Type_FUNCTION - #ifndef ESP8266 - extern const char* getContentType(const String& path); - #else - extern const __FlashStringHelper* getContentType(const String& path); - #endif - _contentType = getContentType(path); -#else - if (path.endsWith(T__html)) - _contentType = T_text_html; - else if (path.endsWith(T__htm)) - _contentType = T_text_html; - else if (path.endsWith(T__css)) - _contentType = T_text_css; - else if (path.endsWith(T__json)) - _contentType = T_application_json; - else if (path.endsWith(T__js)) - _contentType = T_application_javascript; - else if (path.endsWith(T__png)) - _contentType = T_image_png; - else if (path.endsWith(T__gif)) - _contentType = T_image_gif; - else if (path.endsWith(T__jpg)) - _contentType = T_image_jpeg; - else if (path.endsWith(T__ico)) - _contentType = T_image_x_icon; - else if (path.endsWith(T__svg)) - _contentType = T_image_svg_xml; - else if (path.endsWith(T__eot)) - _contentType = T_font_eot; - else if (path.endsWith(T__woff)) - _contentType = T_font_woff; - else if (path.endsWith(T__woff2)) - _contentType = T_font_woff2; - else if (path.endsWith(T__ttf)) - _contentType = T_font_ttf; - else if (path.endsWith(T__xml)) - _contentType = T_text_xml; - else if (path.endsWith(T__pdf)) - _contentType = T_application_pdf; - else if (path.endsWith(T__zip)) - _contentType = T_application_zip; - else if (path.endsWith(T__gz)) - _contentType = T_application_x_gzip; - else - _contentType = T_text_plain; -#endif -} - -AsyncFileResponse::AsyncFileResponse(FS& fs, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { - _code = 200; - _path = path; - - if (!download && !fs.exists(_path) && fs.exists(_path + T__gz)) { - _path = _path + T__gz; - addHeader(T_Content_Encoding, T_gzip); - _callback = nullptr; // Unable to process zipped templates - _sendContentLength = true; - _chunked = false; - } - - _content = fs.open(_path, fs::FileOpenMode::read); - _contentLength = _content.size(); - - if (strlen(contentType) == 0) - _setContentTypeFromPath(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(T_Content_Disposition, buf); -} - -AsyncFileResponse::AsyncFileResponse(File content, const String& path, const char* contentType, bool download, AwsTemplateProcessor callback) : AsyncAbstractResponse(callback) { - _code = 200; - _path = path; - - if (!download && String(content.name()).endsWith(T__gz) && !path.endsWith(T__gz)) { - addHeader(T_Content_Encoding, T_gzip); - _callback = nullptr; // Unable to process gzipped templates - _sendContentLength = true; - _chunked = false; - } - - _content = content; - _contentLength = _content.size(); - - if (strlen(contentType) == 0) - _setContentTypeFromPath(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(T_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 char* 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 char* 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 char* 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 char* 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 char* 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/ESPAsyncWebServer/src/WebServer.cpp b/lib/ESPAsyncWebServer/src/WebServer.cpp deleted file mode 100644 index d7c9a02..0000000 --- a/lib/ESPAsyncWebServer/src/WebServer.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* - 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" - -using namespace asyncsrv; - -bool ON_STA_FILTER(AsyncWebServerRequest* request) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 - return WiFi.localIP() == request->client()->localIP(); - #else - return false; - #endif -} - -bool ON_AP_FILTER(AsyncWebServerRequest* request) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 - return WiFi.localIP() != request->client()->localIP(); - #else - return false; - #endif -} - -#ifndef HAVE_FS_FILE_OPEN_MODE -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(T_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/ESPAsyncWebServer/src/literals.h b/lib/ESPAsyncWebServer/src/literals.h deleted file mode 100644 index 8a7293b..0000000 --- a/lib/ESPAsyncWebServer/src/literals.h +++ /dev/null @@ -1,345 +0,0 @@ -#pragma once - -namespace asyncsrv { - -static constexpr const char* empty = ""; - -#ifndef ESP8622 -static constexpr const char* T_100_CONTINUE = "100-continue"; -static constexpr const char* T_ACCEPT = "Accept"; -static constexpr const char* T_Accept_Ranges = "Accept-Ranges"; -static constexpr const char* T_app_xform_urlencoded = "application/x-www-form-urlencoded"; -static constexpr const char* T_AUTH = "Authorization"; -static constexpr const char* T_BASIC = "Basic"; -static constexpr const char* T_BASIC_REALM = "Basic realm=\""; -static constexpr const char* T_BASIC_REALM_LOGIN_REQ = "Basic realm=\"Login Required\""; -static constexpr const char* T_BODY = "body"; -static constexpr const char* T_Cache_Control = "Cache-Control"; -static constexpr const char* T_chunked = "chunked"; -static constexpr const char* T_close = "close"; -static constexpr const char* T_Connection = "Connection"; -static constexpr const char* T_Content_Disposition = "Content-Disposition"; -static constexpr const char* T_Content_Encoding = "Content-Encoding"; -static constexpr const char* T_Content_Length = "Content-Length"; -static constexpr const char* T_Content_Type = "Content-Type"; -static constexpr const char* T_Cookie = "Cookie"; -static constexpr const char* T_DIGEST = "Digest"; -static constexpr const char* T_DIGEST_ = "Digest "; -static constexpr const char* T_ETag = "ETag"; -static constexpr const char* T_EXPECT = "Expect"; -static constexpr const char* T_HTTP_1_0 = "HTTP/1.0"; -static constexpr const char* T_HTTP_100_CONT = "HTTP/1.1 100 Continue\r\n\r\n"; -static constexpr const char* T_IMS = "If-Modified-Since"; -static constexpr const char* T_INM = "If-None-Match"; -static constexpr const char* T_keep_alive = "keep-alive"; -static constexpr const char* T_Last_Event_ID = "Last-Event-ID"; -static constexpr const char* T_Last_Modified = "Last-Modified"; -static constexpr const char* T_LOCATION = "Location"; -static constexpr const char* T_MULTIPART_ = "multipart/"; -static constexpr const char* T_no_cache = "no-cache"; -static constexpr const char* T_none = "none"; -static constexpr const char* T_UPGRADE = "Upgrade"; -static constexpr const char* T_WS = "websocket"; -static constexpr const char* T_WWW_AUTH = "WWW-Authenticate"; -static constexpr const char* Transfer_Encoding = "Transfer-Encoding"; - -// HTTP Methods -static constexpr const char* T_ANY = "ANY"; -static constexpr const char* T_GET = "GET"; -static constexpr const char* T_POST = "POST"; -static constexpr const char* T_PUT = "PUT"; -static constexpr const char* T_DELETE = "DELETE"; -static constexpr const char* T_PATCH = "PATCH"; -static constexpr const char* T_HEAD = "HEAD"; -static constexpr const char* T_OPTIONS = "OPTIONS"; -static constexpr const char* T_UNKNOWN = "UNKNOWN"; - -// Req content types -static constexpr const char* T_RCT_NOT_USED = "RCT_NOT_USED"; -static constexpr const char* T_RCT_DEFAULT = "RCT_DEFAULT"; -static constexpr const char* T_RCT_HTTP = "RCT_HTTP"; -static constexpr const char* T_RCT_WS = "RCT_WS"; -static constexpr const char* T_RCT_EVENT = "RCT_EVENT"; -static constexpr const char* T_ERROR = "ERROR"; - -// extentions & MIME-Types -static constexpr const char* T__css = ".css"; -static constexpr const char* T__eot = ".eot"; -static constexpr const char* T__gif = ".gif"; -static constexpr const char* T__gz = ".gz"; -static constexpr const char* T__htm = ".htm"; -static constexpr const char* T__html = ".html"; -static constexpr const char* T__ico = ".ico"; -static constexpr const char* T__jpg = ".jpg"; -static constexpr const char* T__js = ".js"; -static constexpr const char* T__json = ".json"; -static constexpr const char* T__pdf = ".pdf"; -static constexpr const char* T__png = ".png"; -static constexpr const char* T__svg = ".svg"; -static constexpr const char* T__ttf = ".ttf"; -static constexpr const char* T__woff = ".woff"; -static constexpr const char* T__woff2 = ".woff2"; -static constexpr const char* T__xml = ".xml"; -static constexpr const char* T__zip = ".zip"; -static constexpr const char* T_application_javascript = "application/javascript"; -static constexpr const char* T_application_json = "application/json"; -static constexpr const char* T_application_msgpack = "application/msgpack"; -static constexpr const char* T_application_pdf = "application/pdf"; -static constexpr const char* T_application_x_gzip = "application/x-gzip"; -static constexpr const char* T_application_zip = "application/zip"; -static constexpr const char* T_font_eot = "font/eot"; -static constexpr const char* T_font_ttf = "font/ttf"; -static constexpr const char* T_font_woff = "font/woff"; -static constexpr const char* T_font_woff2 = "font/woff2"; -static constexpr const char* T_image_gif = "image/gif"; -static constexpr const char* T_image_jpeg = "image/jpeg"; -static constexpr const char* T_image_png = "image/png"; -static constexpr const char* T_image_svg_xml = "image/svg+xml"; -static constexpr const char* T_image_x_icon = "image/x-icon"; -static constexpr const char* T_text_css = "text/css"; -static constexpr const char* T_text_event_stream = "text/event-stream"; -static constexpr const char* T_text_html = "text/html"; -static constexpr const char* T_text_plain = "text/plain"; -static constexpr const char* T_text_xml = "text/xml"; - -// Responce codes -static constexpr const char* T_HTTP_CODE_100 = "Continue"; -static constexpr const char* T_HTTP_CODE_101 = "Switching Protocols"; -static constexpr const char* T_HTTP_CODE_200 = "OK"; -static constexpr const char* T_HTTP_CODE_201 = "Created"; -static constexpr const char* T_HTTP_CODE_202 = "Accepted"; -static constexpr const char* T_HTTP_CODE_203 = "Non-Authoritative Information"; -static constexpr const char* T_HTTP_CODE_204 = "No Content"; -static constexpr const char* T_HTTP_CODE_205 = "Reset Content"; -static constexpr const char* T_HTTP_CODE_206 = "Partial Content"; -static constexpr const char* T_HTTP_CODE_300 = "Multiple Choices"; -static constexpr const char* T_HTTP_CODE_301 = "Moved Permanently"; -static constexpr const char* T_HTTP_CODE_302 = "Found"; -static constexpr const char* T_HTTP_CODE_303 = "See Other"; -static constexpr const char* T_HTTP_CODE_304 = "Not Modified"; -static constexpr const char* T_HTTP_CODE_305 = "Use Proxy"; -static constexpr const char* T_HTTP_CODE_307 = "Temporary Redirect"; -static constexpr const char* T_HTTP_CODE_400 = "Bad Request"; -static constexpr const char* T_HTTP_CODE_401 = "Unauthorized"; -static constexpr const char* T_HTTP_CODE_402 = "Payment Required"; -static constexpr const char* T_HTTP_CODE_403 = "Forbidden"; -static constexpr const char* T_HTTP_CODE_404 = "Not Found"; -static constexpr const char* T_HTTP_CODE_405 = "Method Not Allowed"; -static constexpr const char* T_HTTP_CODE_406 = "Not Acceptable"; -static constexpr const char* T_HTTP_CODE_407 = "Proxy Authentication Required"; -static constexpr const char* T_HTTP_CODE_408 = "Request Time-out"; -static constexpr const char* T_HTTP_CODE_409 = "Conflict"; -static constexpr const char* T_HTTP_CODE_410 = "Gone"; -static constexpr const char* T_HTTP_CODE_411 = "Length Required"; -static constexpr const char* T_HTTP_CODE_412 = "Precondition Failed"; -static constexpr const char* T_HTTP_CODE_413 = "Request Entity Too Large"; -static constexpr const char* T_HTTP_CODE_414 = "Request-URI Too Large"; -static constexpr const char* T_HTTP_CODE_415 = "Unsupported Media Type"; -static constexpr const char* T_HTTP_CODE_416 = "Requested range not satisfiable"; -static constexpr const char* T_HTTP_CODE_417 = "Expectation Failed"; -static constexpr const char* T_HTTP_CODE_500 = "Internal Server Error"; -static constexpr const char* T_HTTP_CODE_501 = "Not Implemented"; -static constexpr const char* T_HTTP_CODE_502 = "Bad Gateway"; -static constexpr const char* T_HTTP_CODE_503 = "Service Unavailable"; -static constexpr const char* T_HTTP_CODE_504 = "Gateway Time-out"; -static constexpr const char* T_HTTP_CODE_505 = "HTTP Version not supported"; -static constexpr const char* T_HTTP_CODE_ANY = "Unknown code"; - -// other -static constexpr const char* T__opaque = "\", opaque=\""; -static constexpr const char* T_13 = "13"; -static constexpr const char* T_asyncesp = "asyncesp"; -static constexpr const char* T_auth_nonce = "\", qop=\"auth\", nonce=\""; -static constexpr const char* T_cnonce = "cnonce"; -static constexpr const char* T_data_ = "data: "; -static constexpr const char* T_event_ = "event: "; -static constexpr const char* T_filename = "filename"; -static constexpr const char* T_gzip = "gzip"; -static constexpr const char* T_Host = "Host"; -static constexpr const char* T_id__ = "id: "; -static constexpr const char* T_name = "name"; -static constexpr const char* T_nc = "nc"; -static constexpr const char* T_nonce = "nonce"; -static constexpr const char* T_opaque = "opaque"; -static constexpr const char* T_qop = "qop"; -static constexpr const char* T_realm = "realm"; -static constexpr const char* T_realm__ = "realm=\""; -static constexpr const char* T_response = "response"; -static constexpr const char* T_retry_ = "retry: "; -static constexpr const char* T_rn = "\r\n"; -static constexpr const char* T_rnrn = "\r\n\r\n"; -static constexpr const char* T_uri = "uri"; -static constexpr const char* T_username = "username"; - - -#else // ESP8622 - -static const char T_100_CONTINUE[] PROGMEM = "100-continue"; -static const char T_ACCEPT[] PROGMEM = "Accept"; -static const char T_Accept_Ranges[] PROGMEM = "Accept-Ranges"; -static const char T_app_xform_urlencoded[] PROGMEM = "application/x-www-form-urlencoded"; -static const char T_AUTH[] PROGMEM = "Authorization"; -static const char T_BASIC[] PROGMEM = "Basic"; -static const char T_BASIC_REALM[] PROGMEM = "Basic realm=\""; -static const char T_BASIC_REALM_LOGIN_REQ[] PROGMEM = "Basic realm=\"Login Required\""; -static const char T_BODY[] PROGMEM = "body"; -static const char T_Cache_Control[] PROGMEM = "Cache-Control"; -static const char T_chunked[] PROGMEM = "chunked"; -static const char T_close[] PROGMEM = "close"; -static const char T_Connection[] PROGMEM = "Connection"; -static const char T_Content_Disposition[] PROGMEM = "Content-Disposition"; -static const char T_Content_Encoding[] PROGMEM = "Content-Encoding"; -static const char T_Content_Length[] PROGMEM = "Content-Length"; -static const char T_Content_Type[] PROGMEM = "Content-Type"; -static const char T_Cookie[] PROGMEM = "Cookie"; -static const char T_DIGEST[] PROGMEM = "Digest"; -static const char T_DIGEST_[] PROGMEM = "Digest "; -static const char T_ETag[] PROGMEM = "ETag"; -static const char T_EXPECT[] PROGMEM = "Expect"; -static const char T_HTTP_1_0[] PROGMEM = "HTTP/1.0"; -static const char T_HTTP_100_CONT[] PROGMEM = "HTTP/1.1 100 Continue\r\n\r\n"; -static const char T_IMS[] PROGMEM = "If-Modified-Since"; -static const char T_INM[] PROGMEM = "If-None-Match"; -static const char T_keep_alive[] PROGMEM = "keep-alive"; -static const char T_Last_Event_ID[] PROGMEM = "Last-Event-ID"; -static const char T_Last_Modified[] PROGMEM = "Last-Modified"; -static const char T_LOCATION[] PROGMEM = "Location"; -static const char T_MULTIPART_[] PROGMEM = "multipart/"; -static const char T_no_cache[] PROGMEM = "no-cache"; -static const char T_none[] PROGMEM = "none"; -static const char T_UPGRADE[] PROGMEM = "Upgrade"; -static const char T_WS[] PROGMEM = "websocket"; -static const char T_WWW_AUTH[] PROGMEM = "WWW-Authenticate"; -static const char Transfer_Encoding[] PROGMEM = "Transfer-Encoding"; - -// HTTP Methods -static const char T_ANY[] PROGMEM = "ANY"; -static const char T_GET[] PROGMEM = "GET"; -static const char T_POST[] PROGMEM = "POST"; -static const char T_PUT[] PROGMEM = "PUT"; -static const char T_DELETE[] PROGMEM = "DELETE"; -static const char T_PATCH[] PROGMEM = "PATCH"; -static const char T_HEAD[] PROGMEM = "HEAD"; -static const char T_OPTIONS[] PROGMEM = "OPTIONS"; -static const char T_UNKNOWN[] PROGMEM = "UNKNOWN"; - -// Req content types -static const char T_RCT_NOT_USED[] PROGMEM = "RCT_NOT_USED"; -static const char T_RCT_DEFAULT[] PROGMEM = "RCT_DEFAULT"; -static const char T_RCT_HTTP[] PROGMEM = "RCT_HTTP"; -static const char T_RCT_WS[] PROGMEM = "RCT_WS"; -static const char T_RCT_EVENT[] PROGMEM = "RCT_EVENT"; -static const char T_ERROR[] PROGMEM = "ERROR"; - -// extentions & MIME-Types -static const char T__css[] PROGMEM = ".css"; -static const char T__eot[] PROGMEM = ".eot"; -static const char T__gif[] PROGMEM = ".gif"; -static const char T__gz[] PROGMEM = ".gz"; -static const char T__htm[] PROGMEM = ".htm"; -static const char T__html[] PROGMEM = ".html"; -static const char T__ico[] PROGMEM = ".ico"; -static const char T__jpg[] PROGMEM = ".jpg"; -static const char T__js[] PROGMEM = ".js"; -static const char T__json[] PROGMEM = ".json"; -static const char T__pdf[] PROGMEM = ".pdf"; -static const char T__png[] PROGMEM = ".png"; -static const char T__svg[] PROGMEM = ".svg"; -static const char T__ttf[] PROGMEM = ".ttf"; -static const char T__woff[] PROGMEM = ".woff"; -static const char T__woff2[] PROGMEM = ".woff2"; -static const char T__xml[] PROGMEM = ".xml"; -static const char T__zip[] PROGMEM = ".zip"; -static const char T_application_javascript[] PROGMEM = "application/javascript"; -static const char T_application_json[] PROGMEM = "application/json"; -static const char T_application_msgpack[] PROGMEM = "application/msgpack"; -static const char T_application_pdf[] PROGMEM = "application/pdf"; -static const char T_application_x_gzip[] PROGMEM = "application/x-gzip"; -static const char T_application_zip[] PROGMEM = "application/zip"; -static const char T_font_eot[] PROGMEM = "font/eot"; -static const char T_font_ttf[] PROGMEM = "font/ttf"; -static const char T_font_woff[] PROGMEM = "font/woff"; -static const char T_font_woff2[] PROGMEM = "font/woff2"; -static const char T_image_gif[] PROGMEM = "image/gif"; -static const char T_image_jpeg[] PROGMEM = "image/jpeg"; -static const char T_image_png[] PROGMEM = "image/png"; -static const char T_image_svg_xml[] PROGMEM = "image/svg+xml"; -static const char T_image_x_icon[] PROGMEM = "image/x-icon"; -static const char T_text_css[] PROGMEM = "text/css"; -static const char T_text_event_stream[] PROGMEM = "text/event-stream"; -static const char T_text_html[] PROGMEM = "text/html"; -static const char T_text_plain[] PROGMEM = "text/plain"; -static const char T_text_xml[] PROGMEM = "text/xml"; - -// Responce codes -static const char T_HTTP_CODE_100[] PROGMEM = "Continue"; -static const char T_HTTP_CODE_101[] PROGMEM = "Switching Protocols"; -static const char T_HTTP_CODE_200[] PROGMEM = "OK"; -static const char T_HTTP_CODE_201[] PROGMEM = "Created"; -static const char T_HTTP_CODE_202[] PROGMEM = "Accepted"; -static const char T_HTTP_CODE_203[] PROGMEM = "Non-Authoritative Information"; -static const char T_HTTP_CODE_204[] PROGMEM = "No Content"; -static const char T_HTTP_CODE_205[] PROGMEM = "Reset Content"; -static const char T_HTTP_CODE_206[] PROGMEM = "Partial Content"; -static const char T_HTTP_CODE_300[] PROGMEM = "Multiple Choices"; -static const char T_HTTP_CODE_301[] PROGMEM = "Moved Permanently"; -static const char T_HTTP_CODE_302[] PROGMEM = "Found"; -static const char T_HTTP_CODE_303[] PROGMEM = "See Other"; -static const char T_HTTP_CODE_304[] PROGMEM = "Not Modified"; -static const char T_HTTP_CODE_305[] PROGMEM = "Use Proxy"; -static const char T_HTTP_CODE_307[] PROGMEM = "Temporary Redirect"; -static const char T_HTTP_CODE_400[] PROGMEM = "Bad Request"; -static const char T_HTTP_CODE_401[] PROGMEM = "Unauthorized"; -static const char T_HTTP_CODE_402[] PROGMEM = "Payment Required"; -static const char T_HTTP_CODE_403[] PROGMEM = "Forbidden"; -static const char T_HTTP_CODE_404[] PROGMEM = "Not Found"; -static const char T_HTTP_CODE_405[] PROGMEM = "Method Not Allowed"; -static const char T_HTTP_CODE_406[] PROGMEM = "Not Acceptable"; -static const char T_HTTP_CODE_407[] PROGMEM = "Proxy Authentication Required"; -static const char T_HTTP_CODE_408[] PROGMEM = "Request Time-out"; -static const char T_HTTP_CODE_409[] PROGMEM = "Conflict"; -static const char T_HTTP_CODE_410[] PROGMEM = "Gone"; -static const char T_HTTP_CODE_411[] PROGMEM = "Length Required"; -static const char T_HTTP_CODE_412[] PROGMEM = "Precondition Failed"; -static const char T_HTTP_CODE_413[] PROGMEM = "Request Entity Too Large"; -static const char T_HTTP_CODE_414[] PROGMEM = "Request-URI Too Large"; -static const char T_HTTP_CODE_415[] PROGMEM = "Unsupported Media Type"; -static const char T_HTTP_CODE_416[] PROGMEM = "Requested range not satisfiable"; -static const char T_HTTP_CODE_417[] PROGMEM = "Expectation Failed"; -static const char T_HTTP_CODE_500[] PROGMEM = "Internal Server Error"; -static const char T_HTTP_CODE_501[] PROGMEM = "Not Implemented"; -static const char T_HTTP_CODE_502[] PROGMEM = "Bad Gateway"; -static const char T_HTTP_CODE_503[] PROGMEM = "Service Unavailable"; -static const char T_HTTP_CODE_504[] PROGMEM = "Gateway Time-out"; -static const char T_HTTP_CODE_505[] PROGMEM = "HTTP Version not supported"; -static const char T_HTTP_CODE_ANY[] PROGMEM = "Unknown code"; - -// other -static const char T__opaque[] PROGMEM = "\", opaque=\""; -static const char T_13[] PROGMEM = "13"; -static const char T_asyncesp[] PROGMEM = "asyncesp"; -static const char T_auth_nonce[] PROGMEM = "\", qop=\"auth\", nonce=\""; -static const char T_cnonce[] PROGMEM = "cnonce"; -static const char T_data_[] PROGMEM = "data: "; -static const char T_event_[] PROGMEM = "event: "; -static const char T_filename[] PROGMEM = "filename"; -static const char T_gzip[] PROGMEM = "gzip"; -static const char T_Host[] PROGMEM = "Host"; -static const char T_id__[] PROGMEM = "id: "; -static const char T_name[] PROGMEM = "name"; -static const char T_nc[] PROGMEM = "nc"; -static const char T_nonce[] PROGMEM = "nonce"; -static const char T_opaque[] PROGMEM = "opaque"; -static const char T_qop[] PROGMEM = "qop"; -static const char T_realm[] PROGMEM = "realm"; -static const char T_realm__[] PROGMEM = "realm=\""; -static const char T_response[] PROGMEM = "response"; -static const char T_retry_[] PROGMEM = "retry: "; -static const char T_rn[] PROGMEM = "\r\n"; -static const char T_rnrn[] PROGMEM = "\r\n\r\n"; -static const char T_uri[] PROGMEM = "uri"; -static const char T_username[] PROGMEM = "username"; - -#endif // ESP8622 - -} // namespace asyncsrv {} diff --git a/lib/ESPAsyncWebServer/src/port/SHA1Builder.cpp b/lib/ESPAsyncWebServer/src/port/SHA1Builder.cpp deleted file mode 100644 index 901fb80..0000000 --- a/lib/ESPAsyncWebServer/src/port/SHA1Builder.cpp +++ /dev/null @@ -1,284 +0,0 @@ -/* - * 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/ESPAsyncWebServer/src/port/SHA1Builder.h b/lib/ESPAsyncWebServer/src/port/SHA1Builder.h deleted file mode 100644 index da9a77a..0000000 --- a/lib/ESPAsyncWebServer/src/port/SHA1Builder.h +++ /dev/null @@ -1,39 +0,0 @@ -// 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/MqttLogger/src/MqttLogger.cpp b/lib/MqttLogger/src/MqttLogger.cpp index d1b1c71..3ac5be3 100644 --- a/lib/MqttLogger/src/MqttLogger.cpp +++ b/lib/MqttLogger/src/MqttLogger.cpp @@ -7,7 +7,7 @@ MqttLogger::MqttLogger(MqttLoggerMode mode) this->setBufferSize(MQTT_MAX_PACKET_SIZE); } -MqttLogger::MqttLogger(MqttClient& client, const char* topic, MqttLoggerMode mode) +MqttLogger::MqttLogger(esp_mqtt_client_handle_t client, const char* topic, MqttLoggerMode mode) { this->setClient(client); this->setTopic(topic); @@ -19,9 +19,9 @@ MqttLogger::~MqttLogger() { } -void MqttLogger::setClient(MqttClient& client) +void MqttLogger::setClient(esp_mqtt_client_handle_t client) { - this->client = &client; + this->client = client; } void MqttLogger::setTopic(const char* topic) @@ -69,29 +69,30 @@ boolean MqttLogger::setBufferSize(uint16_t size) } // send & reset current buffer -void MqttLogger::sendBuffer() +void MqttLogger::sendBuffer() { if (this->bufferCnt > 0) { bool doSerial = this->mode==MqttLoggerMode::SerialOnly || this->mode==MqttLoggerMode::MqttAndSerial || this->mode==MqttLoggerMode::MqttAndSerialAndWeb || this->mode==MqttLoggerMode::SerialAndWeb; bool doWebSerial = this->mode==MqttLoggerMode::MqttAndSerialAndWeb || this->mode==MqttLoggerMode::SerialAndWeb; - - if (this->mode!=MqttLoggerMode::SerialOnly && this->mode!=MqttLoggerMode::SerialAndWeb && this->client != NULL && this->client->connected()) + + if (this->mode!=MqttLoggerMode::SerialOnly && this->mode!=MqttLoggerMode::SerialAndWeb) { - this->client->publish(topic, 0, true, this->buffer, this->bufferCnt); - } else if (this->mode == MqttLoggerMode::MqttAndSerialFallback) + esp_mqtt_client_publish(this->client, topic, (const char*)this->buffer, this->bufferCnt, 1, 1); + } + else if (this->mode == MqttLoggerMode::MqttAndSerialFallback) { doSerial = true; } - if (doSerial) + if (doSerial) { Serial.write(this->buffer, this->bufferCnt); Serial.println(); } if (doWebSerial) { - WebSerial.write(this->buffer, this->bufferCnt); - WebSerial.println(); + //WebSerial.write(this->buffer, this->bufferCnt); + //WebSerial.println(); } this->bufferCnt=0; } diff --git a/lib/MqttLogger/src/MqttLogger.h b/lib/MqttLogger/src/MqttLogger.h index 6f30a6f..56dc300 100644 --- a/lib/MqttLogger/src/MqttLogger.h +++ b/lib/MqttLogger/src/MqttLogger.h @@ -11,8 +11,8 @@ #include #include -#include -#include "MycilaWebSerial.h" +#include +//#include "MycilaWebSerial.h" #define MQTT_MAX_PACKET_SIZE 1024 @@ -31,17 +31,18 @@ private: const char* topic; uint8_t* buffer; uint8_t* bufferEnd; - uint16_t bufferCnt = 0, bufferSize = 0; - MqttClient* client; + uint16_t bufferCnt = 0; + uint16_t bufferSize = 0; + esp_mqtt_client_handle_t client; MqttLoggerMode mode; void sendBuffer(); public: MqttLogger(MqttLoggerMode mode=MqttLoggerMode::MqttAndSerialFallback); - MqttLogger(MqttClient& client, const char* topic, MqttLoggerMode mode=MqttLoggerMode::MqttAndSerialFallback); + MqttLogger(esp_mqtt_client_handle_t client, const char* topic, MqttLoggerMode mode=MqttLoggerMode::MqttAndSerialFallback); ~MqttLogger(); - void setClient(MqttClient& client); + void setClient(esp_mqtt_client_handle_t client); void setTopic(const char* topic); void setMode(MqttLoggerMode mode); void setRetained(boolean retained); diff --git a/lib/MycilaWebSerial/LICENSE b/lib/MycilaWebSerial/LICENSE deleted file mode 100644 index 2b5457c..0000000 --- a/lib/MycilaWebSerial/LICENSE +++ /dev/null @@ -1,10 +0,0 @@ -The MIT License (MIT) ---------------------- - -Copyright © 2023-2024, Mathieu Carbou - -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/MycilaWebSerial/README.md b/lib/MycilaWebSerial/README.md deleted file mode 100644 index c3c399c..0000000 --- a/lib/MycilaWebSerial/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# MycilaWebSerial - -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Continuous Integration](https://github.com/mathieucarbou/MycilaWebSerial/actions/workflows/ci.yml/badge.svg)](https://github.com/mathieucarbou/MycilaWebSerial/actions/workflows/ci.yml) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/MycilaWebSerial.svg)](https://registry.platformio.org/libraries/mathieucarbou/MycilaWebSerial) - -MycilaWebSerial 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 library is based on the UI from [asjdf/WebSerialLite](https://github.com/asjdf/WebSerialLite) (and this part falls under GPL v3). - -## Changes - -- 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/MycilaWebSerial/docs/_config.yml b/lib/MycilaWebSerial/docs/_config.yml deleted file mode 100644 index 6868c50..0000000 --- a/lib/MycilaWebSerial/docs/_config.yml +++ /dev/null @@ -1,8 +0,0 @@ -# bundle exec jekyll serve --host=0.0.0.0 - -title: MycilaWebSerial -description: "MycilaWebSerial 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/MycilaWebSerial/docs/index.md b/lib/MycilaWebSerial/docs/index.md deleted file mode 100644 index c3c399c..0000000 --- a/lib/MycilaWebSerial/docs/index.md +++ /dev/null @@ -1,67 +0,0 @@ -# MycilaWebSerial - -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Continuous Integration](https://github.com/mathieucarbou/MycilaWebSerial/actions/workflows/ci.yml/badge.svg)](https://github.com/mathieucarbou/MycilaWebSerial/actions/workflows/ci.yml) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/mathieucarbou/library/MycilaWebSerial.svg)](https://registry.platformio.org/libraries/mathieucarbou/MycilaWebSerial) - -MycilaWebSerial 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 library is based on the UI from [asjdf/WebSerialLite](https://github.com/asjdf/WebSerialLite) (and this part falls under GPL v3). - -## Changes - -- 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/MycilaWebSerial/examples/HighPerf/HighPerf.ino b/lib/MycilaWebSerial/examples/HighPerf/HighPerf.ino deleted file mode 100644 index ff636f9..0000000 --- a/lib/MycilaWebSerial/examples/HighPerf/HighPerf.ino +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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/MycilaWebSerial/examples/Logging/Logging.ino b/lib/MycilaWebSerial/examples/Logging/Logging.ino deleted file mode 100644 index 8a025d3..0000000 --- a/lib/MycilaWebSerial/examples/Logging/Logging.ino +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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/MycilaWebSerial/library.json b/lib/MycilaWebSerial/library.json deleted file mode 100644 index 11d5beb..0000000 --- a/lib/MycilaWebSerial/library.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "MycilaWebSerial", - "version": "6.3.0", - "keywords": "MycilaWebSerial, serial, monitor, ESP8266, ESP32, webpage, websocket, wireless", - "description": "MycilaWebSerial is a webpage based Serial Monitor to log, monitor, or debug your code remotely.", - "homepage": "https://github.com/mathieucarbou/MycilaWebSerial", - "repository": { - "type": "git", - "url": "https://github.com/mathieucarbou/MycilaWebSerial.git" - }, - "authors": [ - { - "name": "Mathieu Carbou", - "email": "mathieu.carbou@gmail.com", - "maintainer": true - } - ], - "license": "MIT", - "frameworks": "arduino", - "platforms": ["espressif8266", "espressif32"], - "headers": ["MycilaWebSerial.h"], - "dependencies": [ - { - "owner": "mathieucarbou", - "name": "ESPAsyncWebServer", - "version": "^3.1.2", - "platforms": ["espressif8266", "espressif32"] - } - ], - "export": { - "include": [ - "examples", - "src", - "library.json", - "library.properties", - "LICENSE", - "README.md" - ] - } -} diff --git a/lib/MycilaWebSerial/library.properties b/lib/MycilaWebSerial/library.properties deleted file mode 100644 index 5989f0e..0000000 --- a/lib/MycilaWebSerial/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=MycilaWebSerial -version=6.3.0 -author=Mathieu Carbou -category=Communication -maintainer=Mathieu Carbou -sentence=A Web based Serial Monitor for ESP8266 & ESP32 to debug your code remotely. -paragraph=MycilaWebSerial is a webpage based Serial Monitor to log, monitor, or debug your code remotely. -url=https://github.com/mathieucarbou/MycilaWebSerial -architectures=esp8266,esp32 -license=MIT diff --git a/lib/MycilaWebSerial/platformio.ini b/lib/MycilaWebSerial/platformio.ini deleted file mode 100644 index 1912fed..0000000 --- a/lib/MycilaWebSerial/platformio.ini +++ /dev/null @@ -1,42 +0,0 @@ -[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/ESPAsyncWebServer @ 3.1.2 -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.8.1 -board = esp32dev - -[env:arduino-3] -platform = espressif32 -platform_packages= - platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.4 - platformio/framework-arduinoespressif32-libs @ https://github.com/espressif/arduino-esp32/releases/download/3.0.4/esp32-arduino-libs-3.0.4.zip -board = esp32dev - -[env:esp8266] -platform = espressif8266 -board = huzzah -lib_deps = - mathieucarbou/ESPAsyncWebServer @ 3.1.2 diff --git a/lib/MycilaWebSerial/portal/LICENSE b/lib/MycilaWebSerial/portal/LICENSE deleted file mode 100644 index f288702..0000000 --- a/lib/MycilaWebSerial/portal/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - 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/MycilaWebSerial/portal/README.md b/lib/MycilaWebSerial/portal/README.md deleted file mode 100644 index 44b4230..0000000 --- a/lib/MycilaWebSerial/portal/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Frontend - -The `index.html` is the only page of MycilaWebSerial 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/MycilaWebSerial/portal/finalize.js b/lib/MycilaWebSerial/portal/finalize.js deleted file mode 100644 index e10b7fd..0000000 --- a/lib/MycilaWebSerial/portal/finalize.js +++ /dev/null @@ -1,66 +0,0 @@ -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 = -` -// SPDX-License-Identifier: GPL-3.0-or-later -#pragma once -const uint32_t WEBSERIAL_HTML_SIZE = ${GZIPPED_INDEX.length}; -const uint8_t WEBSERIAL_HTML[] PROGMEM = { -${ addLineBreaks(GZIPPED_INDEX) } -}; -`; - - fs.writeFileSync(path.resolve(__dirname, SAVE_PATH+'/MycilaWebSerialPage.h'), FILE); - console.log(`[finalize.js] Compressed Bundle into MycilaWebSerialPage.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/MycilaWebSerial/portal/index.html b/lib/MycilaWebSerial/portal/index.html deleted file mode 100644 index 5c4e9fc..0000000 --- a/lib/MycilaWebSerial/portal/index.html +++ /dev/null @@ -1,368 +0,0 @@ - - - - - - - Web Console - - - - - -
-

Web Console

- - - - -
-
- - - -
- - -
-

-

- - - - \ No newline at end of file diff --git a/lib/MycilaWebSerial/portal/package-lock.json b/lib/MycilaWebSerial/portal/package-lock.json deleted file mode 100644 index e66710c..0000000 --- a/lib/MycilaWebSerial/portal/package-lock.json +++ /dev/null @@ -1,240 +0,0 @@ -{ - "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/MycilaWebSerial/portal/package.json b/lib/MycilaWebSerial/portal/package.json deleted file mode 100644 index d6aec35..0000000 --- a/lib/MycilaWebSerial/portal/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "scripts": { - "build": "node finalize.js" - }, - "dependencies": { - "@gfx/zopfli": "^1.0.15", - "html-minifier-terser": "^7.1.0" - } -} diff --git a/lib/MycilaWebSerial/portal/pnpm-lock.yaml b/lib/MycilaWebSerial/portal/pnpm-lock.yaml deleted file mode 100644 index cffcb68..0000000 --- a/lib/MycilaWebSerial/portal/pnpm-lock.yaml +++ /dev/null @@ -1,177 +0,0 @@ -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/MycilaWebSerial/src/MycilaWebSerial.cpp b/lib/MycilaWebSerial/src/MycilaWebSerial.cpp deleted file mode 100644 index d4c331d..0000000 --- a/lib/MycilaWebSerial/src/MycilaWebSerial.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// SPDX-License-Identifier: MIT -/* - * Copyright (C) 2023-2024 Mathieu Carbou - */ -#include "MycilaWebSerial.h" - -#include "MycilaWebSerialPage.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) { - _recvString = callback; - _recv = [&](uint8_t* data, size_t len) { - if (data && len) { - String msg; - msg.reserve(len); - msg.concat((char*)data); - _recvString(msg); - } - }; -} - -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/MycilaWebSerial/src/MycilaWebSerial.h b/lib/MycilaWebSerial/src/MycilaWebSerial.h deleted file mode 100644 index 4770618..0000000 --- a/lib/MycilaWebSerial/src/MycilaWebSerial.h +++ /dev/null @@ -1,70 +0,0 @@ -// SPDX-License-Identifier: MIT -/* - * Copyright (C) 2023-2024 Mathieu Carbou - */ -#pragma once - -#if defined(ESP8266) -#include "ESP8266WiFi.h" -#elif defined(ESP32) -#include "WiFi.h" -#endif - -#include -#include -#include - -#define WSL_VERSION "6.3.0" -#define WSL_VERSION_MAJOR 6 -#define WSL_VERSION_MINOR 3 -#define WSL_VERSION_REVISION 0 - -#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; - WSLStringMessageHandler _recvString = 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; diff --git a/lib/MycilaWebSerial/src/MycilaWebSerialPage.h b/lib/MycilaWebSerial/src/MycilaWebSerialPage.h deleted file mode 100644 index 8d4bf37..0000000 --- a/lib/MycilaWebSerial/src/MycilaWebSerialPage.h +++ /dev/null @@ -1,84 +0,0 @@ - -// SPDX-License-Identifier: GPL-3.0-or-later -#pragma once -const uint32_t WEBSERIAL_HTML_SIZE = 2320; -const uint8_t WEBSERIAL_HTML[] PROGMEM = { -31,139,8,0,0,0,0,0,2,3,116,85,247,146,179,54,16,127,21,197,95,202,57,99,225,242,117,48,78,239, -189,231,95,33,45,160,156,144,136,36,184,115,24,222,61,139,4,87,231,238,108,107,181,179,229,183,85,199,119,132, -225,254,220,2,169,125,163,78,199,249,23,152,56,29,27,240,140,240,154,89,7,62,239,124,73,223,44,60,163,61, -104,159,175,190,249,34,7,81,193,10,149,125,75,225,223,78,246,249,223,244,143,79,232,103,166,105,153,151,133,130, -211,209,75,143,199,95,80,144,207,140,118,70,193,113,27,89,15,140,93,73,225,235,92,64,47,57,208,112,217,72, -45,189,100,138,58,206,20,228,251,21,209,172,129,188,151,112,213,26,235,79,71,231,207,104,71,200,126,16,210,181, -138,157,211,66,25,126,57,178,161,97,182,146,58,77,94,88,104,50,15,215,158,10,224,198,34,38,163,83,109,52, -140,31,110,210,148,149,30,44,158,5,148,198,194,64,175,160,184,148,158,22,230,154,58,249,159,212,85,42,117,13, -86,250,236,49,107,108,23,39,59,178,35,123,244,51,22,70,156,7,211,131,117,220,26,165,104,1,53,235,165,177, -193,97,86,131,172,106,159,238,119,187,247,178,16,94,36,23,35,89,203,132,64,251,72,149,152,18,90,178,70,170, -115,74,89,219,42,160,238,236,60,52,155,120,208,78,110,62,85,82,95,254,192,248,111,129,243,37,106,108,86,191, -65,101,128,252,241,205,106,243,171,41,140,55,155,213,215,160,122,240,146,51,242,35,116,176,218,56,166,29,117,8, -191,28,147,144,21,142,169,7,59,4,154,41,89,233,52,114,198,164,178,236,60,112,163,16,254,179,87,175,94,239, -223,188,29,19,87,51,97,174,134,82,42,20,73,133,53,45,141,172,139,29,121,209,94,147,231,248,181,85,129,183, -233,127,75,146,221,235,245,154,220,151,59,160,204,225,145,220,171,245,122,76,174,104,217,41,53,220,38,103,66,33, -197,77,113,167,11,178,88,75,15,3,254,166,201,203,41,235,73,169,224,250,70,102,186,76,106,8,115,34,233,68, -165,251,49,249,167,115,94,150,103,42,49,91,142,130,22,195,61,78,10,26,77,91,211,105,1,98,40,140,21,96, -169,101,66,118,110,113,227,128,79,221,51,220,105,133,89,14,57,89,193,248,101,21,244,233,156,180,242,77,249,182, -100,99,210,48,169,239,193,203,2,48,33,109,52,152,162,124,215,232,108,193,51,15,68,16,165,206,51,235,179,80, -153,25,104,172,207,157,110,18,125,29,157,144,164,101,90,131,26,90,227,100,176,108,65,49,47,123,200,34,80,196, -84,150,51,77,195,236,164,206,40,41,22,86,76,124,8,55,187,159,130,169,189,31,133,24,205,69,37,206,20,191, -152,74,70,104,152,133,117,108,98,204,19,164,13,160,141,102,110,116,234,77,155,30,230,148,70,188,164,232,188,199, -196,242,206,58,180,218,26,25,34,92,230,225,13,54,203,126,135,63,72,60,182,106,58,175,164,134,24,78,24,180, -37,216,93,118,7,229,99,236,187,221,171,215,229,139,7,24,82,172,19,43,20,136,225,177,194,75,246,106,255,234, -237,141,194,51,11,28,29,13,13,198,52,23,227,121,114,8,185,91,144,199,76,90,8,120,123,176,211,32,170,236, -169,5,49,62,155,42,143,124,26,177,220,150,145,21,88,166,206,67,134,185,91,140,78,14,35,253,80,111,73,231, -211,17,48,133,88,136,195,64,134,206,77,173,0,10,184,159,147,119,163,53,37,14,246,47,196,77,56,135,185,16, -217,189,101,155,221,228,115,135,163,104,204,180,78,22,141,169,19,8,130,124,170,121,198,132,155,246,28,98,89,116, -112,152,16,125,131,170,113,180,13,243,84,65,233,135,64,166,19,185,176,163,94,228,7,122,60,110,227,139,112,220, -198,23,108,90,200,167,163,144,61,225,138,57,151,175,194,152,204,131,76,238,44,192,21,190,121,123,34,69,30,94, -38,18,172,228,75,152,152,151,7,239,87,189,63,29,25,169,45,148,249,150,156,142,178,169,38,93,101,42,67,80, -214,90,99,115,132,143,133,254,30,89,23,107,226,44,207,183,10,105,68,198,238,1,138,107,145,132,157,70,166,253, -70,98,123,173,162,20,90,189,95,220,211,49,158,139,254,188,177,72,180,179,66,247,92,73,126,153,99,76,216,152, -76,125,166,128,233,139,53,62,149,125,69,152,149,140,214,82,8,208,185,183,29,16,193,60,163,18,61,228,2,20, -120,32,165,84,42,231,157,181,152,149,207,166,50,145,210,240,46,140,68,94,50,245,63,173,85,181,237,214,14,3, -127,69,55,239,210,146,101,89,86,46,115,15,190,148,222,187,92,56,204,252,245,149,189,147,148,185,93,49,206,140, -33,123,76,231,207,96,90,234,191,165,48,182,223,195,127,31,223,252,54,51,133,8,62,183,30,103,48,93,228,161, -248,253,215,120,4,236,192,211,223,102,219,30,2,41,182,86,179,93,161,115,99,204,133,50,138,83,69,211,41,172, -229,34,109,224,192,81,133,5,9,166,87,206,107,201,184,97,170,84,131,204,2,73,41,247,60,203,85,150,198,160, -164,144,201,192,251,111,199,152,244,64,52,196,69,114,75,129,103,165,4,50,39,7,75,96,153,230,145,239,104,209, -22,132,0,131,73,159,142,145,15,18,45,141,230,24,205,215,220,189,245,238,25,28,199,16,232,87,216,7,29,211, -193,197,76,166,112,119,136,194,12,188,150,141,175,176,202,78,102,189,170,114,55,11,231,251,199,136,44,156,136,116, -97,39,124,166,159,179,103,71,221,132,255,15,142,175,183,142,163,254,211,155,245,217,39,13,62,8,213,15,180,55, -11,168,233,14,154,63,22,237,246,86,238,95,175,82,198,36,190,140,107,217,189,13,10,184,215,97,41,128,136,87, -34,163,131,15,185,236,218,24,58,53,208,128,166,176,99,202,109,106,17,53,92,112,209,232,177,206,237,253,30,109, -231,104,57,77,51,51,205,65,10,37,44,6,197,34,221,17,245,54,96,14,96,112,48,184,62,191,181,104,217,255, -224,221,161,26,131,49,175,73,0,37,219,78,9,191,51,235,221,182,186,66,229,116,85,242,59,171,82,249,221,117, -84,242,19,117,226,4,83,202,144,184,79,133,191,215,138,121,184,123,248,44,30,17,135,39,177,100,222,4,62,189, -102,90,95,52,216,118,207,218,193,15,60,26,74,146,208,252,35,166,100,48,233,87,229,224,206,133,57,42,170,254, -122,196,21,138,17,31,212,50,39,93,52,136,236,238,144,193,133,91,168,74,224,140,185,10,38,51,178,81,138,120, -190,170,65,196,101,14,3,133,37,186,172,173,248,149,41,175,77,223,220,168,130,101,39,219,42,170,125,181,228,66, -229,177,184,55,70,37,237,94,163,247,223,154,6,214,33,96,116,24,48,248,149,212,66,125,105,11,25,36,18,40, -193,100,48,42,7,201,130,129,36,76,214,66,61,20,62,84,14,41,164,152,168,30,72,32,152,231,77,122,70,181, -147,232,84,177,231,93,244,161,133,20,133,151,149,88,5,147,235,32,16,254,43,57,158,193,132,161,61,25,57,225, -185,187,187,49,47,91,153,201,145,78,224,180,237,127,127,11,132,54,228,124,164,73,214,89,190,101,151,98,135,185, -189,227,186,160,170,65,117,241,20,134,113,146,97,183,54,114,189,159,197,201,72,198,23,215,156,194,12,148,225,140, -109,228,70,63,243,221,179,33,162,253,104,58,186,26,173,198,183,94,232,204,56,6,141,39,246,118,9,54,195,171, -151,65,180,129,229,19,156,2,28,72,113,178,227,136,66,13,255,108,252,28,42,11,7,234,72,254,61,48,91,189, -222,117,188,41,104,196,188,64,152,250,139,157,24,85,198,230,93,162,91,187,187,55,206,15,204,95,238,66,186,135, -33,201,2,193,187,11,218,138,33,216,71,37,184,215,251,71,207,10,74,66,244,132,241,238,137,219,231,39,42,170, -143,1,238,238,42,93,60,29,27,91,213,71,242,199,175,148,130,22,15,37,94,232,246,116,24,57,218,83,193,244, -204,16,74,228,19,38,130,48,101,252,76,65,159,111,148,244,243,138,104,230,21,73,252,92,70,230,11,175,238,26, -141,243,203,91,53,4,116,235,190,30,36,65,162,139,70,228,131,223,2,202,82,221,174,244,20,183,197,216,12,164, -203,113,249,1,137,104,89,140,2,123,187,147,18,184,243,252,195,155,215,184,11,181,1,10,108,235,212,20,165,20, -81,130,30,218,81,119,1,49,58,244,95,130,170,27,80,208,20,35,140,39,204,22,152,88,27,89,114,101,181,3, -46,105,32,190,82,74,153,188,61,141,51,212,151,122,108,129,146,31,46,2,168,199,170,252,149,61,8,170,153,13, -10,2,225,178,0,176,192,99,211,192,41,57,101,124,29,214,25,191,216,44,134,41,68,98,83,106,56,200,150,182, -154,58,104,59,173,116,53,1,45,43,253,6,31,9,221,135,131,140,7,238,153,112,16,199,70,13,29,239,149,127, -75,185,97,142,173,244,35,247,92,238,69,240,64,225,130,93,184,120,149,80,248,69,182,45,123,87,222,116,152,180, -5,86,66,170,235,37,86,8,135,147,9,79,44,249,197,158,103,41,70,225,196,189,126,33,208,106,98,163,73,138, -179,66,38,149,30,18,41,65,184,238,120,135,94,22,99,108,43,205,67,208,111,121,233,176,177,58,7,180,115,204, -176,41,72,242,131,228,212,97,224,161,178,192,132,173,240,72,82,65,230,131,173,209,37,101,57,249,149,145,28,114, -242,83,147,121,60,230,196,190,42,247,32,151,129,220,57,210,102,51,186,144,11,23,210,143,213,68,118,72,79,125, -83,79,34,78,110,22,211,212,149,36,132,95,214,232,220,128,125,166,209,30,106,54,37,215,202,222,108,182,220,96, -212,44,142,62,88,92,251,138,92,84,129,120,243,246,209,107,92,67,208,185,122,13,191,69,189,171,22,240,42,108, -180,5,13,232,130,18,23,0,97,142,189,230,234,187,233,63,170,40,30,237,131,182,47,199,198,130,134,154,146,135, -111,94,33,232,172,163,85,170,128,130,112,26,179,138,121,76,14,105,180,133,224,217,233,53,13,114,167,231,255,151, -253,15,145,100,45,14,173,21,0,0 -}; diff --git a/lib/PsychicHttp/CHANGELOG.md b/lib/PsychicHttp/CHANGELOG.md new file mode 100644 index 0000000..ca99a11 --- /dev/null +++ b/lib/PsychicHttp/CHANGELOG.md @@ -0,0 +1,34 @@ +# v1.2.1 + +* Fix bug with missing include preventing the HTTPS server from compiling. + +# v1.2 + +* Added TemplatePrinter from https://github.com/Chris--A/PsychicHttp/tree/templatePrint +* Support using as ESP IDF component +* Optional using https server in ESP IDF +* Fixed bug with headers +* Add ESP IDF example + CI script +* Added Arduino Captive Portal example and OTAUpdate from @06GitHub +* HTTPS fix for ESP-IDF v5.0.2+ from @06GitHub +* lots of bugfixes from @mathieucarbou + +Thanks to @Chris--A, @06GitHub, and @dzungpv for your contributions. + +# v1.1 + +* Changed the internal structure to support request handlers on endpoints and generic requests that do not match an endpoint + * websockets, uploads, etc should now create an appropriate handler and attach to an endpoint with the server.on() syntax +* Added PsychicClient to abstract away some of the internals of ESP-IDF sockets + add convenience + * onOpen and onClose callbacks have changed as a result +* Added support for EventSource / SSE +* Added support for multipart file uploads +* changed getParam() to return a PsychicWebParameter in line with ESPAsyncWebserver +* Renamed various classes / files: + * PsychicHttpFileResponse -> PsychicFileResponse + * PsychicHttpServerEndpoint -> PsychicEndpoint + * PsychicHttpServerRequest -> PsychicRequest + * PsychicHttpServerResponse -> PsychicResponse + * PsychicHttpWebsocket.h -> PsychicWebSocket.h + * Websocket => WebSocket +* Quite a few bugfixes from the community. Thank you @glennsky, @gb88, @KastanEr, @kstam, and @zekageri \ No newline at end of file diff --git a/lib/ESPAsyncWebServer/CMakeLists.txt b/lib/PsychicHttp/CMakeLists.txt similarity index 82% rename from lib/ESPAsyncWebServer/CMakeLists.txt rename to lib/PsychicHttp/CMakeLists.txt index 64292ec..4f76477 100644 --- a/lib/ESPAsyncWebServer/CMakeLists.txt +++ b/lib/PsychicHttp/CMakeLists.txt @@ -8,7 +8,9 @@ set(COMPONENT_ADD_INCLUDEDIRS set(COMPONENT_REQUIRES "arduino-esp32" - "AsyncTCP" + "esp_https_server" + "ArduinoJson" + "UrlEncode" ) register_component() diff --git a/lib/PsychicHttp/LICENSE b/lib/PsychicHttp/LICENSE new file mode 100644 index 0000000..8e797d9 --- /dev/null +++ b/lib/PsychicHttp/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2024 Jeremy Poulter, Zachary Smith, and Mathieu Carbou + +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. \ No newline at end of file diff --git a/lib/PsychicHttp/README.md b/lib/PsychicHttp/README.md new file mode 100644 index 0000000..5c4289e --- /dev/null +++ b/lib/PsychicHttp/README.md @@ -0,0 +1,826 @@ +# PsychicHttp - HTTP on your ESP 🧙🔮 + +PsychicHttp is a webserver library for ESP32 + Arduino framework which uses the [ESP-IDF HTTP Server](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html) library under the hood. It is written in a similar style to the [Arduino WebServer](https://github.com/espressif/arduino-esp32/tree/master/libraries/WebServer), [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer), and [ArduinoMongoose](https://github.com/jeremypoulter/ArduinoMongoose) libraries to make writing code simple and porting from those other libraries straightforward. + +# Features + +* Asynchronous approach (server runs in its own FreeRTOS thread) +* Handles all HTTP methods with lots of convenience functions: + * GET/POST parameters + * get/set headers + * get/set cookies + * basic key/value session data storage + * authentication (basic and digest mode) +* HTTPS / SSL support +* Static fileserving (SPIFFS, LittleFS, etc.) +* Chunked response serving for large files +* File uploads (Basic + Multipart) +* Websocket support with onOpen, onFrame, and onClose callbacks +* EventSource / SSE support with onOpen, and onClose callbacks +* Request filters, including Client vs AP mode (ON_STA_FILTER / ON_AP_FILTER) +* TemplatePrinter class for dynamic variables at runtime + +## Differences from ESPAsyncWebserver + +* No templating system (anyone actually use this?) +* No url rewriting (but you can use request->redirect) + +# Usage + +## Installation + +### Platformio + +[PlatformIO](http://platformio.org) is an open source ecosystem for IoT development. + + Add "PsychicHttp" to project using [Project Configuration File `platformio.ini`](http://docs.platformio.org/page/projectconf.html) and [lib_deps](http://docs.platformio.org/page/projectconf/section_env_library.html#lib-deps) option: + +```ini +[env:myboard] +platform = espressif... +board = ... +framework = arduino + +# using the latest stable version +lib_deps = hoeken/PsychicHttp + +# or using GIT Url (the latest development version) +lib_deps = https://github.com/hoeken/PsychicHttp +``` + +### Installation - Arduino + +Open *Tools -> Manage Libraries...* and search for PsychicHttp. + +# Principles of Operation + +## Things to Note + +* PsychicHttp is a fully asynchronous server and as such does not run on the loop thread. +* You should not use yield or delay or any function that uses them inside the callbacks. +* The server is smart enough to know when to close the connection and free resources. +* You can not send more than one response to a single request. + +## PsychicHttp + +* Listens for connections. +* Wraps the incoming request into PsychicRequest. +* Keeps track of clients + calls optional callbacks on client open and close. +* Find the appropriate handler (if any) for a request and pass it on. + +## Request Life Cycle + +* TCP connection is received by the server. +* HTTP request is wrapped inside ```PsychicRequest``` object + TCP Connection wrapped inside PsychicConnection object. +* When the request head is received, the server goes through all ```PsychicEndpoints``` and finds one that matches the url + method. + * ```handler->filter()``` and ```handler->canHandle()``` are called on the handler to verify the handler should process the request. + * ```handler->needsAuthentication()``` is called and sends an authorization response if required. + * ```handler->handleRequest()``` is called to actually process the HTTP request. +* If the handler cannot process the request, the server will loop through any global handlers and call that handler if it passes filter(), canHandle(), and needsAuthentication(). +* If no global handlers are called, the server.defaultEndpoint handler will be called. +* Each handler is responsible for processing the request and sending a response. +* When the response is sent, the client is closed and freed from the memory. + * Unless its a special handler like websockets or eventsource. + +![Flowchart of Request Lifecycle](/assets/request-flow.svg) + +### Handlers + +* ```PsychicHandler``` is used for processing and responding to specific HTTP requests. +* ```PsychicHandler``` instances can be attached to any endpoint or as global handlers. +* Setting a ```Filter``` to the ```PsychicHandler``` controls when to apply the handler, decision can be based on + request method, url, request host/port/target host, the request client's localIP or remoteIP. +* Two filter callbacks are provided: ```ON_AP_FILTER``` to execute the rewrite when request is made to the AP interface, + ```ON_STA_FILTER``` to execute the rewrite when request is made to the STA interface. +* The ```canHandle``` method is used for handler specific control on whether the requests can be handled. Decision can be based on request method, request url, request host/port/target host. +* Depending on how the handler is implemented, it may provide callbacks for adding your own custom processing code to the handler. +* Global ```Handlers``` are evaluated in the order they are attached to the server. The ```canHandle``` is called only + if the ```Filter``` that was set to the ```Handler``` return true. +* The first global ```Handler``` that can handle the request is selected, no further processing of handlers is called. + +![Flowchart of Request Lifecycle](/assets/handler-callbacks.svg) + +### Responses and how do they work + +* The ```PsychicResponse``` objects are used to send the response data back to the client. +* Typically the response should be fully generated and sent from the callback. +* It may be possible to generate the response outside the callback, but it will be difficult. + * The exceptions are websockets + eventsource where the response is sent, but the connection is maintained and new data can be sent/received outside the handler. + +# Porting From ESPAsyncWebserver + +If you have existing code using ESPAsyncWebserver, you will feel right at home with PsychicHttp. Even if internally it is much different, the external interface is very similar. Some things are mostly cosmetic, like different class names and callback definitions. A few things might require a bit more in-depth approach. If you're porting your code and run into issues that aren't covered here, please post and issue. + +## Globals Stuff + +* Change your #include to ```#include ``` +* Change your server instance: ```PsychicHttpServer server;``` +* Define websocket handler if you have one: ```PsychicWebSocketHandler websocketHandler;``` +* Define eventsource if you have one: ```PsychicEventSource eventSource;``` + +## setup() Stuff + +* no more server.begin(), call server.listen(80), before you add your handlers +* server has a configurable limit on .on() endpoints. change it with ```server.config.max_uri_handlers = 20;``` as needed. +* check your callback function definitions: + * AsyncWebServerRequest -> PsychicRequest + * no more onBody() event + * for small bodies (server.maxRequestBodySize, default 16k) it will be automatically loaded and accessed by request->body() + * for large bodies, use an upload handler and onUpload() + * websocket callbacks are much different (and simpler!) + * websocket / eventsource handlers get attached to url in server.on("/url", &handler) instead of passing url to handler constructor. + * eventsource callbacks are onOpen and onClose now. +* HTTP_ANY is not supported by ESP-IDF, so we can't use it either. +* NO server.onFileUpload(onUpload); (you could attach an UploadHandler to the default endpoint i guess?) +* NO server.onRequestBody(onBody); (same) + +## Requests / Responses + +* request->send is now request->reply() +* if you create a response, call response->send() directly, not request->send(reply) +* request->headers() is not supported by ESP-IDF, you have to just check for the header you need. +* No AsyncCallbackJsonWebHandler (for now... can add if needed) +* No request->beginResponse(). Instanciate a PsychicResponse instead: ```PsychicResponse response(request);``` +* No PROGMEM suppport (its not relevant to ESP32: https://esp32.com/viewtopic.php?t=20595) +* No Stream response support just yet + +# Usage + +## Create the Server + +Here is an example of the typical server setup: + +```cpp +#include +PsychicHttpServer server; + +void setup() +{ + //optional low level setup server config stuff here. + //server.config is an ESP-IDF httpd_config struct + //see: https://docs.espressif.com/projects/esp-idf/en/v4.4.6/esp32/api-reference/protocols/esp_http_server.html#_CPPv412httpd_config + //increase maximum number of uri endpoint handlers (.on() calls) + server.config.max_uri_handlers = 20; + + //connect to wifi + + //start the server listening on port 80 (standard HTTP port) + server.listen(80); + + //call server methods to attach endpoints and handlers + server.on(...); + server.serveStatic(...); + server.attachHandler(...); +} +``` + +## Add Handlers + +One major difference from ESPAsyncWebserver is that handlers can be attached to a specific url (endpoint) or as a global handler. The reason for this, is that attaching to a specific URL is more efficient and makes for cleaner code. + +### Endpoint Handlers + +An endpoint is basically just the URL path (eg. /path/to/file) without any query string. The ```server.on(...)``` function is a convenience function for creating endpoints and attaching a handler to them. There are two main styles: attaching a basic ```WebRequest``` handler and attaching an external handler. + +```cpp +//creates a basic PsychicWebHandler that calls the request_callback callback +server.on("/url", HTTP_GET, request_callback); + +//same as above, but defaults to HTTP_GET +server.on("/url", request_callback); + +//attaches a websocket handler to /ws +PsychicWebSocketHandler websocketHandler; +server.on("/ws", &websocketHandler); +``` + +The ```server.on(...)``` returns a pointer to the endpoint, which can be used to call various functions like ```setHandler()```, ```setFilter()```, and ```setAuthentication()```. + +```cpp +//respond to /url only from requests to the AP +server.on("/url", HTTP_GET, request_callback)->setFilter(ON_AP_FILTER); + +//require authentication on /url +server.on("/url", HTTP_GET, request_callback)->setAuthentication("user", "pass"); + +//attach websocket handler to /ws +PsychicWebSocketHandler websocketHandler; +server.on("/ws")->attachHandler(&websocketHandler); +``` + +### Basic Requests + +The ```PsychicWebHandler``` class is for handling standard web requests. It provides a single callback: ```onRequest()```. This callback is called when the handler receives a valid HTTP request. + +One major difference from ESPAsyncWebserver is that this callback needs to return an esp_err_t variable to let the server know the result of processing the request. The ```response->reply()``` and ```request->send()``` functions will return this. It is a good habit to return the result of these functions as sending the response will close the connection. + +The function definition for the onRequest callback is: + +```cpp +esp_err_t function_name(PsychicRequest *request); +``` + +Here is a simple example that sends back the client's IP on the URL /ip + +```cpp +server.on("/ip", [](PsychicRequest *request) +{ + String output = "Your IP is: " + request->client()->remoteIP().toString(); + return request->reply(output.c_str()); +}); +``` + +### Uploads + +The ```PsychicUploadHandler``` class is for handling uploads, both large POST bodies and multipart encoded forms. It provides two callbacks: ```onUpload()``` and ```onRequest()```. + +```onUpload(...)``` is called when there is new data. This function may be called multiple times so that you can process the data in chunks. The function definition for the onUpload callback is: + +```cpp +esp_err_t function_name(PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final); +``` + +* request is a pointer to the Request object +* filename is the name of the uploaded file +* index is the overall byte position of the current data +* data is a pointer to the data buffer +* len is the length of the data buffer +* final is a flag to tell if its the last chunk of data + +```onRequest(...)``` is called after the successful handling of the upload. Its definition and usage is the same as the basic request example as above. + +#### Basic Upload (file is the entire POST body) + +It's worth noting that there is no standard way of passing in a filename for this method, so the handler attempts to guess the filename with the following methods: + +* Checking the Content-Disposition header +* Checking the _filename query parameter (eg. /upload?filename=filename.txt becomes filename.txt) +* Checking the url and taking the last part as filename (eg. /upload/filename.txt becomes filename.txt). You must set a wildcard url for this to work as in the example below. + +```cpp +//handle a very basic upload as post body + PsychicUploadHandler *uploadHandler = new PsychicUploadHandler(); + uploadHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + Serial.printf("Writing %d/%d bytes to: %s\n", (int)index+(int)len, request->contentLength(), path.c_str()); + + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + uploadHandler->onRequest([](PsychicRequest *request) + { + String url = "/" + request->getFilename(); + String output = "" + url + ""; + + return request->reply(output.c_str()); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + server.on("/upload/*", HTTP_POST, uploadHandler); +``` + +#### Multipart Upload + +Very similar to the basic upload, with 2 key differences: + +* multipart requests don't know the total size of the file until after it has been fully processed. You can get a rough idea with request->contentLength(), but that is the length of the entire multipart encoded request. +* you can access form variables, including multipart file infor (name + size) in the onRequest handler using request->getParam() + +```cpp + //a little bit more complicated multipart form + PsychicUploadHandler *multipartHandler = new PsychicUploadHandler(); + multipartHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + //some progress over serial. + Serial.printf("Writing %d bytes to: %s\n", (int)len, path.c_str()); + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + multipartHandler->onRequest([](PsychicRequest *request) + { + PsychicWebParameter *file = request->getParam("file_upload"); + + String url = "/" + file->value(); + String output; + + output += "" + url + "
\n"; + output += "Bytes: " + String(file->size()) + "
\n"; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + }); + + //upload to /multipart url + server.on("/multipart", HTTP_POST, multipartHandler); +``` + +### Static File Serving + +The ```PsychicStaticFileHandler``` is a special handler that does not provide any callbacks. It is used to serve a file or files from a specific directory in a filesystem to a directory on the webserver. The syntax is exactly the same as ESPAsyncWebserver. Anything that is derived from the ```FS``` class should work (eg. SPIFFS, LittleFS, SD, etc) + +A couple important notes: + +* If it finds a file with an extra .gz extension, it will serve it as gzip encoded (eg: /targetfile.ext -> {targetfile.ext}.gz) +* If the file is larger than FILE_CHUNK_SIZE (default 8kb) then it will send it as a chunked response. +* It will detect most basic filetypes and automatically set the appropriate Content-Type + +The ```server.serveStatic()``` function handles creating the handler and assigning it to the server: + +```cpp +//serve static files from LittleFS/www on / only to clients on same wifi network +//this is where our /index.html file lives +server.serveStatic("/", LittleFS, "/www/")->setFilter(ON_STA_FILTER); + +//serve static files from LittleFS/www-ap on / only to clients on SoftAP +//this is where our /index.html file lives +server.serveStatic("/", LittleFS, "/www-ap/")->setFilter(ON_AP_FILTER); + +//serve static files from LittleFS/img on /img +//it's more efficient to serve everything from a single www directory, but this is also possible. +server.serveStatic("/img", LittleFS, "/img/"); + +//you can also serve single files +server.serveStatic("/myfile.txt", LittleFS, "/custom.txt"); +``` + +You could also theoretically use the file response directly: + +```cpp +server.on("/ip", [](PsychicRequest *request) +{ + String filename = "/path/to/file"; + PsychicFileResponse response(request, LittleFS, filename); + + return response.send(); +}); +PsychicFileResponse(PsychicRequest *request, FS &fs, const String& path) +``` + +### Websockets + +The ```PsychicWebSocketHandler``` class is for handling WebSocket connections. It provides 3 callbacks: + +```onOpen(...)``` is called when a new WebSocket client connects. +```onFrame(...)``` is called when a new WebSocket frame has arrived. +```onClose(...)``` is called when a new WebSocket client disconnects. + +Here are the callback definitions: + +```cpp +void open_function(PsychicWebSocketClient *client); +esp_err_t frame_function(PsychicWebSocketRequest *request, httpd_ws_frame *frame); +void close_function(PsychicWebSocketClient *client); +``` + +WebSockets were the main reason for starting PsychicHttp, so they are well tested. They are also much simplified from the ESPAsyncWebserver style. You do not need to worry about error handling, partial frame assembly, PONG messages, etc. The onFrame() function is called when a complete frame has been received, and can handle frames up to the entire available heap size. + +Here is a basic example of using WebSockets: + +```cpp + //create our handler... note this should be located as a global or somewhere it wont go out of scope and be destroyed. + PsychicWebSocketHandler websocketHandler(); + + websocketHandler.onOpen([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + client->sendMessage("Hello!"); + }); + + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { + Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char *)frame->payload); + return request->reply(frame); + }); + + websocketHandler.onClose([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + + //attach the handler to /ws. You can then connect to ws://ip.address/ws + server.on("/ws", &websocketHandler); +``` + +The onFrame() callback has 2 parameters: + +* ```PsychicWebSocketRequest *request``` a special request with helper functions for replying in websocket format. +* ```httpd_ws_frame *frame``` ESP-IDF websocket struct. The important struct members we care about are: + * ```uint8_t *payload; /*!< Pre-allocated data buffer */``` + * ```size_t len; /*!< Length of the WebSocket data */``` + +For sending data on the websocket connection, there are 3 methods: + +* ```request->reply()``` - only available in the onFrame() callback context. +* ```webSocketHandler.sendAll()``` - can be used anywhere to send websocket messages to all connected clients. +* ```client->send()``` - can be used anywhere* to send a websocket message to a specific client + +All of the above functions either accept simple ```char *``` string of you can construct your own httpd_ws_frame. + +*Special Note:* Do not hold on to the ```PsychicWebSocketClient``` for sending messages to clients outside the callbacks. That pointer is destroyed when a client disconnects. Instead, store the ```int client->socket()```. Then when you want to send a message, use this code: + +```cpp +//make sure our client is still connected. +PsychicWebSocketClient *client = websocketHandler.getClient(socket); +if (client != NULL) + client->send("Your Message") +``` + +### EventSource / SSE + +The ```PsychicEventSource``` class is for handling EventSource / SSE connections. It provides 2 callbacks: + +```onOpen(...)``` is called when a new EventSource client connects. +```onClose(...)``` is called when a new EventSource client disconnects. + +Here are the callback definitions: + +```cpp +void open_function(PsychicEventSourceClient *client); +void close_function(PsychicEventSourceClient *client); +``` + +Here is a basic example of using PsychicEventSource: + +```cpp + //create our handler... note this should be located as a global or somewhere it wont go out of scope and be destroyed. + PsychicEventSource eventSource; + + eventSource.onOpen([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + client->send("Hello user!", NULL, millis(), 1000); + }); + + eventSource.onClose([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + + //attach the handler to /events + server.on("/events", &eventSource); +``` + +For sending data on the EventSource connection, there are 2 methods: + +* ```eventSource.send()``` - can be used anywhere to send events to all connected clients. +* ```client->send()``` - can be used anywhere* to send events to a specific client + +All of the above functions accept a simple ```char *``` message, and optionally: ```char *``` event name, id, and reconnect time. + +*Special Note:* Do not hold on to the ```PsychicEventSourceClient``` for sending messages to clients outside the callbacks. That pointer is destroyed when a client disconnects. Instead, store the ```int client->socket()```. Then when you want to send a message, use this code: + +```cpp +//make sure our client is still connected. +PsychicEventSourceClient *client = eventSource.getClient(socket); +if (client != NULL) + client->send("Your Event") +``` + +### HTTPS / SSL + +PsychicHttp supports HTTPS / SSL out of the box, however there are some limitations (see performance below). Enabling it also increases the code size by about 100kb. To use HTTPS, you need to modify your setup like so: + +```cpp +#include +#include +PsychicHttpsServer server; +server.listen(443, server_cert, server_key); +``` + +```server_cert``` and ```server_key``` are both ```const char *``` parameters which contain the server certificate and private key, respectively. + +To generate your own key and self signed certificate, you can use the command below: + +``` +openssl req -x509 -newkey rsa:4096 -nodes -keyout server.key -out server.crt -sha256 -days 365 +``` + +Including the ```PsychicHttpsServer.h``` also defines ```PSY_ENABLE_SSL``` which you can use in your code to allow enabling / disabling calls in your code based on if the HTTPS server is available: + +```cpp +//our main server object +#ifdef PSY_ENABLE_SSL + PsychicHttpsServer server; +#else + PsychicHttpServer server; +#endif +``` + +Last, but not least, you can create a separate HTTP server on port 80 that redirects all requests to the HTTPS server: + +```cpp +//this creates a 2nd server listening on port 80 and redirects all requests HTTPS +PsychicHttpServer *redirectServer = new PsychicHttpServer(); +redirectServer->config.ctrl_port = 20420; // just a random port different from the default one +redirectServer->listen(80); +redirectServer->onNotFound([](PsychicRequest *request) { + String url = "https://" + request->host() + request->url(); + return request->redirect(url.c_str()); +}); +``` + +# TemplatePrinter + +**This is not specific to PsychicHttp, and it works with any `Print` object. You could for example, template data out to `File`, `Serial`, etc...**. + +The template engine is a `Print` interface and can be printed to directly, however, if you are just templating a few short strings, I'd probably just use `response.printf()` instead. **Its benefit will be seen when templating large inputs such as files.** + +One benefit may be **templating a **JSON** file avoiding the need to use ArduinoJson.** + +Before closing the underlying `Print`/`Stream` that this writes to, it must be flushed as small amounts of data can be buffered. A convenience method to take care of this is shows in `example 3`. + +The header file is not currently added to `PsychicHttp.h` and users will have to add it manually: + +```C++ +#include +``` + +## Template parameter definition: + +- Must start and end with a preset delimiter, the default is `%` +- Can only contain `a-z`, `A-Z`, `0-9`, and `_` +- Maximum length of 63 characters (buffer is 64 including `null`). +- A parameter must not be zero length (not including delimiters). +- Spaces or any other character do not match as a parameter, and will be output as is. +- Valid examples + - `%MY_PARAM%` + - `%SOME1%` +- **Invalid** examples + - `%MY PARAM%` + - `%SOME1 %` + - `%UNFINISHED` + - `%%` + +## Template processing +A function or lambda is used to receive the parameter replacement. + +```C++ +bool templateHandler(Print &output, const char *param){ + //... +} + +[](Print &output, const char *param){ + //... +} +``` + +Parameters: +- `Print &output` - the underlying `Print`, print the results of templating to this. +- `const char *param` - a string containing the current parameter. + +The handler must return a `bool`. +- `true`: the parameter was handled, continue as normal. +- `false`: the input detected as a parameter is not, print literal. + +See output in **example 1** regarding the effects of returning `true` or `false`. + +## Template input handler +This is not needed unless using the static convenience function `TemplatePrinter::start()`. See **example 3**. + +```C++ +bool inputHandler(TemplatePrinter &printer){ + //... +} + +[](TemplatePrinter &printer){ + //... +} +``` + +Parameters: +- `TemplatePrinter &printer` - The template engine, print your template text to this for processing. + + +## Example 1 - Simple use with `PsychicStreamResponse`: +This example highlights its most basic usage. + +```C++ + +// Function to handle parameter requests. + +bool templateHandler(Print &output, const char *param){ + + if(strcmp(param, "FREE_HEAP") == 0){ + output.print((double)ESP.getFreeHeap() / 1024.0, 2); + + }else if(strcmp(param, "MIN_FREE_HEAP") == 0){ + output.print((double)ESP.getMinFreeHeap() / 1024.0, 2); + + }else if(strcmp(param, "MAX_ALLOC_HEAP") == 0){ + output.print((double)ESP.getMaxAllocHeap() / 1024.0, 2); + + }else if(strcmp(param, "HEAP_SIZE") == 0){ + output.print((double)ESP.getHeapSize() / 1024.0, 2); + }else{ + return false; + } + output.print("Kb"); + return true; +} + +// Example serving a request +server.on("/template", [](PsychicRequest *request) { + PsychicStreamResponse response(request, "text/plain"); + + response.beginSend(); + + TemplatePrinter printer(response, templateHandler); + + printer.println("My ESP has %FREE_HEAP% left. Its lifetime minimum heap is %MIN_FREE_HEAP%."); + printer.println("The maximum allocation size is %MAX_ALLOC_HEAP%, and its total size is %HEAP_SIZE%."); + printer.println("This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%."); + printer.println("This line finished with %UNFIN"); + printer.flush(); + + return response.endSend(); +}); +``` + +The output for example looks like: +``` +My ESP has 170.92Kb left. Its lifetime minimum heap is 169.83Kb. +The maximum allocation size is 107.99Kb, and its total size is 284.19Kb. +This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%. +This line finished with %UNFIN +``` + +## Example 2 - Templating a file + +```C++ +server.on("/home", [](PsychicRequest *request) { + PsychicStreamResponse response(request, "text/html"); + File file = SD.open("/www/index.html"); + + response.beginSend(); + + TemplatePrinter printer(response, templateHandler); + + printer.copyFrom(file); + printer.flush(); + file.close(); + + return response.endSend(); +}); +``` + +## Example 3 - Using the `TemplatePrinter::start` method. +This static method allows an RAII approach, allowing you to template a stream, etc... without needing a `flush()`. The function call is laid out as: + +```C++ +TemplatePrinter::start(host_stream, template_handler, input_handler); +``` + +\*these examples use the `templateHandler` function defined in example 1. + +### Serve a file like example 2 +```C++ +server.on("/home", [](PsychicRequest *request) { + PsychicStreamResponse response(request, "text/html"); + File file = SD.open("/www/index.html"); + + response.beginSend(); + TemplatePrinter::start(response, templateHandler, [&file](TemplatePrinter &printer){ + printer.copyFrom(file); + }); + file.close(); + + return response.endSend(); +}); +``` + +### Template a string like example 1 +```C++ +server.on("/template2", [](PsychicRequest *request) { + + PsychicStreamResponse response(request, "text/plain"); + + response.beginSend(); + + TemplatePrinter::start(response, templateHandler, [](TemplatePrinter &printer){ + printer.println("My ESP has %FREE_HEAP% left. Its lifetime minimum heap is %MIN_FREE_HEAP%."); + printer.println("The maximum allocation size is %MAX_ALLOC_HEAP%, and its total size is %HEAP_SIZE%."); + printer.println("This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%."); + }); + + return response.endSend(); +}); +``` + +# Performance + +In order to really see the differences between libraries, I created some basic benchmark firmwares for PsychicHttp, ESPAsyncWebserver, and ArduinoMongoose. I then ran the loadtest-http.sh and loadtest-websocket.sh scripts against each firmware to get some real numbers on the performance of each server library. All of the code and results are available in the /benchmark folder. If you want to see the collated data and graphs, there is a [LibreOffice spreadsheet](/benchmark/comparison.ods). + +![Performance graph](/benchmark/performance.png) +![Latency graph](/benchmark/latency.png) + +## HTTPS / SSL + +Yes, PsychicHttp supports SSL out of the box, but there are a few caveats: + +* Due to memory limitations, it can only handle 2 connections at a time. Each SSL connection takes about 45k ram, and a blank PsychicHttp sketch has about 150k ram free. +* Speed and latency are still pretty good (see graph above) but the SSH handshake seems to take 1500ms. With websockets or browser its not an issue since the connection is kept alive, but if you are loading requests in another way it will be a bit slow +* Unless you want to expose your ESP to the internet, you are limited to self signed keys and the annoying browser security warnings that come with them. + +## Analysis + +The results clearly show some of the reasons for writing PsychicHttp: ESPAsyncWebserver crashes under heavy load on each test, across the board in a 60s test. That means in normal usage, you're just rolling the dice with how long it will go until it crashes. Every other number is moot, IMHO. + +ArduinoMongoose doesn't crash under heavy load, but it does bog down with extremely high latency (15s) for web requests and appears to not even respond at the highest loadings as the loadtest script crashes instead. The code itself doesnt crash, so bonus points there. After the high load, it does go back to serving normally. One area ArduinoMongoose does shine, is in websockets where its performance is almost 2x the performance of PsychicHttp. Both in requests per second and latency. Clearly an area of improvement for PsychicHttp. + +PsychicHttp has good performance across the board. No crashes and continously responds during each test. It is a clear winner in requests per second when serving files from memory, dynamic JSON, and has consistent performance when serving files from LittleFS. The only real downside is the lower performance of the websockets with a single connection handling 38rps, and maxing out at 120rps across multiple connections. + +## Takeaways + +With all due respect to @me-no-dev who has done some amazing work in the open source community, I cannot recommend anyone use the ESPAsyncWebserver for anything other than simple projects that don't need to be reliable. Even then, PsychicHttp has taken the arcane api of the ESP-IDF web server library and made it nice and friendly to use with a very similar API to ESPAsyncWebserver. Also, ESPAsyncWebserver is more or less abandoned, with 150 open issues, 77 pending pull requests, and the last commit in over 2 years. + +ArduinoMongoose is a good alternative, although the latency issues when it gets fully loaded can be very annoying. I believe it is also cross platform to other microcontrollers as well, but I haven't tested that. The other issue here is that it is based on an old version of a modified Mongoose library that will be difficult to update as it is a major revision behind and several security updates behind as well. Big thanks to @jeremypoulter though as PsychicHttp is a fork of ArduinoMongoose so it's built on strong bones. + +# Roadmap + +## v1.2: ESPAsyncWebserver Parity + + +Change: +Modify the request handling to bring initail url matching and filtering into PsychicHttpServer itself. + +Benefits: +* Fix a bug with filter() where endpoint is matched, but filter fails and it doesn't continue matching further endpoints (checks are in different codebases) +* HTTP_ANY support +* unlimited endpoints + * we would use a List to store endpoints + * dont have to pre-declare config.max_uri_handlers; +* much more flexibility for future + +Issues +* it would log a warning on every request as if its a 404. (httpd_uri.c:298) +* req->user_ctx is not passed in. (httpd_uri.c:309) + * but... user_ctx is something we could store in the psychicendpoint data + * Websocket support assumes an endpoint with matching url / method (httpd_uri.c:312) + * we could copy and bring this code into our own internal request processor + * would need to manually maintain more code (~100 lines?) and be more prone to esp-idf http_server updates causing problems. + +How to implement +* set config.max_uri_handlers = 1; +* possibly do not register any uri_handlers (looks like it would be fastest way to exit httpd_find_uri_handler (httpd_uri.c:94)) + * looks like 404 is set by default, so should work. +* modify PsychicEndpoint to store the stuff we would pass to http_server +* create a new function handleRequest() before PsychicHttpServer::defaultNotFoundHandler to process incoming requests. + * bring in code from PsychicHttpServer::notFoundHandler + * add new code to loop over endpoints to call match and filter +* bring code from esp-idf library + +* templating system +* regex url matching +* rewrite urls? +* What else are we missing? + + +## Longterm Wants + +* investigate websocket performance gap +* support for esp-idf framework +* support for arduino 3.0 framework +* Enable worker based multithreading with esp-idf v5.x +* 100-continue support? + +If anyone wants to take a crack at implementing any of the above features I am more than happy to accept pull requests. diff --git a/lib/PsychicHttp/RELEASE.md b/lib/PsychicHttp/RELEASE.md new file mode 100644 index 0000000..98db528 --- /dev/null +++ b/lib/PsychicHttp/RELEASE.md @@ -0,0 +1,6 @@ +* Update CHANGELOG +* Bump version in library.json +* Bump version in library.properties +* Make new release + tag + * this will get pulled in automatically by Arduino Library Indexer +* run ```pio pkg publish``` to publish to Platform.io \ No newline at end of file diff --git a/lib/PsychicHttp/assets/handler-callbacks.svg b/lib/PsychicHttp/assets/handler-callbacks.svg new file mode 100644 index 0000000..62fcbdf --- /dev/null +++ b/lib/PsychicHttp/assets/handler-callbacks.svg @@ -0,0 +1,4 @@ + + + +
WebHandler
WebHandler
Handlers with Callbacks
Handlers with Callbacks
onRequest()
onRequest()
WebSocketHandler
WebSocketHandler
onOpen()
onOpen()
onFrame()
onFrame()
onClose()
onClose()
UploadHandler
UploadHandler
onRequest()
onRequest()
onUpload()
onUpload()
EventSource
EventSource
onOpen()
onOpen()
onClose()
onClose()
Text is not SVG - cannot display
\ No newline at end of file diff --git a/lib/PsychicHttp/assets/request-flow.svg b/lib/PsychicHttp/assets/request-flow.svg new file mode 100644 index 0000000..999fb00 --- /dev/null +++ b/lib/PsychicHttp/assets/request-flow.svg @@ -0,0 +1,4 @@ + + + +
HTTP Request
HTTP Request
Yes
Yes
No
No
Endpoint Matched?
Endpoint Matche...
PsychicHandler
PsychicHandler
Yes
Yes
Matching
 Handler?
Matching...
Default Endpoint
Default Endpoint
No
No
Yes
Yes
New Connection?
New Connection?
server.onOpen Callback
server.onOpen Callba...
Connection Closed?
Connection Closed?
handler.onClose
server.onClose
Callbacks
handler.onClose...
Finish
Finish
handler.onOpen + specific callbacks
handler.onOpen + spe...
filter() ?
filter() ?
canHandle() ?
canHandle() ?
authenticate() ?
authenticate() ?
requestAuthentication()
requestAuthentication()
handleRequest()
handleRequest()
response.send()
response.send()
PsychicHttp Request Flow
PsychicHttp Request Flow
Text is not SVG - cannot display
\ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/arduinomongoose/.gitignore b/lib/PsychicHttp/benchmark/arduinomongoose/.gitignore new file mode 100644 index 0000000..9e5f911 --- /dev/null +++ b/lib/PsychicHttp/benchmark/arduinomongoose/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/lib/PsychicHttp/benchmark/arduinomongoose/data/www/alien.png b/lib/PsychicHttp/benchmark/arduinomongoose/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/benchmark/arduinomongoose/data/www/alien.png differ diff --git a/lib/PsychicHttp/benchmark/arduinomongoose/include/README b/lib/PsychicHttp/benchmark/arduinomongoose/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/benchmark/arduinomongoose/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/benchmark/arduinomongoose/lib/README b/lib/PsychicHttp/benchmark/arduinomongoose/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/benchmark/arduinomongoose/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/espMqttClient/examples/simple-linux/platformio.ini b/lib/PsychicHttp/benchmark/arduinomongoose/platformio.ini similarity index 56% rename from lib/espMqttClient/examples/simple-linux/platformio.ini rename to lib/PsychicHttp/benchmark/arduinomongoose/platformio.ini index 565336f..b5604fb 100644 --- a/lib/espMqttClient/examples/simple-linux/platformio.ini +++ b/lib/PsychicHttp/benchmark/arduinomongoose/platformio.ini @@ -8,22 +8,15 @@ ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html -;[platformio] -;default_envs = esp8266 +[env] +platform = espressif32 +framework = arduino +board = esp32dev +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder +lib_deps = + jeremypoulter/ArduinoMongoose + bblanchon/ArduinoJson +board_build.filesystem = littlefs -[common] -build_flags = - -D DEBUG_ESP_MQTT_CLIENT=1 - -std=c++11 - -pthread - -Wall - -Wextra - -Werror - -[env:native] -platform = native -build_flags = - ${common.build_flags} - -D EMC_RX_BUFFER_SIZE=1500 -build_type = debug -lib_compat_mode = off +[env:default] \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/arduinomongoose/src/main.cpp b/lib/PsychicHttp/benchmark/arduinomongoose/src/main.cpp new file mode 100644 index 0000000..f7e0a9d --- /dev/null +++ b/lib/PsychicHttp/benchmark/arduinomongoose/src/main.cpp @@ -0,0 +1,234 @@ +/* Wi-Fi STA Connect and Disconnect Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. + +*/ +#include +#include +#include +#include +#include +#include + +const char *ssid = ""; +const char *password = ""; + +MongooseHttpServer server; + +const char *htmlContent = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +bool connectToWifi() +{ + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.setSleep(false); + WiFi.useStaticBuffers(true); + + WiFi.begin(ssid, password); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + Serial.println("ArduinoMongoose Benchmark"); + + // We start by connecting to a WiFi network + // To debug, please enable Core Debug Level to Verbose + if (connectToWifi()) + { + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + //start our server + Mongoose.begin(); + server.begin(80); + + //index file + server.on("/", HTTP_GET, [](MongooseHttpServerRequest *request) + { + request->send(200, "text/html", htmlContent); + }); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/api", HTTP_GET, [](MongooseHttpServerRequest *request) + { + //create a response object + StaticJsonDocument<128> output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + String foo = request->getParam("foo"); + output["foo"] = foo; + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + request->send(200, "application/json", jsonBuffer.c_str()); + }); + + //websocket + server.on("/ws$")-> + onFrame([](MongooseHttpWebSocketConnection *connection, int flags, uint8_t *data, size_t len) { + connection->send(WEBSOCKET_OP_TEXT, data, len); + //server.sendAll(connection, (char *)data); + }); + + //hack - no servestatic + server.on("/alien.png", HTTP_GET, [](MongooseHttpServerRequest *request) + { + //open our file + File fp = LittleFS.open("/www/alien.png"); + size_t length = fp.size(); + + //read our data + uint8_t * data = (uint8_t *)malloc(length); + if (data != NULL) + { + fp.readBytes((char *)data, length); + + //send it off + MongooseHttpServerResponseBasic *response = request->beginResponse(); + response->setContent(data, length); + response->setContentType("image/png"); + response->setCode(200); + request->send(response); + + //free the memory + free(data); + } + else + request->send(503); + }); + } +} + +void loop() +{ + Mongoose.poll(1000); +} \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/arduinomongoose/test/README b/lib/PsychicHttp/benchmark/arduinomongoose/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/lib/PsychicHttp/benchmark/arduinomongoose/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html diff --git a/lib/PsychicHttp/benchmark/comparison.ods b/lib/PsychicHttp/benchmark/comparison.ods new file mode 100644 index 0000000..47e6587 Binary files /dev/null and b/lib/PsychicHttp/benchmark/comparison.ods differ diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/.gitignore b/lib/PsychicHttp/benchmark/espasyncwebserver/.gitignore new file mode 100644 index 0000000..9e5f911 --- /dev/null +++ b/lib/PsychicHttp/benchmark/espasyncwebserver/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/data/www/alien.png b/lib/PsychicHttp/benchmark/espasyncwebserver/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/benchmark/espasyncwebserver/data/www/alien.png differ diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/include/README b/lib/PsychicHttp/benchmark/espasyncwebserver/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/benchmark/espasyncwebserver/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/lib/README b/lib/PsychicHttp/benchmark/espasyncwebserver/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/benchmark/espasyncwebserver/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/platformio.ini b/lib/PsychicHttp/benchmark/espasyncwebserver/platformio.ini new file mode 100644 index 0000000..0f883e3 --- /dev/null +++ b/lib/PsychicHttp/benchmark/espasyncwebserver/platformio.ini @@ -0,0 +1,22 @@ +; 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 + +[env] +platform = espressif32 +framework = arduino +board = esp32dev +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder +lib_deps = + https://github.com/me-no-dev/ESPAsyncWebServer + bblanchon/ArduinoJson +board_build.filesystem = littlefs + +[env:default] \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/src/main.cpp b/lib/PsychicHttp/benchmark/espasyncwebserver/src/main.cpp new file mode 100644 index 0000000..c76c1cd --- /dev/null +++ b/lib/PsychicHttp/benchmark/espasyncwebserver/src/main.cpp @@ -0,0 +1,276 @@ +/* Wi-Fi STA Connect and Disconnect Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. + +*/ +#include +#include +#include +#include +#include + +const char *ssid = ""; +const char *password = ""; + +AsyncWebServer server(80); +AsyncWebSocket ws("/ws"); + +const char *htmlContent = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +bool connectToWifi() +{ + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.setSleep(false); + WiFi.useStaticBuffers(true); + + WiFi.begin(ssid, password); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void onEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ + if(type == WS_EVT_CONNECT){ + //client connected + // Serial.printf("ws[%s][%u] connect\n", server->url(), client->id()); + // client->printf("Hello Client %u :)", client->id()); + // client->ping(); + } else if(type == WS_EVT_DISCONNECT){ + //client disconnected + // Serial.printf("ws[%s][%u] disconnect: %u\n", server->url(), client->id()); + } else if(type == WS_EVT_ERROR){ + //error was received from the other end + // Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data); + } else if(type == WS_EVT_PONG){ + //pong message was received (in response to a ping request maybe) + // Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len)?(char*)data:""); + } else if(type == WS_EVT_DATA){ + //data packet + AwsFrameInfo * info = (AwsFrameInfo*)arg; + if(info->final && info->index == 0 && info->len == len){ + //the whole message is in a single frame and we got all of it's data + // Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT)?"text":"binary", info->len); + if(info->opcode == WS_TEXT){ + data[len] = 0; + // Serial.printf("%s\n", (char*)data); + } else { + // for(size_t i=0; i < info->len; i++){ + // Serial.printf("%02x ", data[i]); + // } + // Serial.printf("\n"); + } + if(info->opcode == WS_TEXT) + { + client->text((char *)data, len); + } + // else + // client->binary("I got your binary message"); + } else { + //message is comprised of multiple frames or the frame is split into multiple packets + if(info->index == 0){ + // if(info->num == 0) + // Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary"); + // Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len); + } + + Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT)?"text":"binary", info->index, info->index + len); + if(info->message_opcode == WS_TEXT){ + data[len] = 0; + // Serial.printf("%s\n", (char*)data); + } else { + // for(size_t i=0; i < len; i++){ + // Serial.printf("%02x ", data[i]); + // } + // Serial.printf("\n"); + } + + if((info->index + len) == info->len){ + // Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len); + if(info->final){ + // Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary"); + if(info->message_opcode == WS_TEXT) + { + client->text((char *)data, info->len); + } + // else + // client->binary("I got your binary message"); + } + } + } + } +} + +void setup() +{ + Serial.begin(115200); + delay(10); + Serial.println("ESPAsyncWebserver Benchmark"); + + // We start by connecting to a WiFi network + // To debug, please enable Core Debug Level to Verbose + if (connectToWifi()) + { + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) + { + request->send(200, "text/html", htmlContent); + }); + + //serve static files from LittleFS/www on / + server.serveStatic("/", LittleFS, "/www/"); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/api", HTTP_GET, [](AsyncWebServerRequest *request) + { + //create a response object + StaticJsonDocument<128> output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + AsyncWebParameter* foo = request->getParam("foo"); + output["foo"] = foo->value(); + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + request->send(200, "application/json", jsonBuffer.c_str()); + }); + + ws.onEvent(onEvent); + server.addHandler(&ws); + + server.begin(); + } +} + +void loop() +{ + ws.cleanupClients(); + delay(1000); +} \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/espasyncwebserver/test/README b/lib/PsychicHttp/benchmark/espasyncwebserver/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/lib/PsychicHttp/benchmark/espasyncwebserver/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html diff --git a/lib/PsychicHttp/benchmark/eventsource-client-test.js b/lib/PsychicHttp/benchmark/eventsource-client-test.js new file mode 100644 index 0000000..8253789 --- /dev/null +++ b/lib/PsychicHttp/benchmark/eventsource-client-test.js @@ -0,0 +1,39 @@ +#!/usr/bin/env node + +const EventSource = require('eventsource'); +const url = 'http://192.168.2.131/events'; + +async function eventSourceClient() { + console.log(`Starting test`); + for (let i = 0; i < 1000000; i++) + { + if (i % 100 == 0) + console.log(`Count: ${i}`); + + let eventSource = new EventSource(url); + + eventSource.onopen = () => { + //console.log('EventSource connection opened.'); + }; + + eventSource.onerror = (error) => { + console.error('EventSource error:', error); + + // Close the connection on error + eventSource.close(); + }; + + await new Promise((resolve) => { + eventSource.onmessage = (event) => { + //console.log('Received message:', event.data); + + // Close the connection after receiving the first message + eventSource.close(); + + resolve(); + } + }); + } +} + +eventSourceClient(); \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/http-client-test.js b/lib/PsychicHttp/benchmark/http-client-test.js new file mode 100644 index 0000000..29588b9 --- /dev/null +++ b/lib/PsychicHttp/benchmark/http-client-test.js @@ -0,0 +1,43 @@ +#!/usr/bin/env node + +const axios = require('axios'); + +const url = 'http://192.168.2.131/api'; +const queryParams = { + foo: 'bar', + foo1: 'bar', + foo2: 'bar', + foo3: 'bar', + foo4: 'bar', + foo5: 'bar', + foo6: 'bar', +}; + +const totalRequests = 1000000; +const requestsPerCount = 100; + +let requestCount = 0; + +function fetchData() { + axios.get(url, { params: queryParams }) + .then(response => { + requestCount++; + + if (requestCount % requestsPerCount === 0) { + console.log(`Requests completed: ${requestCount}`); + } + + if (requestCount < totalRequests) { + fetchData(); + } else { + console.log('All requests completed.'); + } + }) + .catch(error => { + console.error('Error making request:', error.message); + }); +} + +// Start making requests +console.log(`Starting test`); +fetchData(); \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/latency.png b/lib/PsychicHttp/benchmark/latency.png new file mode 100644 index 0000000..1cedc93 Binary files /dev/null and b/lib/PsychicHttp/benchmark/latency.png differ diff --git a/lib/PsychicHttp/benchmark/loadtest-http.sh b/lib/PsychicHttp/benchmark/loadtest-http.sh new file mode 100644 index 0000000..4e75b84 --- /dev/null +++ b/lib/PsychicHttp/benchmark/loadtest-http.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +#Command to install the testers: +# npm install -g autocannon + +TEST_IP="192.168.2.131" +TEST_TIME=60 +LOG_FILE=psychic-http-loadtest.log +TIMEOUT=10000 +PROTOCOL=http +#PROTOCOL=https + +if test -f "$LOG_FILE"; then + rm $LOG_FILE +fi + +for CONCURRENCY in 1 2 3 4 5 6 7 8 9 10 15 20 +#for CONCURRENCY in 20 +do + printf "\n\nCLIENTS: *** $CONCURRENCY ***\n\n" >> $LOG_FILE + echo "Testing $CONCURRENCY clients on $PROTOCOL://$TEST_IP/" + #loadtest -c $CONCURRENCY --cores 1 -t $TEST_TIME --timeout $TIMEOUT "$PROTOCOL://$TEST_IP/" --quiet >> $LOG_FILE + autocannon -c $CONCURRENCY -w 1 -d $TEST_TIME --renderStatusCodes "$PROTOCOL://$TEST_IP/" >> $LOG_FILE 2>&1 + printf "\n\n----------------\n\n" >> $LOG_FILE + sleep 1 + + echo "Testing $CONCURRENCY clients on $PROTOCOL://$TEST_IP/api" + #loadtest -c $CONCURRENCY --cores 1 -t $TEST_TIME --timeout $TIMEOUT "$PROTOCOL://$TEST_IP/api?foo=bar" --quiet >> $LOG_FILE + autocannon -c $CONCURRENCY -w 1 -d $TEST_TIME --renderStatusCodes "$PROTOCOL://$TEST_IP/api?foo=bar" >> $LOG_FILE 2>&1 + printf "\n\n----------------\n\n" >> $LOG_FILE + sleep 1 + + echo "Testing $CONCURRENCY clients on $PROTOCOL://$TEST_IP/alien.png" + #loadtest -c $CONCURRENCY --cores 1 -t $TEST_TIME --timeout $TIMEOUT "$PROTOCOL://$TEST_IP/alien.png" --quiet >> $LOG_FILE + autocannon -c $CONCURRENCY -w 1 -d $TEST_TIME --renderStatusCodes "$PROTOCOL://$TEST_IP/alien.png" >> $LOG_FILE 2>&1 + printf "\n\n----------------\n\n" >> $LOG_FILE + sleep 1 +done \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/loadtest-websocket.sh b/lib/PsychicHttp/benchmark/loadtest-websocket.sh new file mode 100644 index 0000000..a9b5a41 --- /dev/null +++ b/lib/PsychicHttp/benchmark/loadtest-websocket.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +#Command to install the testers: +# npm install -g loadtest + +TEST_IP="192.168.2.131" +TEST_TIME=60 +LOG_FILE=psychic-websocket-loadtest.log +PROTOCOL=ws +#PROTOCOL=wss + +if test -f "$LOG_FILE"; then + rm $LOG_FILE +fi + +for CONCURRENCY in 1 2 3 4 5 6 7 +do + printf "\n\nCLIENTS: *** $CONCURRENCY ***\n\n" >> $LOG_FILE + echo "Testing $CONCURRENCY clients on $PROTOCOL://$TEST_IP/ws" + loadtest -c $CONCURRENCY --cores 1 -t $TEST_TIME --insecure $PROTOCOL://$TEST_IP/ws --quiet 2> /dev/null >> $LOG_FILE + sleep 1 +done + +for CONNECTIONS in 8 10 16 20 +#for CONNECTIONS in 20 +do + CONCURRENCY=$((CONNECTIONS / 2)) + printf "\n\nCLIENTS: *** $CONNECTIONS ***\n\n" >> $LOG_FILE + echo "Testing $CONNECTIONS clients on $PROTOCOL://$TEST_IP/ws" + loadtest -c $CONCURRENCY --cores 2 -t $TEST_TIME --insecure $PROTOCOL://$TEST_IP/ws --quiet 2> /dev/null >> $LOG_FILE + sleep 1 +done \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/package.json b/lib/PsychicHttp/benchmark/package.json new file mode 100644 index 0000000..3237d56 --- /dev/null +++ b/lib/PsychicHttp/benchmark/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "axios": "^1.6.2", + "eventsource": "^2.0.2", + "ws": "^8.14.2" + } +} diff --git a/lib/PsychicHttp/benchmark/performance.png b/lib/PsychicHttp/benchmark/performance.png new file mode 100644 index 0000000..81d2a3f Binary files /dev/null and b/lib/PsychicHttp/benchmark/performance.png differ diff --git a/lib/PsychicHttp/benchmark/psychichttp/.gitignore b/lib/PsychicHttp/benchmark/psychichttp/.gitignore new file mode 100644 index 0000000..9e5f911 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/lib/PsychicHttp/benchmark/psychichttp/data/www/alien.png b/lib/PsychicHttp/benchmark/psychichttp/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/benchmark/psychichttp/data/www/alien.png differ diff --git a/lib/PsychicHttp/benchmark/psychichttp/include/README b/lib/PsychicHttp/benchmark/psychichttp/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/benchmark/psychichttp/lib/README b/lib/PsychicHttp/benchmark/psychichttp/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/benchmark/psychichttp/platformio.ini b/lib/PsychicHttp/benchmark/psychichttp/platformio.ini new file mode 100644 index 0000000..868f0ca --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/platformio.ini @@ -0,0 +1,22 @@ +; 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 + +[env] +platform = espressif32 +framework = arduino +board = esp32dev +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder +lib_deps = + https://github.com/hoeken/PsychicHttp + bblanchon/ArduinoJson +board_build.filesystem = littlefs + +[env:default] diff --git a/lib/PsychicHttp/benchmark/psychichttp/src/main.cpp b/lib/PsychicHttp/benchmark/psychichttp/src/main.cpp new file mode 100644 index 0000000..c42d644 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/src/main.cpp @@ -0,0 +1,228 @@ +/* Wi-Fi STA Connect and Disconnect Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. + +*/ +#include +#include +#include +#include +#include +#include "_secret.h" + +#ifndef WIFI_SSID + #error "You need to enter your wifi credentials. Copy secret.h to _secret.h and enter your credentials there." +#endif + +//Enter your WIFI credentials in secret.h +const char *ssid = WIFI_SSID; +const char *password = WIFI_PASS; + +PsychicHttpServer server; +PsychicWebSocketHandler websocketHandler; +PsychicEventSource eventSource; + +const char *htmlContent = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +bool connectToWifi() +{ + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.setSleep(false); + WiFi.useStaticBuffers(true); + + WiFi.begin(ssid, password); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + Serial.println("PsychicHTTP Benchmark"); + + if (connectToWifi()) + { + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + //start our server + server.listen(80); + + //our index + server.on("/", HTTP_GET, [](PsychicRequest *request) + { + return request->reply(200, "text/html", htmlContent); + }); + + //serve static files from LittleFS/www on / + server.serveStatic("/", LittleFS, "/www/"); + + //a websocket echo server + websocketHandler.onOpen([](PsychicWebSocketClient *client) { + client->sendMessage("Hello!"); + }); + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { + request->reply(frame); + return ESP_OK; + }); + server.on("/ws", &websocketHandler); + + //EventSource server + eventSource.onOpen([](PsychicEventSourceClient *client) { + client->send("Hello", NULL, millis(), 1000); + }); + server.on("/events", &eventSource); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/api", HTTP_GET, [](PsychicRequest *request) + { + //create a response object + StaticJsonDocument<128> output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + String foo = request->getParam("foo")->value(); + output["foo"] = foo; + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + return request->reply(200, "application/json", jsonBuffer.c_str()); + }); + } +} + +unsigned long last; +void loop() +{ + if (millis() - last > 1000) + { + Serial.printf("Free Heap: %d\n", esp_get_free_heap_size()); + last = millis(); + } +} \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/psychichttp/src/secret.h b/lib/PsychicHttp/benchmark/psychichttp/src/secret.h new file mode 100644 index 0000000..6d4bb15 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/src/secret.h @@ -0,0 +1,2 @@ +#define WIFI_SSID "Your_SSID" +#define WIFI_PASS "Your_PASS" \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/psychichttp/test/README b/lib/PsychicHttp/benchmark/psychichttp/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttp/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html diff --git a/lib/PsychicHttp/benchmark/psychichttps/.gitignore b/lib/PsychicHttp/benchmark/psychichttps/.gitignore new file mode 100644 index 0000000..9e5f911 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/lib/PsychicHttp/benchmark/psychichttps/data/server.crt b/lib/PsychicHttp/benchmark/psychichttps/data/server.crt new file mode 100644 index 0000000..34a1e01 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/data/server.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDKzCCAhOgAwIBAgIUBxM3WJf2bP12kAfqhmhhjZWv0ukwDQYJKoZIhvcNAQEL +BQAwJTEjMCEGA1UEAwwaRVNQMzIgSFRUUFMgc2VydmVyIGV4YW1wbGUwHhcNMTgx +MDE3MTEzMjU3WhcNMjgxMDE0MTEzMjU3WjAlMSMwIQYDVQQDDBpFU1AzMiBIVFRQ +UyBzZXJ2ZXIgZXhhbXBsZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALBint6nP77RCQcmKgwPtTsGK0uClxg+LwKJ3WXuye3oqnnjqJCwMEneXzGdG09T +sA0SyNPwrEgebLCH80an3gWU4pHDdqGHfJQa2jBL290e/5L5MB+6PTs2NKcojK/k +qcZkn58MWXhDW1NpAnJtjVniK2Ksvr/YIYSbyD+JiEs0MGxEx+kOl9d7hRHJaIzd +GF/vO2pl295v1qXekAlkgNMtYIVAjUy9CMpqaQBCQRL+BmPSJRkXBsYk8GPnieS4 +sUsp53DsNvCCtWDT6fd9D1v+BB6nDk/FCPKhtjYOwOAZlX4wWNSZpRNr5dfrxKsb +jAn4PCuR2akdF4G8WLUeDWECAwEAAaNTMFEwHQYDVR0OBBYEFMnmdJKOEepXrHI/ +ivM6mVqJgAX8MB8GA1UdIwQYMBaAFMnmdJKOEepXrHI/ivM6mVqJgAX8MA8GA1Ud +EwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBADiXIGEkSsN0SLSfCF1VNWO3 +emBurfOcDq4EGEaxRKAU0814VEmU87btIDx80+z5Dbf+GGHCPrY7odIkxGNn0DJY +W1WcF+DOcbiWoUN6DTkAML0SMnp8aGj9ffx3x+qoggT+vGdWVVA4pgwqZT7Ybntx +bkzcNFW0sqmCv4IN1t4w6L0A87ZwsNwVpre/j6uyBw7s8YoJHDLRFT6g7qgn0tcN +ZufhNISvgWCVJQy/SZjNBHSpnIdCUSJAeTY2mkM4sGxY0Widk8LnjydxZUSxC3Nl +hb6pnMh3jRq4h0+5CZielA4/a+TdrNPv/qok67ot/XJdY3qHCCd8O2b14OVq9jo= +-----END CERTIFICATE----- \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/psychichttps/data/server.key b/lib/PsychicHttp/benchmark/psychichttps/data/server.key new file mode 100644 index 0000000..a591325 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/data/server.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwYp7epz++0QkH +JioMD7U7BitLgpcYPi8Cid1l7snt6Kp546iQsDBJ3l8xnRtPU7ANEsjT8KxIHmyw +h/NGp94FlOKRw3ahh3yUGtowS9vdHv+S+TAfuj07NjSnKIyv5KnGZJ+fDFl4Q1tT +aQJybY1Z4itirL6/2CGEm8g/iYhLNDBsRMfpDpfXe4URyWiM3Rhf7ztqZdveb9al +3pAJZIDTLWCFQI1MvQjKamkAQkES/gZj0iUZFwbGJPBj54nkuLFLKedw7DbwgrVg +0+n3fQ9b/gQepw5PxQjyobY2DsDgGZV+MFjUmaUTa+XX68SrG4wJ+DwrkdmpHReB +vFi1Hg1hAgMBAAECggEAaTCnZkl/7qBjLexIryC/CBBJyaJ70W1kQ7NMYfniWwui +f0aRxJgOdD81rjTvkINsPp+xPRQO6oOadjzdjImYEuQTqrJTEUnntbu924eh+2D9 +Mf2CAanj0mglRnscS9mmljZ0KzoGMX6Z/EhnuS40WiJTlWlH6MlQU/FDnwC6U34y +JKy6/jGryfsx+kGU/NRvKSru6JYJWt5v7sOrymHWD62IT59h3blOiP8GMtYKeQlX +49om9Mo1VTIFASY3lrxmexbY+6FG8YO+tfIe0tTAiGrkb9Pz6tYbaj9FjEWOv4Vc ++3VMBUVdGJjgqvE8fx+/+mHo4Rg69BUPfPSrpEg7sQKBgQDlL85G04VZgrNZgOx6 +pTlCCl/NkfNb1OYa0BELqWINoWaWQHnm6lX8YjrUjwRpBF5s7mFhguFjUjp/NW6D +0EEg5BmO0ePJ3dLKSeOA7gMo7y7kAcD/YGToqAaGljkBI+IAWK5Su5yldrECTQKG +YnMKyQ1MWUfCYEwHtPvFvE5aPwKBgQDFBWXekpxHIvt/B41Cl/TftAzE7/f58JjV +MFo/JCh9TDcH6N5TMTRS1/iQrv5M6kJSSrHnq8pqDXOwfHLwxetpk9tr937VRzoL +CuG1Ar7c1AO6ujNnAEmUVC2DppL/ck5mRPWK/kgLwZSaNcZf8sydRgphsW1ogJin +7g0nGbFwXwKBgQCPoZY07Pr1TeP4g8OwWTu5F6dSvdU2CAbtZthH5q98u1n/cAj1 +noak1Srpa3foGMTUn9CHu+5kwHPIpUPNeAZZBpq91uxa5pnkDMp3UrLIRJ2uZyr8 +4PxcknEEh8DR5hsM/IbDcrCJQglM19ZtQeW3LKkY4BsIxjDf45ymH407IQKBgE/g +Ul6cPfOxQRlNLH4VMVgInSyyxWx1mODFy7DRrgCuh5kTVh+QUVBM8x9lcwAn8V9/ +nQT55wR8E603pznqY/jX0xvAqZE6YVPcw4kpZcwNwL1RhEl8GliikBlRzUL3SsW3 +q30AfqEViHPE3XpE66PPo6Hb1ymJCVr77iUuC3wtAoGBAIBrOGunv1qZMfqmwAY2 +lxlzRgxgSiaev0lTNxDzZkmU/u3dgdTwJ5DDANqPwJc6b8SGYTp9rQ0mbgVHnhIB +jcJQBQkTfq6Z0H6OoTVi7dPs3ibQJFrtkoyvYAbyk36quBmNRjVh6rc8468bhXYr +v/t+MeGJP/0Zw8v/X2CFll96 +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/psychichttps/data/www/alien.png b/lib/PsychicHttp/benchmark/psychichttps/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/benchmark/psychichttps/data/www/alien.png differ diff --git a/lib/PsychicHttp/benchmark/psychichttps/include/README b/lib/PsychicHttp/benchmark/psychichttps/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/benchmark/psychichttps/lib/README b/lib/PsychicHttp/benchmark/psychichttps/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/benchmark/psychichttps/platformio.ini b/lib/PsychicHttp/benchmark/psychichttps/platformio.ini new file mode 100644 index 0000000..868f0ca --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/platformio.ini @@ -0,0 +1,22 @@ +; 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 + +[env] +platform = espressif32 +framework = arduino +board = esp32dev +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder +lib_deps = + https://github.com/hoeken/PsychicHttp + bblanchon/ArduinoJson +board_build.filesystem = littlefs + +[env:default] diff --git a/lib/PsychicHttp/benchmark/psychichttps/src/main.cpp b/lib/PsychicHttp/benchmark/psychichttps/src/main.cpp new file mode 100644 index 0000000..2639758 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/src/main.cpp @@ -0,0 +1,240 @@ +/* Wi-Fi STA Connect and Disconnect Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. + +*/ +#include +#include +#include +#include +#include +#include "_secret.h" +#include +#include + +#ifndef WIFI_SSID + #error "You need to enter your wifi credentials. Rename secret.h to _secret.h and enter your credentials there." +#endif + +//Enter your WIFI credentials in secret.h +const char *ssid = WIFI_SSID; +const char *password = WIFI_PASS; + +PsychicHttpsServer server; +PsychicWebSocketHandler websocketHandler; + +String server_cert; +String server_key; + +const char *htmlContent = R"( + + + + Sample HTML + + +

Hello, World!

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod + rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper + arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit + accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi. + Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo + dapibus elit, id varius sem dui id lacus.

+ + +)"; + +bool connectToWifi() +{ + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.setSleep(false); + + WiFi.begin(ssid, password); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + Serial.println("PsychicHTTP Benchmark"); + + if (connectToWifi()) + { + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + File fp = LittleFS.open("/server.crt"); + if (fp) { + server_cert = fp.readString(); + } else { + Serial.println("server.pem not found, SSL not available"); + return; + } + fp.close(); + + File fp2 = LittleFS.open("/server.key"); + if (fp2) { + server_key = fp2.readString(); + } else { + Serial.println("server.key not found, SSL not available"); + return; + } + fp2.close(); + + //start our server + server.listen(443, server_cert.c_str(), server_key.c_str()); + + //our index + server.on("/", HTTP_GET, [](PsychicRequest *request) + { + return request->reply(200, "text/html", htmlContent); + }); + + //serve static files from LittleFS/www on / + server.serveStatic("/", LittleFS, "/www/"); + + //a websocket echo server + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { + request->reply(frame); + return ESP_OK; + }); + server.on("/ws", &websocketHandler); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/api", HTTP_GET, [](PsychicRequest *request) + { + //create a response object + StaticJsonDocument<128> output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + String foo = request->getParam("foo")->value(); + output["foo"] = foo; + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + return request->reply(200, "application/json", jsonBuffer.c_str()); + }); + } +} + +unsigned long last; +void loop() +{ + if (millis() - last > 1000) + { + Serial.printf("Free Heap: %d\n", esp_get_free_heap_size()); + last = millis(); + } +} \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/psychichttps/src/secret.h b/lib/PsychicHttp/benchmark/psychichttps/src/secret.h new file mode 100644 index 0000000..6d4bb15 --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/src/secret.h @@ -0,0 +1,2 @@ +#define WIFI_SSID "Your_SSID" +#define WIFI_PASS "Your_PASS" \ No newline at end of file diff --git a/lib/PsychicHttp/benchmark/psychichttps/test/README b/lib/PsychicHttp/benchmark/psychichttps/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/lib/PsychicHttp/benchmark/psychichttps/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html diff --git a/lib/PsychicHttp/benchmark/results/arduinomongoose-http-loadtest.log b/lib/PsychicHttp/benchmark/results/arduinomongoose-http-loadtest.log new file mode 100644 index 0000000..24a6e34 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/arduinomongoose-http-loadtest.log @@ -0,0 +1,1172 @@ + + +CLIENTS: *** 1 *** + +Running 60s test @ http://192.168.2.131/ +1 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 720 ms │ 14880 ms │ 29087 ms │ 29519 ms │ 15024.03 ms │ 8572.14 ms │ 29737 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 11 │ 11 │ 12 │ 14 │ 12.47 │ 0.87 │ 11 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 48.2 kB │ 48.2 kB │ 52.6 kB │ 61.3 kB │ 54.6 kB │ 3.79 kB │ 48.2 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 748 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.07s, 3.28 MB read +748 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +1 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 781 ms │ 15061 ms │ 29571 ms │ 30046 ms │ 15137.29 ms │ 8833.98 ms │ 30393 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 17 │ 18 │ 20 │ 23 │ 20.34 │ 1.27 │ 17 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 2.99 kB │ 3.15 kB │ 3.52 kB │ 4.03 kB │ 3.57 kB │ 220 B │ 2.99 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1220 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.06s, 214 kB read +1k errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +1 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 969 ms │ 15300 ms │ 29831 ms │ 30132 ms │ 15143.83 ms │ 8807.54 ms │ 30385 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 3 │ 4 │ 3.15 │ 0.36 │ 3 │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.1 kB │ 86.1 kB │ 86.1 kB │ 115 kB │ 90.4 kB │ 10.3 kB │ 86.1 kB │ +└───────────┴─────────┴─────────┴─────────┴────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 189 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +378 requests in 60.06s, 5.43 MB read +188 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 2 *** + +Running 60s test @ http://192.168.2.131/ +2 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 803 ms │ 14773 ms │ 29269 ms │ 29642 ms │ 14925.25 ms │ 8556.82 ms │ 29974 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬───────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 17 │ 17 │ 19 │ 21 │ 18.9 │ 0.98 │ 17 │ +├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 74.5 kB │ 74.5 kB │ 83.3 kB │ 92 kB │ 82.8 kB │ 4.29 kB │ 74.5 kB │ +└───────────┴─────────┴─────────┴─────────┴───────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1134 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.06s, 4.97 MB read +29 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +2 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 772 ms │ 15252 ms │ 29307 ms │ 29709 ms │ 15094.92 ms │ 8732.51 ms │ 30070 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 26 │ 27 │ 29 │ 32 │ 29.72 │ 1.43 │ 26 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 4.58 kB │ 4.75 kB │ 5.11 kB │ 5.63 kB │ 5.23 kB │ 251 B │ 4.58 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1783 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 314 kB read +1k errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +2 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 856 ms │ 15635 ms │ 28880 ms │ 29310 ms │ 15261.99 ms │ 8577.65 ms │ 29700 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 4 │ 4 │ 5 │ 6 │ 4.64 │ 0.64 │ 4 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 115 kB │ 115 kB │ 144 kB │ 172 kB │ 133 kB │ 18.1 kB │ 115 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 278 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +558 requests in 60.06s, 7.98 MB read +17 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 3 *** + +Running 60s test @ http://192.168.2.131/ +3 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 794 ms │ 15166 ms │ 29323 ms │ 29697 ms │ 15066.78 ms │ 8676.25 ms │ 30114 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 22 │ 23 │ 26 │ 29 │ 25.99 │ 1.42 │ 22 │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 96.4 kB │ 101 kB │ 114 kB │ 127 kB │ 114 kB │ 6.22 kB │ 96.4 kB │ +└───────────┴─────────┴────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1559 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 6.83 MB read +14 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +3 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 826 ms │ 14949 ms │ 29377 ms │ 29790 ms │ 15049.95 ms │ 8720.15 ms │ 30168 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 32 │ 32 │ 36 │ 39 │ 36.1 │ 1.82 │ 32 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 5.63 kB │ 5.63 kB │ 6.34 kB │ 6.87 kB │ 6.36 kB │ 319 B │ 5.63 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2166 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.1s, 381 kB read +1k errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +3 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬─────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼─────────┼──────────┤ +│ Latency │ 995 ms │ 15127 ms │ 29464 ms │ 29993 ms │ 15219.94 ms │ 8704 ms │ 30258 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴─────────┴──────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 6 │ 6 │ 5.62 │ 0.99 │ 3 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.1 kB │ 86.1 kB │ 172 kB │ 172 kB │ 161 kB │ 28.3 kB │ 86.1 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 337 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +677 requests in 60.07s, 9.67 MB read +54 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 4 *** + +Running 60s test @ http://192.168.2.131/ +4 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 702 ms │ 15255 ms │ 29811 ms │ 30226 ms │ 15144.93 ms │ 8830.16 ms │ 30616 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤ +│ Req/Sec │ 26 │ 27 │ 29 │ 32 │ 29.05 │ 1.58 │ 26 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤ +│ Bytes/Sec │ 114 kB │ 118 kB │ 127 kB │ 140 kB │ 127 kB │ 6.9 kB │ 114 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1743 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 7.63 MB read +20 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +4 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬───────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼───────────┼──────────┤ +│ Latency │ 762 ms │ 15231 ms │ 29096 ms │ 29534 ms │ 15112.66 ms │ 8660.6 ms │ 29997 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴───────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼────────┼───────┼─────────┤ +│ Req/Sec │ 35 │ 35 │ 41 │ 44 │ 40.89 │ 1.9 │ 35 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼────────┼───────┼─────────┤ +│ Bytes/Sec │ 6.16 kB │ 6.16 kB │ 7.22 kB │ 7.75 kB │ 7.2 kB │ 334 B │ 6.16 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2453 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 432 kB read +977 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +4 connections +1 workers + + +┌─────────┬─────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 1175 ms │ 15413 ms │ 29485 ms │ 30066 ms │ 15217.07 ms │ 8604.35 ms │ 30126 ms │ +└─────────┴─────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 4 │ 4 │ 8 │ 8 │ 6.47 │ 1.87 │ 4 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 115 kB │ 115 kB │ 230 kB │ 230 kB │ 186 kB │ 53.6 kB │ 115 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 388 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +780 requests in 60.05s, 11.1 MB read +39 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 5 *** + +Running 60s test @ http://192.168.2.131/ +5 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 802 ms │ 14978 ms │ 29391 ms │ 29863 ms │ 15042.57 ms │ 8642.88 ms │ 30280 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤ +│ Req/Sec │ 26 │ 29 │ 33 │ 37 │ 33.19 │ 2.13 │ 26 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤ +│ Bytes/Sec │ 114 kB │ 127 kB │ 145 kB │ 162 kB │ 145 kB │ 9.3 kB │ 114 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1991 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.07s, 8.72 MB read +10 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +5 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 724 ms │ 15356 ms │ 29304 ms │ 29791 ms │ 15198.71 ms │ 8761.23 ms │ 30174 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 40 │ 40 │ 45 │ 50 │ 44.84 │ 2.78 │ 40 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.04 kB │ 7.04 kB │ 7.92 kB │ 8.81 kB │ 7.89 kB │ 489 B │ 7.04 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2690 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 473 kB read +603 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +5 connections +1 workers + + +┌─────────┬─────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 1250 ms │ 15289 ms │ 29607 ms │ 30193 ms │ 15345.82 ms │ 8719.55 ms │ 30354 ms │ +└─────────┴─────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 10 │ 7.25 │ 2.25 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 172 kB │ 287 kB │ 208 kB │ 64.5 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 435 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +875 requests in 60.06s, 12.5 MB read +36 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 6 *** + +Running 60s test @ http://192.168.2.131/ +6 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 847 ms │ 14920 ms │ 28899 ms │ 29392 ms │ 15008.54 ms │ 8456.33 ms │ 29870 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 33 │ 33 │ 36 │ 39 │ 35.75 │ 1.75 │ 33 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 145 kB │ 145 kB │ 158 kB │ 171 kB │ 157 kB │ 7.65 kB │ 145 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2145 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 9.4 MB read +3 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +6 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 890 ms │ 14807 ms │ 29142 ms │ 29732 ms │ 14934.33 ms │ 8513.39 ms │ 30168 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 44 │ 44 │ 48 │ 53 │ 48.3 │ 2.22 │ 44 │ +├───────────┼─────────┼─────────┼────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.75 kB │ 7.75 kB │ 8.5 kB │ 9.38 kB │ 8.54 kB │ 395 B │ 7.74 kB │ +└───────────┴─────────┴─────────┴────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2898 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +6k requests in 60.07s, 512 kB read +386 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +6 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 853 ms │ 15325 ms │ 29742 ms │ 30578 ms │ 15287.1 ms │ 8714.92 ms │ 30650 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 6 │ 6 │ 6 │ 12 │ 7.7 │ 2.44 │ 6 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 172 kB │ 172 kB │ 172 kB │ 345 kB │ 221 kB │ 70 kB │ 172 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 462 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +930 requests in 60.06s, 13.3 MB read +24 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 7 *** + +Running 60s test @ http://192.168.2.131/ +7 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 785 ms │ 15141 ms │ 29506 ms │ 29981 ms │ 15124.91 ms │ 8769.84 ms │ 30379 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤ +│ Req/Sec │ 32 │ 33 │ 37 │ 40 │ 36.64 │ 2.04 │ 32 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼────────┼────────┤ +│ Bytes/Sec │ 140 kB │ 145 kB │ 162 kB │ 175 kB │ 160 kB │ 8.9 kB │ 140 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2198 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 9.63 MB read +1 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +7 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 773 ms │ 15322 ms │ 29472 ms │ 29911 ms │ 15145.75 ms │ 8792.14 ms │ 30238 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 45 │ 45 │ 51 │ 56 │ 50.62 │ 3.07 │ 45 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.97 kB │ 7.97 kB │ 9.03 kB │ 9.92 kB │ 8.96 kB │ 541 B │ 7.96 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3037 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +6k requests in 60.06s, 538 kB read +252 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +7 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 903 ms │ 15426 ms │ 29337 ms │ 30187 ms │ 15395.14 ms │ 8592.24 ms │ 30239 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 7 │ 7 │ 7 │ 14 │ 8.06 │ 2.03 │ 7 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 201 kB │ 201 kB │ 201 kB │ 402 kB │ 231 kB │ 58 kB │ 201 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 483 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +973 requests in 60.06s, 13.9 MB read +27 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 8 *** + +Running 60s test @ http://192.168.2.131/ +8 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 947 ms │ 15230 ms │ 29194 ms │ 29710 ms │ 15139.81 ms │ 8698.37 ms │ 30418 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 31 │ 33 │ 38 │ 43 │ 37.92 │ 2.7 │ 31 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 136 kB │ 145 kB │ 167 kB │ 188 kB │ 166 kB │ 11.8 kB │ 136 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2275 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 9.96 MB read +1 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +8 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 818 ms │ 15102 ms │ 29043 ms │ 29502 ms │ 14999.69 ms │ 8454.75 ms │ 30295 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 44 │ 45 │ 51 │ 60 │ 51.37 │ 3.35 │ 44 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.79 kB │ 7.97 kB │ 9.03 kB │ 10.6 kB │ 9.09 kB │ 591 B │ 7.79 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3082 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +6k requests in 60s, 546 kB read +222 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +8 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 951 ms │ 15565 ms │ 30182 ms │ 30252 ms │ 15396.59 ms │ 8860.08 ms │ 31138 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 7 │ 8 │ 8 │ 14 │ 8.56 │ 1.59 │ 7 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 201 kB │ 230 kB │ 230 kB │ 402 kB │ 245 kB │ 45.5 kB │ 201 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 513 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.06s, 14.7 MB read +31 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 9 *** + +Running 60s test @ http://192.168.2.131/ +9 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬───────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼───────────┼──────────┤ +│ Latency │ 951 ms │ 15246 ms │ 28914 ms │ 29402 ms │ 15108.58 ms │ 8543.6 ms │ 30524 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴───────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 31 │ 32 │ 37 │ 43 │ 37.42 │ 2.9 │ 31 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 136 kB │ 140 kB │ 162 kB │ 188 kB │ 164 kB │ 12.7 kB │ 136 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2245 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.05s, 9.83 MB read +1 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +9 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 885 ms │ 15043 ms │ 29217 ms │ 29730 ms │ 14953.4 ms │ 8530.16 ms │ 30399 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 44 │ 46 │ 52 │ 58 │ 52.1 │ 3.22 │ 44 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.79 kB │ 8.14 kB │ 9.21 kB │ 10.3 kB │ 9.22 kB │ 570 B │ 7.79 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3126 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +6k requests in 60.07s, 553 kB read +189 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +9 connections +1 workers + + +┌─────────┬─────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 1079 ms │ 15444 ms │ 28978 ms │ 29935 ms │ 15389.63 ms │ 8469.15 ms │ 30003 ms │ +└─────────┴─────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 9 │ 10 │ 8.56 │ 2.21 │ 1 │ +├───────────┼─────┼──────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 258 kB │ 287 kB │ 245 kB │ 63.4 kB │ 28.7 kB │ +└───────────┴─────┴──────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 513 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.06s, 14.7 MB read +20 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 10 *** + +Running 60s test @ http://192.168.2.131/ +10 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 996 ms │ 15183 ms │ 29343 ms │ 29946 ms │ 15135.07 ms │ 8665.13 ms │ 30794 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 32 │ 32 │ 37 │ 43 │ 37.59 │ 2.43 │ 32 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 140 kB │ 140 kB │ 162 kB │ 188 kB │ 165 kB │ 10.6 kB │ 140 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2255 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 9.88 MB read +5 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +10 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 876 ms │ 15390 ms │ 29322 ms │ 29837 ms │ 15193.95 ms │ 8726.45 ms │ 30887 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 46 │ 47 │ 52 │ 60 │ 52.42 │ 3.63 │ 46 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 8.14 kB │ 8.32 kB │ 9.21 kB │ 10.6 kB │ 9.28 kB │ 642 B │ 8.14 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3145 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +6k requests in 60.07s, 557 kB read +193 errors (0 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +10 connections +1 workers + + +┌─────────┬─────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 1126 ms │ 15812 ms │ 30288 ms │ 31239 ms │ 15913.56 ms │ 8747.22 ms │ 32439 ms │ +└─────────┴─────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────┬─────────┬────────┬────────┬────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼─────────┼────────┼────────┼────────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 2 │ 10 │ 10 │ 8.84 │ 2.37 │ 2 │ +├───────────┼─────┼─────────┼────────┼────────┼────────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 57.4 kB │ 287 kB │ 287 kB │ 254 kB │ 68 kB │ 57.4 kB │ +└───────────┴─────┴─────────┴────────┴────────┴────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 530 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.06s, 15.2 MB read +42 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 15 *** + +Running 60s test @ http://192.168.2.131/ +15 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +15 connections +1 workers + + +┌─────────┬────────┬──────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼──────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 690 ms │ 12131 ms │ 28685 ms │ 29798 ms │ 13051.88 ms │ 8385.32 ms │ 32739 ms │ +└─────────┴────────┴──────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 46 │ 50 │ 56 │ 63 │ 55.99 │ 3.53 │ 46 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 8.14 kB │ 8.86 kB │ 9.92 kB │ 11.2 kB │ 9.91 kB │ 624 B │ 8.14 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3359 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +7k requests in 60.06s, 595 kB read +269 errors (5 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +15 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + + + +CLIENTS: *** 20 *** + +Running 60s test @ http://192.168.2.131/ +20 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +20 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 377 ms │ 5749 ms │ 19598 ms │ 21657 ms │ 6953.55 ms │ 5299.16 ms │ 23969 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 45 │ 45 │ 55 │ 60 │ 54.27 │ 3.9 │ 45 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.88 kB │ 7.88 kB │ 9.63 kB │ 10.6 kB │ 9.53 kB │ 687 B │ 7.88 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3256 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +7k requests in 60.06s, 571 kB read +312 errors (30 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +20 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + diff --git a/lib/PsychicHttp/benchmark/results/arduinomongoose-websocket-loadtest.log b/lib/PsychicHttp/benchmark/results/arduinomongoose-websocket-loadtest.log new file mode 100644 index 0000000..8c18045 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/arduinomongoose-websocket-loadtest.log @@ -0,0 +1,246 @@ + + +CLIENTS: *** 1 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 1 +Agent: none + +Completed requests: 3750 +Total errors: 0 +Total time: 60.001 s +Mean latency: 15.5 ms +Effective rps: 62 + +Percentage of requests served within a certain time + 50% 12 ms + 90% 18 ms + 95% 36 ms + 99% 80 ms + 100% 223 ms (longest request) + + +CLIENTS: *** 2 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 2 +Agent: none + +Completed requests: 5795 +Total errors: 0 +Total time: 60.004 s +Mean latency: 20.2 ms +Effective rps: 97 + +Percentage of requests served within a certain time + 50% 16 ms + 90% 27 ms + 95% 64 ms + 99% 86 ms + 100% 108 ms (longest request) + + +CLIENTS: *** 3 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 3 +Agent: none + +Completed requests: 7445 +Total errors: 0 +Total time: 60.003 s +Mean latency: 23.6 ms +Effective rps: 124 + +Percentage of requests served within a certain time + 50% 19 ms + 90% 32 ms + 95% 70 ms + 99% 92 ms + 100% 121 ms (longest request) + + +CLIENTS: *** 4 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 4 +Agent: none + +Completed requests: 8751 +Total errors: 0 +Total time: 60.005 s +Mean latency: 26.9 ms +Effective rps: 146 + +Percentage of requests served within a certain time + 50% 22 ms + 90% 38 ms + 95% 73 ms + 99% 95 ms + 100% 115 ms (longest request) + + +CLIENTS: *** 5 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 5 +Agent: none + +Completed requests: 9953 +Total errors: 0 +Total time: 60.004 s +Mean latency: 29.6 ms +Effective rps: 166 + +Percentage of requests served within a certain time + 50% 25 ms + 90% 42 ms + 95% 74 ms + 99% 93 ms + 100% 116 ms (longest request) + + +CLIENTS: *** 6 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 6 +Agent: none + +Completed requests: 10871 +Total errors: 0 +Total time: 60.005 s +Mean latency: 32.6 ms +Effective rps: 181 + +Percentage of requests served within a certain time + 50% 27 ms + 90% 50 ms + 95% 82 ms + 99% 100 ms + 100% 116 ms (longest request) + + +CLIENTS: *** 7 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 7 +Agent: none + +Completed requests: 11777 +Total errors: 0 +Total time: 60.003 s +Mean latency: 35.1 ms +Effective rps: 196 + +Percentage of requests served within a certain time + 50% 30 ms + 90% 66 ms + 95% 83 ms + 99% 101 ms + 100% 137 ms (longest request) + + +CLIENTS: *** 8 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 8 +Running on cores: 2 +Agent: none + +Completed requests: 11639 +Total errors: 0 +Total time: 60.004 s +Mean latency: 35.4 ms +Effective rps: 194 + +Percentage of requests served within a certain time + 50% 30 ms + 90% 67 ms + 95% 86 ms + 99% 106 ms + 100% 135 ms (longest request) + + +CLIENTS: *** 10 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 10 +Running on cores: 2 +Agent: none + +Completed requests: 11619 +Total errors: 0 +Total time: 60.004 s +Mean latency: 35.6 ms +Effective rps: 194 + +Percentage of requests served within a certain time + 50% 30 ms + 90% 71 ms + 95% 87 ms + 99% 105 ms + 100% 125 ms (longest request) + + +CLIENTS: *** 16 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 16 +Running on cores: 2 +Agent: none + +Completed requests: 15314 +Total errors: 0 +Total time: 60.005 s +Mean latency: 54.2 ms +Effective rps: 255 + +Percentage of requests served within a certain time + 50% 46 ms + 90% 91 ms + 95% 105 ms + 99% 127 ms + 100% 826 ms (longest request) + + +CLIENTS: *** 20 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 20 +Running on cores: 2 +Agent: none + +Completed requests: 15370 +Total errors: 0 +Total time: 60.005 s +Mean latency: 57.7 ms +Effective rps: 256 + +Percentage of requests served within a certain time + 50% 48 ms + 90% 96 ms + 95% 110 ms + 99% 132 ms + 100% 851 ms (longest request) diff --git a/lib/PsychicHttp/benchmark/results/espasync-http-loadtest.log b/lib/PsychicHttp/benchmark/results/espasync-http-loadtest.log new file mode 100644 index 0000000..cafa123 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/espasync-http-loadtest.log @@ -0,0 +1,1165 @@ + + +CLIENTS: *** 1 *** + +Running 60s test @ http://192.168.2.131/ +1 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 32 ms │ 40 ms │ 118 ms │ 118 ms │ 54.67 ms │ 29.29 ms │ 118 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.1 │ 0.31 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 4.38 kB │ 438 B │ 1.31 kB │ 4.38 kB │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 6 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +12 requests in 60.08s, 26.3 kB read +5 errors (5 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +1 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 61 ms │ 64 ms │ 131 ms │ 131 ms │ 93.84 ms │ 31.05 ms │ 131 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬───────┬────────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼───────┼────────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.1 │ 0.31 │ 1 │ +├───────────┼─────┼──────┼─────┼───────┼────────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 174 B │ 17.4 B │ 52.2 B │ 174 B │ +└───────────┴─────┴──────┴─────┴───────┴────────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 6 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +12 requests in 60.08s, 1.04 kB read +5 errors (5 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +1 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 135 ms │ 142 ms │ 162 ms │ 162 ms │ 145.84 ms │ 10.32 ms │ 162 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.1 │ 0.31 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 28.8 kB │ 2.88 kB │ 8.63 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 6 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +12 requests in 60.07s, 173 kB read +5 errors (5 timeouts) + + +---------------- + + + +CLIENTS: *** 2 *** + +Running 60s test @ http://192.168.2.131/ +2 connections +1 workers + + +┌─────────┬───────┬───────┬───────┬───────┬──────────┬──────────┬───────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼───────┼───────┼──────────┼──────────┼───────┤ +│ Latency │ 29 ms │ 52 ms │ 93 ms │ 93 ms │ 56.09 ms │ 17.92 ms │ 93 ms │ +└─────────┴───────┴───────┴───────┴───────┴──────────┴──────────┴───────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 2 │ 0.2 │ 0.61 │ 2 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 8.76 kB │ 876 B │ 2.63 kB │ 8.76 kB │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 12 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +24 requests in 60.08s, 52.5 kB read +10 errors (10 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +2 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 60 ms │ 106 ms │ 126 ms │ 126 ms │ 102.5 ms │ 21.86 ms │ 126 ms │ +└─────────┴───────┴────────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬───────┬────────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼───────┼────────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 2 │ 0.2 │ 0.61 │ 2 │ +├───────────┼─────┼──────┼─────┼───────┼────────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 348 B │ 34.8 B │ 104 B │ 348 B │ +└───────────┴─────┴──────┴─────┴───────┴────────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 12 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +24 requests in 60.08s, 2.09 kB read +10 errors (10 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +2 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 228 ms │ 245 ms │ 268 ms │ 268 ms │ 245.34 ms │ 13.38 ms │ 268 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 2 │ 0.2 │ 0.61 │ 2 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 57.5 kB │ 5.75 kB │ 17.3 kB │ 57.5 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 12 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +24 requests in 60.07s, 345 kB read +10 errors (10 timeouts) + + +---------------- + + + +CLIENTS: *** 3 *** + +Running 60s test @ http://192.168.2.131/ +3 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 40 ms │ 97 ms │ 133 ms │ 133 ms │ 95.45 ms │ 30.82 ms │ 133 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 3 │ 0.3 │ 0.91 │ 3 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 13.1 kB │ 1.31 kB │ 3.94 kB │ 13.1 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 18 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +36 requests in 60.08s, 78.8 kB read +15 errors (15 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +3 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 55 ms │ 66 ms │ 211 ms │ 211 ms │ 82.78 ms │ 37.03 ms │ 211 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬───────┬────────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼───────┼────────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 3 │ 0.3 │ 0.91 │ 3 │ +├───────────┼─────┼──────┼─────┼───────┼────────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 522 B │ 52.2 B │ 157 B │ 522 B │ +└───────────┴─────┴──────┴─────┴───────┴────────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 18 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +36 requests in 60.1s, 3.13 kB read +15 errors (15 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +3 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 215 ms │ 278 ms │ 348 ms │ 348 ms │ 280.56 ms │ 30.51 ms │ 348 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 3 │ 0.3 │ 0.91 │ 3 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 86.3 kB │ 8.62 kB │ 25.9 kB │ 86.3 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 18 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +36 requests in 60.15s, 518 kB read +15 errors (15 timeouts) + + +---------------- + + + +CLIENTS: *** 4 *** + +Running 60s test @ http://192.168.2.131/ +4 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 29 ms │ 76 ms │ 137 ms │ 137 ms │ 86.55 ms │ 35.16 ms │ 137 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 4 │ 0.4 │ 1.21 │ 4 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 17.5 kB │ 1.75 kB │ 5.25 kB │ 17.5 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 24 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +48 requests in 60.13s, 105 kB read +20 errors (20 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +4 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬───────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼───────────┼────────┤ +│ Latency │ 54 ms │ 108 ms │ 523 ms │ 523 ms │ 164.71 ms │ 130.96 ms │ 523 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴───────────┴────────┘ +┌───────────┬─────┬──────┬─────┬───────┬────────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼───────┼────────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 4 │ 0.4 │ 1.21 │ 4 │ +├───────────┼─────┼──────┼─────┼───────┼────────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 696 B │ 69.6 B │ 209 B │ 696 B │ +└───────────┴─────┴──────┴─────┴───────┴────────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 24 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +48 requests in 60.09s, 4.18 kB read +20 errors (20 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +4 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬─────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼─────────┼────────┤ +│ Latency │ 322 ms │ 379 ms │ 405 ms │ 405 ms │ 372.55 ms │ 20.5 ms │ 405 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴─────────┴────────┘ +┌───────────┬─────┬──────┬─────┬────────┬─────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 4 │ 0.4 │ 1.21 │ 4 │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 115 kB │ 11.5 kB │ 34.5 kB │ 115 kB │ +└───────────┴─────┴──────┴─────┴────────┴─────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 24 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +48 requests in 60.08s, 690 kB read +20 errors (20 timeouts) + + +---------------- + + + +CLIENTS: *** 5 *** + +Running 60s test @ http://192.168.2.131/ +5 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬─────────┬─────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼─────────┼─────────┼────────┤ +│ Latency │ 36 ms │ 104 ms │ 148 ms │ 148 ms │ 94.7 ms │ 35.9 ms │ 148 ms │ +└─────────┴───────┴────────┴────────┴────────┴─────────┴─────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 5 │ 0.5 │ 1.5 │ 5 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 21.9 kB │ 2.19 kB │ 6.57 kB │ 21.9 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 30 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +60 requests in 60.05s, 131 kB read +25 errors (25 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +5 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 66 ms │ 123 ms │ 263 ms │ 263 ms │ 127.67 ms │ 37.33 ms │ 263 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬───────┬──────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼───────┼──────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 5 │ 0.5 │ 1.5 │ 5 │ +├───────────┼─────┼──────┼─────┼───────┼──────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 870 B │ 87 B │ 261 B │ 870 B │ +└───────────┴─────┴──────┴─────┴───────┴──────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 30 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +60 requests in 60.07s, 5.22 kB read +25 errors (25 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +5 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 348 ms │ 398 ms │ 465 ms │ 465 ms │ 399.27 ms │ 31.99 ms │ 465 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬────────┬─────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 5 │ 0.5 │ 1.5 │ 5 │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 144 kB │ 14.4 kB │ 43.1 kB │ 144 kB │ +└───────────┴─────┴──────┴─────┴────────┴─────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 30 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +60 requests in 60.08s, 863 kB read +25 errors (25 timeouts) + + +---------------- + + + +CLIENTS: *** 6 *** + +Running 60s test @ http://192.168.2.131/ +6 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 34 ms │ 111 ms │ 188 ms │ 188 ms │ 113.25 ms │ 41.29 ms │ 188 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 6 │ 0.6 │ 1.81 │ 6 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 26.3 kB │ 2.63 kB │ 7.88 kB │ 26.3 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +72 requests in 60.07s, 158 kB read +30 errors (30 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +6 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 61 ms │ 121 ms │ 296 ms │ 296 ms │ 134.95 ms │ 46.95 ms │ 296 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 6 │ 0.6 │ 1.81 │ 6 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 1.05 kB │ 105 B │ 315 B │ 1.05 kB │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +72 requests in 60.09s, 6.3 kB read +30 errors (30 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +6 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 322 ms │ 422 ms │ 522 ms │ 522 ms │ 422.98 ms │ 51.58 ms │ 522 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬────────┬─────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 6 │ 0.6 │ 1.81 │ 6 │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 173 kB │ 17.2 kB │ 51.7 kB │ 173 kB │ +└───────────┴─────┴──────┴─────┴────────┴─────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +72 requests in 60.08s, 1.04 MB read +30 errors (30 timeouts) + + +---------------- + + + +CLIENTS: *** 7 *** + +Running 60s test @ http://192.168.2.131/ +7 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 60 ms │ 129 ms │ 220 ms │ 280 ms │ 127.81 ms │ 51.08 ms │ 280 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 7 │ 0.7 │ 2.1 │ 7 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 30.7 kB │ 3.06 kB │ 9.19 kB │ 30.6 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 42 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +84 requests in 60.08s, 184 kB read +35 errors (35 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +7 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 63 ms │ 125 ms │ 252 ms │ 289 ms │ 126.22 ms │ 46.41 ms │ 289 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 7 │ 0.7 │ 2.1 │ 7 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 1.23 kB │ 123 B │ 368 B │ 1.23 kB │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 42 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +84 requests in 60.07s, 7.35 kB read +35 errors (35 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +7 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬──────────┬───────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼──────────┼───────────┼────────┤ +│ Latency │ 144 ms │ 439 ms │ 877 ms │ 921 ms │ 439.3 ms │ 138.35 ms │ 921 ms │ +└─────────┴────────┴────────┴────────┴────────┴──────────┴───────────┴────────┘ +┌───────────┬─────┬──────┬─────┬────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 7 │ 0.69 │ 1.87 │ 1 │ +├───────────┼─────┼──────┼─────┼────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 201 kB │ 19.6 kB │ 53.7 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 41 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +83 requests in 60.07s, 1.18 MB read +35 errors (35 timeouts) + + +---------------- + + + +CLIENTS: *** 8 *** + +Running 60s test @ http://192.168.2.131/ +8 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼────────┼──────────┼────────┤ +│ Latency │ 74 ms │ 141 ms │ 193 ms │ 198 ms │ 143 ms │ 31.11 ms │ 198 ms │ +└─────────┴───────┴────────┴────────┴────────┴────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬───────┬────────┬─────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼───────┼────────┼─────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 8 │ 0.8 │ 2.41 │ 8 │ +├───────────┼─────┼──────┼─────┼───────┼────────┼─────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 35 kB │ 3.5 kB │ 10.5 kB │ 35 kB │ +└───────────┴─────┴──────┴─────┴───────┴────────┴─────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 48 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +96 requests in 60.08s, 210 kB read +40 errors (40 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +8 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 59 ms │ 138 ms │ 284 ms │ 319 ms │ 139.8 ms │ 53.96 ms │ 319 ms │ +└─────────┴───────┴────────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬────────┬───────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼────────┼───────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 8 │ 0.8 │ 2.36 │ 1 │ +├───────────┼─────┼──────┼─────┼────────┼───────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 1.4 kB │ 140 B │ 411 B │ 175 B │ +└───────────┴─────┴──────┴─────┴────────┴───────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 48 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +96 requests in 60.07s, 8.4 kB read +40 errors (40 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +8 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + + + +CLIENTS: *** 9 *** + +Running 60s test @ http://192.168.2.131/ +9 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 31 ms │ 116 ms │ 206 ms │ 210 ms │ 109.58 ms │ 45.11 ms │ 210 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 9 │ 0.9 │ 2.7 │ 9 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 39.4 kB │ 3.94 kB │ 11.8 kB │ 39.4 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 54 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +108 requests in 60.08s, 236 kB read +45 errors (45 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +9 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 66 ms │ 131 ms │ 313 ms │ 349 ms │ 139.95 ms │ 60.66 ms │ 349 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 9 │ 0.9 │ 2.7 │ 9 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 1.57 kB │ 158 B │ 473 B │ 1.57 kB │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 54 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +108 requests in 60.08s, 9.45 kB read +45 errors (45 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +9 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + + + +CLIENTS: *** 10 *** + +Running 60s test @ http://192.168.2.131/ +10 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 35 ms │ 96 ms │ 264 ms │ 267 ms │ 103.97 ms │ 54.56 ms │ 267 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 10 │ 1 │ 3 │ 10 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 43.8 kB │ 4.38 kB │ 13.1 kB │ 43.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 60 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +120 requests in 60.08s, 263 kB read +50 errors (50 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +10 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 64 ms │ 144 ms │ 411 ms │ 437 ms │ 156.64 ms │ 80.67 ms │ 437 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 10 │ 1 │ 2.83 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 1.75 kB │ 175 B │ 495 B │ 175 B │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 60 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +120 requests in 60.08s, 10.5 kB read +50 errors (50 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +10 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + + + +CLIENTS: *** 15 *** + +Running 60s test @ http://192.168.2.131/ +15 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬──────────┬─────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼──────────┼─────────┼────────┤ +│ Latency │ 29 ms │ 104 ms │ 359 ms │ 362 ms │ 121.5 ms │ 77.5 ms │ 362 ms │ +└─────────┴───────┴────────┴────────┴────────┴──────────┴─────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 14 │ 1.34 │ 4.02 │ 12 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 52.6 kB │ 5.12 kB │ 15.4 kB │ 48.3 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 80 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +170 requests in 60.09s, 307 kB read +75 errors (75 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +15 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬───────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼───────────┼────────┤ +│ Latency │ 91 ms │ 148 ms │ 505 ms │ 574 ms │ 174.38 ms │ 100.31 ms │ 574 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴───────────┴────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 15 │ 1.5 │ 4.06 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 2.63 kB │ 263 B │ 710 B │ 175 B │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 90 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +180 requests in 60.08s, 15.8 kB read +75 errors (75 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +15 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + + + +CLIENTS: *** 20 *** + +Running 60s test @ http://192.168.2.131/ +20 connections +1 workers + + +┌─────────┬───────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤ +│ Latency │ 62 ms │ 1134 ms │ 6942 ms │ 6976 ms │ 1884.35 ms │ 1805.12 ms │ 6976 ms │ +└─────────┴───────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 15 │ 1.44 │ 4.15 │ 4 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 57.2 kB │ 4.42 kB │ 14.2 kB │ 5.82 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 86 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +211 requests in 60.08s, 265 kB read +105 errors (100 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +20 connections +1 workers + + +┌─────────┬───────┬────────┬─────────┬─────────┬───────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼─────────┼─────────┼───────────┼────────────┼─────────┤ +│ Latency │ 62 ms │ 232 ms │ 4030 ms │ 6972 ms │ 586.75 ms │ 1218.03 ms │ 6972 ms │ +└─────────┴───────┴────────┴─────────┴─────────┴───────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬───────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 11 │ 1.39 │ 3.08 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼───────┼───────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 1.89 kB │ 238 B │ 529 B │ 172 B │ +└───────────┴─────┴──────┴─────┴─────────┴───────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 83 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +203 requests in 60.09s, 14.3 kB read +100 errors (100 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +20 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + diff --git a/lib/PsychicHttp/benchmark/results/espasync-websocket-loadtest.log b/lib/PsychicHttp/benchmark/results/espasync-websocket-loadtest.log new file mode 100644 index 0000000..acc21d1 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/espasync-websocket-loadtest.log @@ -0,0 +1,252 @@ + + +CLIENTS: *** 1 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 1 +Agent: none + +Completed requests: 4231 +Total errors: 0 +Total time: 60.002 s +Mean latency: 13.6 ms +Effective rps: 71 + +Percentage of requests served within a certain time + 50% 10 ms + 90% 16 ms + 95% 24 ms + 99% 81 ms + 100% 280 ms (longest request) + + +CLIENTS: *** 2 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 2 +Agent: none + +Completed requests: 5914 +Total errors: 0 +Total time: 60.001 s +Mean latency: 19.7 ms +Effective rps: 99 + +Percentage of requests served within a certain time + 50% 15 ms + 90% 26 ms + 95% 67 ms + 99% 86 ms + 100% 109 ms (longest request) + + +CLIENTS: *** 3 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 3 +Agent: none + +Completed requests: 8204 +Total errors: 0 +Total time: 60.003 s +Mean latency: 21.4 ms +Effective rps: 137 + +Percentage of requests served within a certain time + 50% 17 ms + 90% 29 ms + 95% 68 ms + 99% 87 ms + 100% 104 ms (longest request) + + +CLIENTS: *** 4 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 4 +Agent: none + +Completed requests: 9634 +Total errors: 0 +Total time: 60.004 s +Mean latency: 24.4 ms +Effective rps: 161 + +Percentage of requests served within a certain time + 50% 19 ms + 90% 33 ms + 95% 73 ms + 99% 91 ms + 100% 145 ms (longest request) + + +CLIENTS: *** 5 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 5 +Agent: none + +Completed requests: 10759 +Total errors: 0 +Total time: 60.003 s +Mean latency: 27.3 ms +Effective rps: 179 + +Percentage of requests served within a certain time + 50% 22 ms + 90% 39 ms + 95% 76 ms + 99% 95 ms + 100% 117 ms (longest request) + + +CLIENTS: *** 6 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 6 +Agent: none + +Completed requests: 11302 +Total errors: 0 +Total time: 60.004 s +Mean latency: 31.3 ms +Effective rps: 188 + +Percentage of requests served within a certain time + 50% 26 ms + 90% 58 ms + 95% 81 ms + 99% 100 ms + 100% 122 ms (longest request) + + +CLIENTS: *** 7 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 7 +Agent: none + +Completed requests: 12713 +Total errors: 0 +Total time: 60.003 s +Mean latency: 32.5 ms +Effective rps: 212 + +Percentage of requests served within a certain time + 50% 27 ms + 90% 52 ms + 95% 81 ms + 99% 99 ms + 100% 125 ms (longest request) + + +CLIENTS: *** 8 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 8 +Running on cores: 2 +Agent: none + +Completed requests: 13157 +Total errors: 0 +Total time: 60.003 s +Mean latency: 35.9 ms +Effective rps: 219 + +Percentage of requests served within a certain time + 50% 30 ms + 90% 71 ms + 95% 88 ms + 99% 107 ms + 100% 132 ms (longest request) + + +CLIENTS: *** 10 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 10 +Running on cores: 2 +Agent: none + +Completed requests: 13417 +Total errors: 2 +Total time: 60.001 s +Mean latency: 34.4 ms +Effective rps: 224 + +Percentage of requests served within a certain time + 50% 30 ms + 90% 53 ms + 95% 81 ms + 99% 101 ms + 100% 124 ms (longest request) + + -1: 2 errors + + +CLIENTS: *** 16 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 16 +Running on cores: 2 +Agent: none + +Completed requests: 12804 +Total errors: 7 +Total time: 60.001 s +Mean latency: 36.4 ms +Effective rps: 213 + +Percentage of requests served within a certain time + 50% 30 ms + 90% 70 ms + 95% 86 ms + 99% 106 ms + 100% 135 ms (longest request) + + -1: 7 errors + + +CLIENTS: *** 20 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 20 +Running on cores: 2 +Agent: none + +Completed requests: 8421 +Total errors: 13 +Total time: 60.003 s +Mean latency: 37.2 ms +Effective rps: 140 + +Percentage of requests served within a certain time + 50% 20 ms + 90% 50 ms + 95% 77 ms + 99% 105 ms + 100% 9227 ms (longest request) + + -1: 13 errors diff --git a/lib/PsychicHttp/benchmark/results/psychic-http-loadtest.log b/lib/PsychicHttp/benchmark/results/psychic-http-loadtest.log new file mode 100644 index 0000000..148d378 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/psychic-http-loadtest.log @@ -0,0 +1,1172 @@ + + +CLIENTS: *** 1 *** + +Running 60s test @ http://192.168.2.131/ +1 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 24 ms │ 31 ms │ 100 ms │ 134 ms │ 39.16 ms │ 22.82 ms │ 270 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 18 │ 21 │ 25 │ 30 │ 25.19 │ 2.28 │ 18 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 78.1 kB │ 91.1 kB │ 108 kB │ 130 kB │ 109 kB │ 9.88 kB │ 78.1 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1511 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.05s, 6.55 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +1 connections +1 workers + + +┌─────────┬───────┬───────┬───────┬───────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼───────┼───────┼──────────┼──────────┼────────┤ +│ Latency │ 19 ms │ 25 ms │ 91 ms │ 99 ms │ 31.42 ms │ 18.78 ms │ 116 ms │ +└─────────┴───────┴───────┴───────┴───────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 26 │ 28 │ 31 │ 34 │ 31.29 │ 1.79 │ 26 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 3.46 kB │ 3.73 kB │ 4.16 kB │ 4.56 kB │ 4.19 kB │ 241 B │ 3.46 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1877 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.06s, 251 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +1 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 141 ms │ 201 ms │ 317 ms │ 331 ms │ 206.85 ms │ 51.73 ms │ 366 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 4 │ 4 │ 5 │ 6 │ 4.82 │ 0.62 │ 4 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 115 kB │ 115 kB │ 144 kB │ 173 kB │ 139 kB │ 17.8 kB │ 115 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 289 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +290 requests in 60.07s, 8.32 MB read + + +---------------- + + + +CLIENTS: *** 2 *** + +Running 60s test @ http://192.168.2.131/ +2 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 26 ms │ 41 ms │ 167 ms │ 203 ms │ 55.52 ms │ 37.23 ms │ 373 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 29 │ 31 │ 35 │ 40 │ 35.64 │ 2.36 │ 29 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 126 kB │ 135 kB │ 152 kB │ 174 kB │ 155 kB │ 10.2 kB │ 126 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2138 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.06s, 9.27 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +2 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 25 ms │ 35 ms │ 103 ms │ 112 ms │ 43.19 ms │ 21.44 ms │ 142 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 40 │ 40 │ 46 │ 50 │ 45.7 │ 2.76 │ 40 │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 5.36 kB │ 5.36 kB │ 6.17 kB │ 6.7 kB │ 6.12 kB │ 370 B │ 5.36 kB │ +└───────────┴─────────┴─────────┴─────────┴────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2742 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 367 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +2 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 188 ms │ 322 ms │ 475 ms │ 507 ms │ 324.51 ms │ 70.51 ms │ 535 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.15 │ 0.63 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 177 kB │ 18 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 369 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +371 requests in 60.06s, 10.6 MB read + + +---------------- + + + +CLIENTS: *** 3 *** + +Running 60s test @ http://192.168.2.131/ +3 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 31 ms │ 54 ms │ 185 ms │ 212 ms │ 68.63 ms │ 39.36 ms │ 386 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 38 │ 39 │ 43 │ 47 │ 43.32 │ 2.31 │ 38 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 165 kB │ 169 kB │ 187 kB │ 204 kB │ 188 kB │ 10 kB │ 165 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2599 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 11.3 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +3 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 29 ms │ 42 ms │ 116 ms │ 126 ms │ 51.59 ms │ 23.91 ms │ 175 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 40 │ 51 │ 58 │ 64 │ 57.59 │ 4.25 │ 40 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 5.36 kB │ 6.83 kB │ 7.78 kB │ 8.58 kB │ 7.72 kB │ 569 B │ 5.36 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3455 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 463 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +3 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬───────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼───────────┼────────┤ +│ Latency │ 203 ms │ 458 ms │ 761 ms │ 814 ms │ 474.54 ms │ 168.16 ms │ 902 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴───────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 4 │ 5 │ 6 │ 7 │ 6.29 │ 0.67 │ 4 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 115 kB │ 144 kB │ 173 kB │ 201 kB │ 181 kB │ 19 kB │ 115 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 377 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +380 requests in 60.06s, 10.9 MB read + + +---------------- + + + +CLIENTS: *** 4 *** + +Running 60s test @ http://192.168.2.131/ +4 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 37 ms │ 63 ms │ 206 ms │ 239 ms │ 81.32 ms │ 45.45 ms │ 396 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 42 │ 44 │ 49 │ 56 │ 48.87 │ 3.01 │ 42 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 182 kB │ 191 kB │ 213 kB │ 243 kB │ 212 kB │ 13 kB │ 182 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2932 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.05s, 12.7 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +4 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 33 ms │ 50 ms │ 123 ms │ 131 ms │ 58.29 ms │ 23.99 ms │ 159 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 59 │ 59 │ 68 │ 78 │ 68 │ 4.3 │ 59 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 7.91 kB │ 7.91 kB │ 9.12 kB │ 10.5 kB │ 9.11 kB │ 576 B │ 7.91 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4080 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.05s, 547 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +4 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬───────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼───────────┼───────────┼─────────┤ +│ Latency │ 326 ms │ 534 ms │ 1064 ms │ 1141 ms │ 635.61 ms │ 238.71 ms │ 1210 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴───────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.27 │ 0.63 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 180 kB │ 18.1 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 376 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +380 requests in 60.05s, 10.8 MB read + + +---------------- + + + +CLIENTS: *** 5 *** + +Running 60s test @ http://192.168.2.131/ +5 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 44 ms │ 74 ms │ 222 ms │ 261 ms │ 91.54 ms │ 47.88 ms │ 417 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 47 │ 47 │ 54 │ 60 │ 54.29 │ 3.05 │ 47 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 204 kB │ 204 kB │ 234 kB │ 260 kB │ 235 kB │ 13.2 kB │ 204 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3257 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 14.1 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +5 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 36 ms │ 57 ms │ 126 ms │ 138 ms │ 64.99 ms │ 24.42 ms │ 195 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 64 │ 69 │ 76 │ 84 │ 76.32 │ 3.97 │ 64 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 8.58 kB │ 9.25 kB │ 10.2 kB │ 11.3 kB │ 10.2 kB │ 532 B │ 8.58 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4579 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 614 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +5 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬───────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼───────────┼───────────┼─────────┤ +│ Latency │ 439 ms │ 652 ms │ 1393 ms │ 1458 ms │ 780.62 ms │ 290.11 ms │ 2018 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴───────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 4 │ 5 │ 6 │ 8 │ 6.35 │ 0.78 │ 4 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 115 kB │ 144 kB │ 173 kB │ 230 kB │ 183 kB │ 22.1 kB │ 115 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 381 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +386 requests in 60.06s, 11 MB read + + +---------------- + + + +CLIENTS: *** 6 *** + +Running 60s test @ http://192.168.2.131/ +6 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 50 ms │ 85 ms │ 238 ms │ 268 ms │ 102.35 ms │ 50.03 ms │ 517 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 49 │ 53 │ 58 │ 65 │ 58.3 │ 3.13 │ 49 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 213 kB │ 230 kB │ 252 kB │ 282 kB │ 253 kB │ 13.6 kB │ 213 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3498 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.05s, 15.2 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +6 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 41 ms │ 64 ms │ 138 ms │ 151 ms │ 74.53 ms │ 27.06 ms │ 286 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 71 │ 71 │ 80 │ 90 │ 79.92 │ 4.07 │ 71 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 9.59 kB │ 9.59 kB │ 10.8 kB │ 12.2 kB │ 10.8 kB │ 548 B │ 9.59 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4795 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 647 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +6 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬───────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼───────────┼──────────┼─────────┤ +│ Latency │ 579 ms │ 840 ms │ 1766 ms │ 1816 ms │ 973.38 ms │ 355.3 ms │ 2392 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴───────────┴──────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 4 │ 4 │ 6 │ 8 │ 6.1 │ 0.87 │ 4 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 115 kB │ 115 kB │ 173 kB │ 230 kB │ 176 kB │ 25 kB │ 115 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 366 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +372 requests in 60.06s, 10.5 MB read + + +---------------- + + + +CLIENTS: *** 7 *** + +Running 60s test @ http://192.168.2.131/ +7 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 57 ms │ 96 ms │ 249 ms │ 293 ms │ 113.4 ms │ 53.05 ms │ 640 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 53 │ 54 │ 62 │ 68 │ 61.44 │ 3.82 │ 53 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 230 kB │ 234 kB │ 269 kB │ 295 kB │ 266 kB │ 16.6 kB │ 230 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3686 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.05s, 16 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +7 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 45 ms │ 69 ms │ 145 ms │ 154 ms │ 79.11 ms │ 27.06 ms │ 274 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬───────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼───────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 78 │ 80 │ 89 │ 99 │ 87.9 │ 4.78 │ 78 │ +├───────────┼─────────┼─────────┼───────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 10.5 kB │ 10.8 kB │ 12 kB │ 13.4 kB │ 11.9 kB │ 644 B │ 10.5 kB │ +└───────────┴─────────┴─────────┴───────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5274 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 712 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +7 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 671 ms │ 952 ms │ 1965 ms │ 2059 ms │ 1094.09 ms │ 402.31 ms │ 3654 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 8 │ 6.34 │ 0.79 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 230 kB │ 182 kB │ 22.7 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 380 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +387 requests in 60.07s, 10.9 MB read + + +---------------- + + + +CLIENTS: *** 8 *** + +Running 60s test @ http://192.168.2.131/ +8 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼─────────┤ +│ Latency │ 56 ms │ 95 ms │ 243 ms │ 275 ms │ 110.53 ms │ 52.27 ms │ 1027 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 52 │ 54 │ 62 │ 73 │ 62.99 │ 4.89 │ 52 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 226 kB │ 234 kB │ 269 kB │ 317 kB │ 273 kB │ 21.2 kB │ 226 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3779 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 16.4 MB read +6 errors (6 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +8 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬─────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼─────────┼──────────┼────────┤ +│ Latency │ 45 ms │ 70 ms │ 146 ms │ 156 ms │ 80.9 ms │ 28.68 ms │ 308 ms │ +└─────────┴───────┴───────┴────────┴────────┴─────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 77 │ 77 │ 86 │ 95 │ 85.92 │ 4.89 │ 77 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 10.4 kB │ 10.4 kB │ 11.6 kB │ 12.8 kB │ 11.6 kB │ 659 B │ 10.4 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5155 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 696 kB read +6 errors (6 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +8 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 699 ms │ 979 ms │ 2038 ms │ 2128 ms │ 1111.14 ms │ 406.26 ms │ 3506 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.25 │ 0.6 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 180 kB │ 17.1 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 375 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +389 requests in 60.06s, 10.8 MB read +6 errors (6 timeouts) + + +---------------- + + + +CLIENTS: *** 9 *** + +Running 60s test @ http://192.168.2.131/ +9 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 57 ms │ 96 ms │ 249 ms │ 277 ms │ 112.81 ms │ 51.23 ms │ 626 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 52 │ 57 │ 61 │ 68 │ 61.7 │ 3.18 │ 52 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 226 kB │ 247 kB │ 265 kB │ 295 kB │ 268 kB │ 13.8 kB │ 226 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3702 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 16.1 MB read +12 errors (12 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +9 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 45 ms │ 70 ms │ 144 ms │ 154 ms │ 79.64 ms │ 27.25 ms │ 239 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬───────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 76 │ 79 │ 87 │ 96 │ 87.34 │ 4.79 │ 76 │ +├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 10.3 kB │ 10.7 kB │ 11.8 kB │ 13 kB │ 11.8 kB │ 647 B │ 10.3 kB │ +└───────────┴─────────┴─────────┴─────────┴───────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5240 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.1s, 707 kB read +12 errors (12 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +9 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 664 ms │ 952 ms │ 2001 ms │ 2055 ms │ 1092.56 ms │ 399.94 ms │ 3588 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.35 │ 0.63 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 183 kB │ 18 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 381 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +402 requests in 60.06s, 11 MB read +12 errors (12 timeouts) + + +---------------- + + + +CLIENTS: *** 10 *** + +Running 60s test @ http://192.168.2.131/ +10 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 56 ms │ 97 ms │ 244 ms │ 277 ms │ 113.43 ms │ 51.43 ms │ 616 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 48 │ 51 │ 61 │ 69 │ 61.42 │ 3.92 │ 48 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 208 kB │ 221 kB │ 265 kB │ 300 kB │ 266 kB │ 17 kB │ 208 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3685 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 16 MB read +18 errors (18 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +10 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 45 ms │ 71 ms │ 147 ms │ 154 ms │ 81.57 ms │ 28.91 ms │ 335 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 75 │ 76 │ 86 │ 92 │ 85.32 │ 4.46 │ 75 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 10.1 kB │ 10.3 kB │ 11.6 kB │ 12.4 kB │ 11.5 kB │ 601 B │ 10.1 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5119 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 691 kB read +18 errors (18 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +10 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 705 ms │ 940 ms │ 1962 ms │ 2052 ms │ 1075.72 ms │ 385.45 ms │ 3313 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.45 │ 0.65 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 186 kB │ 18.5 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 387 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +415 requests in 60.05s, 11.1 MB read +18 errors (18 timeouts) + + +---------------- + + + +CLIENTS: *** 15 *** + +Running 60s test @ http://192.168.2.131/ +15 connections +1 workers + +node:internal/event_target:1084 + process.nextTick(() => { throw err; }); + ^ + +TypeError: colorize is not a function + at /Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:46:31 + at Array.forEach () + at printResult (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/printResult.js:43:43) + at EventEmitter. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/progressTracker.js:79:28) + at EventEmitter.emit (node:events:527:35) + at _cb (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/init.js:76:13) + at handleFinish (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:41:5) + at Worker. (/Users/hoeken/.nvm/versions/node/v21.1.0/lib/node_modules/autocannon/lib/manager.js:78:13) + at Worker.emit (node:events:515:28) + at MessagePort. (node:internal/worker:263:53) + +Node.js v21.1.0 + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +15 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼─────────┤ +│ Latency │ 44 ms │ 69 ms │ 158 ms │ 318 ms │ 82.99 ms │ 44.17 ms │ 1074 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴─────────┘ +┌───────────┬─────────┬────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 22 │ 23 │ 88 │ 98 │ 83.74 │ 16.45 │ 22 │ +├───────────┼─────────┼────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 2.97 kB │ 3.1 kB │ 11.9 kB │ 13.2 kB │ 11.3 kB │ 2.22 kB │ 2.97 kB │ +└───────────┴─────────┴────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5024 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.06s, 678 kB read +48 errors (48 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +15 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 665 ms │ 954 ms │ 1989 ms │ 2105 ms │ 1092.91 ms │ 396.34 ms │ 3476 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.35 │ 0.66 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 183 kB │ 18.8 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 381 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +444 requests in 60.06s, 11 MB read +48 errors (48 timeouts) + + +---------------- + + + +CLIENTS: *** 20 *** + +Running 60s test @ http://192.168.2.131/ +20 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 57 ms │ 97 ms │ 255 ms │ 322 ms │ 114.69 ms │ 55.79 ms │ 683 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 26 │ 48 │ 61 │ 67 │ 60.75 │ 5.8 │ 26 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 113 kB │ 208 kB │ 265 kB │ 291 kB │ 264 kB │ 25.2 kB │ 113 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3645 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.05s, 15.8 MB read +78 errors (78 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +20 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 44 ms │ 69 ms │ 142 ms │ 153 ms │ 78.14 ms │ 26.88 ms │ 256 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬───────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼───────┼───────┼─────────┤ +│ Req/Sec │ 76 │ 78 │ 88 │ 100 │ 88.92 │ 5.59 │ 76 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼───────┼───────┼─────────┤ +│ Bytes/Sec │ 10.3 kB │ 10.5 kB │ 11.9 kB │ 13.5 kB │ 12 kB │ 754 B │ 10.3 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴───────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5335 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 720 kB read +78 errors (78 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +20 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 705 ms │ 940 ms │ 1991 ms │ 2070 ms │ 1085.97 ms │ 389.59 ms │ 3357 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 5 │ 5 │ 6 │ 7 │ 6.39 │ 0.64 │ 5 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 144 kB │ 144 kB │ 173 kB │ 201 kB │ 184 kB │ 18.2 kB │ 144 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 383 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +481 requests in 60.06s, 11 MB read +78 errors (78 timeouts) + + +---------------- + diff --git a/lib/PsychicHttp/benchmark/results/psychic-ssl-http-loadtest.log b/lib/PsychicHttp/benchmark/results/psychic-ssl-http-loadtest.log new file mode 100644 index 0000000..17e3414 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/psychic-ssl-http-loadtest.log @@ -0,0 +1,1194 @@ + + +CLIENTS: *** 1 *** + +Running 60s test @ https://192.168.2.131/ +1 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬─────────┬─────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼─────────┼─────────┼─────────┤ +│ Latency │ 33 ms │ 40 ms │ 139 ms │ 157 ms │ 51.6 ms │ 58.1 ms │ 1757 ms │ +└─────────┴───────┴───────┴────────┴────────┴─────────┴─────────┴─────────┘ +┌───────────┬─────┬─────────┬─────────┬────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 5 │ 20 │ 24 │ 19.19 │ 4.05 │ 5 │ +├───────────┼─────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 21.7 kB │ 86.8 kB │ 104 kB │ 83.2 kB │ 17.5 kB │ 21.7 kB │ +└───────────┴─────┴─────────┴─────────┴────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1151 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.07s, 4.99 MB read + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +1 connections +1 workers + + +┌─────────┬───────┬───────┬───────┬────────┬──────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼───────┼────────┼──────────┼──────────┼─────────┤ +│ Latency │ 21 ms │ 27 ms │ 89 ms │ 100 ms │ 32.17 ms │ 43.71 ms │ 1745 ms │ +└─────────┴───────┴───────┴───────┴────────┴──────────┴──────────┴─────────┘ +┌───────────┬─────┬─────────┬─────────┬─────────┬────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼─────────┼─────────┼─────────┼────────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 8 │ 32 │ 38 │ 30.57 │ 5.91 │ 8 │ +├───────────┼─────┼─────────┼─────────┼─────────┼────────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 1.07 kB │ 4.29 kB │ 5.09 kB │ 4.1 kB │ 791 B │ 1.07 kB │ +└───────────┴─────┴─────────┴─────────┴─────────┴────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1834 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.07s, 246 kB read + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +1 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼───────────┼─────────┤ +│ Latency │ 216 ms │ 252 ms │ 400 ms │ 408 ms │ 281.55 ms │ 122.23 ms │ 1871 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴───────────┴─────────┘ +┌───────────┬─────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 1 │ 4 │ 5 │ 3.54 │ 0.83 │ 1 │ +├───────────┼─────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 28.8 kB │ 115 kB │ 144 kB │ 102 kB │ 23.8 kB │ 28.8 kB │ +└───────────┴─────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 212 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +213 requests in 60.07s, 6.1 MB read + + +---------------- + + + +CLIENTS: *** 2 *** + +Running 60s test @ https://192.168.2.131/ +2 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼───────────┼─────────┤ +│ Latency │ 37 ms │ 54 ms │ 149 ms │ 164 ms │ 64.14 ms │ 106.26 ms │ 3230 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 0 │ 0 │ 33 │ 36 │ 30.92 │ 7.43 │ 27 │ +├───────────┼─────┼──────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 143 kB │ 156 kB │ 134 kB │ 32.2 kB │ 117 kB │ +└───────────┴─────┴──────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1855 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.06s, 8.05 MB read + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +2 connections +1 workers + + +┌─────────┬───────┬───────┬───────┬────────┬──────────┬─────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼───────┼────────┼──────────┼─────────┼─────────┤ +│ Latency │ 27 ms │ 38 ms │ 95 ms │ 106 ms │ 44.65 ms │ 87.8 ms │ 3211 ms │ +└─────────┴───────┴───────┴───────┴────────┴──────────┴─────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 47 │ 52 │ 44.29 │ 10.57 │ 35 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 6.35 kB │ 7.02 kB │ 5.98 kB │ 1.43 kB │ 4.72 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2657 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.07s, 359 kB read + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +2 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼───────────┼─────────┤ +│ Latency │ 320 ms │ 456 ms │ 633 ms │ 701 ms │ 488.51 ms │ 296.92 ms │ 3820 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 4 │ 5 │ 4.09 │ 1.09 │ 3 │ +├───────────┼─────┼──────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 115 kB │ 144 kB │ 118 kB │ 31.2 kB │ 86.3 kB │ +└───────────┴─────┴──────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 245 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +247 requests in 60.07s, 7.05 MB read + + +---------------- + + + +CLIENTS: *** 3 *** + +Running 60s test @ https://192.168.2.131/ +3 connections +1 workers + + +┌─────────┬─────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 1535 ms │ 6477 ms │ 14517 ms │ 14517 ms │ 6462.25 ms │ 2849.18 ms │ 14517 ms │ +└─────────┴─────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.53 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.6 kB │ 2.27 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +75 requests in 60.1s, 156 kB read +5 errors (0 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +3 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 1517 ms │ 1638 ms │ 3675 ms │ 3675 ms │ 1697.95 ms │ 343.44 ms │ 3675 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬────────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.59 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 78.8 B │ 66.6 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴────────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +73 requests in 60.11s, 4.72 kB read +1 errors (0 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +3 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬─────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼─────────────┼────────────┼──────────┤ +│ Latency │ 386 ms │ 9117 ms │ 50313 ms │ 50313 ms │ 12942.77 ms │ 11833.9 ms │ 50313 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴─────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 3 │ 0.57 │ 0.7 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 86.4 kB │ 16.3 kB │ 19.9 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 34 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +68 requests in 60.11s, 979 kB read +28 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 4 *** + +Running 60s test @ https://192.168.2.131/ +4 connections +1 workers + + +┌─────────┬─────────┬─────────┬──────────┬──────────┬─────────────┬─────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼──────────┼──────────┼─────────────┼─────────────┼──────────┤ +│ Latency │ 1530 ms │ 1686 ms │ 40733 ms │ 40733 ms │ 10336.06 ms │ 12608.67 ms │ 40733 ms │ +└─────────┴─────────┴─────────┴──────────┴──────────┴─────────────┴─────────────┴──────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.53 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.6 kB │ 2.27 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +76 requests in 60.15s, 156 kB read +11 errors (0 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +4 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼──────────┼─────────┤ +│ Latency │ 1495 ms │ 1586 ms │ 4490 ms │ 4490 ms │ 1673.35 ms │ 485.3 ms │ 4490 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴──────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬────────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.59 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 78.8 B │ 66.6 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴────────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +74 requests in 60.15s, 4.72 kB read +3 errors (0 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +4 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬─────────────┬─────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼─────────────┼─────────────┼──────────┤ +│ Latency │ 340 ms │ 3642 ms │ 49950 ms │ 49950 ms │ 13180.63 ms │ 14189.21 ms │ 49950 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴─────────────┴─────────────┴──────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 2 │ 0.59 │ 0.65 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 28.8 kB │ 57.6 kB │ 16.8 kB │ 18.4 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +72 requests in 60.15s, 1.01 MB read +30 errors (0 timeouts) + + +---------------- + + + +CLIENTS: *** 5 *** + +Running 60s test @ https://192.168.2.131/ +5 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 1449 ms │ 1597 ms │ 4810 ms │ 4810 ms │ 1691.72 ms │ 537.09 ms │ 4810 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.59 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.53 kB │ 2.14 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +75 requests in 60.13s, 152 kB read +11 errors (0 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +5 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 1510 ms │ 1584 ms │ 4971 ms │ 4971 ms │ 1685.03 ms │ 564.99 ms │ 4971 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬────────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.59 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 78.8 B │ 66.6 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴────────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +75 requests in 60.14s, 4.72 kB read +1 errors (0 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +5 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 409 ms │ 5565 ms │ 38132 ms │ 38132 ms │ 9430.76 ms │ 9263.66 ms │ 38132 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 2 │ 0.56 │ 0.62 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 57.6 kB │ 15.8 kB │ 17.8 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 33 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +69 requests in 60.14s, 950 kB read +29 errors (1 timeouts) + + +---------------- + + + +CLIENTS: *** 6 *** + +Running 60s test @ https://192.168.2.131/ +6 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 1007 ms │ 1603 ms │ 5373 ms │ 5373 ms │ 1696.69 ms │ 639.15 ms │ 5373 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.59 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.53 kB │ 2.14 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +76 requests in 60.14s, 152 kB read +15 errors (2 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +6 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 976 ms │ 1586 ms │ 6118 ms │ 6118 ms │ 1683.15 ms │ 773.87 ms │ 6118 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬────────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.59 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 78.8 B │ 66.6 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴────────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 35 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +76 requests in 60.14s, 4.72 kB read +4 errors (2 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +6 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 437 ms │ 3543 ms │ 18174 ms │ 18174 ms │ 4264.16 ms │ 3629.94 ms │ 18174 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.54 │ 0.6 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 28.8 kB │ 15.3 kB │ 17 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 32 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +69 requests in 60.15s, 921 kB read +30 errors (5 timeouts) + + +---------------- + + + +CLIENTS: *** 7 *** + +Running 60s test @ https://192.168.2.131/ +7 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬───────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼───────────┼──────────┤ +│ Latency │ 979 ms │ 1600 ms │ 37778 ms │ 37778 ms │ 2654.48 ms │ 5987.7 ms │ 37778 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴───────────┴──────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.53 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.6 kB │ 2.27 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +80 requests in 60.1s, 156 kB read +17 errors (7 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +7 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 928 ms │ 1591 ms │ 7128 ms │ 7128 ms │ 1648.53 ms │ 955.92 ms │ 7128 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬──────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 81 B │ 66.1 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴──────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +79 requests in 60.09s, 4.86 kB read +13 errors (8 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +7 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬───────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼───────────┼────────────┼──────────┤ +│ Latency │ 487 ms │ 1740 ms │ 24134 ms │ 24134 ms │ 3069.3 ms │ 4835.41 ms │ 24134 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴───────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.4 │ 0.53 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 28.8 kB │ 11.5 kB │ 15 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 24 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +69 requests in 60.08s, 691 kB read +37 errors (21 timeouts) + + +---------------- + + + +CLIENTS: *** 8 *** + +Running 60s test @ https://192.168.2.131/ +8 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 892 ms │ 1585 ms │ 6973 ms │ 6973 ms │ 1613.52 ms │ 927.38 ms │ 6973 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.62 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.68 kB │ 2.11 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 37 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +89 requests in 60.09s, 161 kB read +25 errors (16 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +8 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 964 ms │ 1593 ms │ 7380 ms │ 7380 ms │ 1645.62 ms │ 998.66 ms │ 7380 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬──────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.53 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 81 B │ 70.6 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴──────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +86 requests in 60.1s, 4.86 kB read +14 errors (14 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +8 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 341 ms │ 4820 ms │ 26999 ms │ 26999 ms │ 7220.49 ms │ 6874.47 ms │ 26999 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 3 │ 0.56 │ 0.67 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 86.4 kB │ 15.8 kB │ 19.3 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 33 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +84 requests in 60.08s, 950 kB read +41 errors (27 timeouts) + + +---------------- + + + +CLIENTS: *** 9 *** + +Running 60s test @ https://192.168.2.131/ +9 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤ +│ Latency │ 960 ms │ 1598 ms │ 7751 ms │ 7751 ms │ 1665.89 ms │ 1056.66 ms │ 7751 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.6 kB │ 2.13 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +93 requests in 60.1s, 156 kB read +25 errors (21 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +9 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤ +│ Latency │ 933 ms │ 1589 ms │ 7703 ms │ 7703 ms │ 1649.14 ms │ 1051.77 ms │ 7703 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬──────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 81 B │ 66.1 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴──────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +93 requests in 60.09s, 4.86 kB read +21 errors (20 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +9 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┤ +│ Latency │ 1049 ms │ 1783 ms │ 7382 ms │ 7382 ms │ 1758 ms │ 1027.58 ms │ 7382 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.57 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 28.8 kB │ 28.8 kB │ 16.3 kB │ 14.3 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 34 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +91 requests in 60.1s, 979 kB read +48 errors (29 timeouts) + + +---------------- + + + +CLIENTS: *** 10 *** + +Running 60s test @ https://192.168.2.131/ +10 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤ +│ Latency │ 979 ms │ 1597 ms │ 7548 ms │ 7548 ms │ 1660.23 ms │ 1024.01 ms │ 7548 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.6 kB │ 2.13 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +100 requests in 60.09s, 156 kB read +29 errors (26 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +10 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 976 ms │ 1590 ms │ 7480 ms │ 7480 ms │ 1628.95 ms │ 1021.2 ms │ 7480 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬──────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 81 B │ 66.1 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴──────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +101 requests in 60.12s, 4.86 kB read +28 errors (28 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +10 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 585 ms │ 5882 ms │ 27503 ms │ 27503 ms │ 6338.82 ms │ 6773.89 ms │ 27503 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.54 │ 0.6 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 28.8 kB │ 15.3 kB │ 17 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 32 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +97 requests in 60.14s, 921 kB read +54 errors (38 timeouts) + + +---------------- + + + +CLIENTS: *** 15 *** + +Running 60s test @ https://192.168.2.131/ +15 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤ +│ Latency │ 957 ms │ 1601 ms │ 7609 ms │ 7609 ms │ 1654.73 ms │ 1034.04 ms │ 7609 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 4.34 kB │ 4.34 kB │ 2.6 kB │ 2.13 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +135 requests in 60.14s, 156 kB read +64 errors (56 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +15 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 966 ms │ 1576 ms │ 7369 ms │ 7369 ms │ 1612.68 ms │ 991.59 ms │ 7369 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬────────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.62 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼────────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 83.3 B │ 65.6 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴────────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 37 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +136 requests in 60.14s, 5 kB read +61 errors (60 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +15 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬──────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼──────────┼────────────┼──────────┤ +│ Latency │ 300 ms │ 7281 ms │ 34953 ms │ 34953 ms │ 10153 ms │ 9647.72 ms │ 34953 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴──────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 3 │ 0.52 │ 0.68 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 86.4 kB │ 14.9 kB │ 19.3 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 31 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +132 requests in 60.11s, 892 kB read +84 errors (70 timeouts) + + +---------------- + + + +CLIENTS: *** 20 *** + +Running 60s test @ https://192.168.2.131/ +20 connections +1 workers + + +┌─────────┬────────┬─────────┬──────────┬──────────┬────────────┬────────────┬──────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼──────────┼──────────┼────────────┼────────────┼──────────┤ +│ Latency │ 944 ms │ 1600 ms │ 36783 ms │ 36783 ms │ 2881.21 ms │ 6487.79 ms │ 36783 ms │ +└─────────┴────────┴─────────┴──────────┴──────────┴────────────┴────────────┴──────────┘ +┌───────────┬─────┬──────┬─────┬─────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────┼─────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 0 │ 1 │ 0.49 │ 0.54 │ 1 │ +├───────────┼─────┼──────┼─────┼─────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 0 B │ 4.34 kB │ 2.1 kB │ 2.31 kB │ 4.34 kB │ +└───────────┴─────┴──────┴─────┴─────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 29 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +165 requests in 60.1s, 126 kB read +96 errors (92 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/api?foo=bar +20 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 931 ms │ 1568 ms │ 7097 ms │ 7097 ms │ 1637.53 ms │ 950.49 ms │ 7097 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────┬──────┬───────┬───────┬──────┬────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.6 │ 0.49 │ 1 │ +├───────────┼─────┼──────┼───────┼───────┼──────┼────────┼───────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 135 B │ 135 B │ 81 B │ 66.1 B │ 135 B │ +└───────────┴─────┴──────┴───────┴───────┴──────┴────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 36 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +170 requests in 60.12s, 4.86 kB read +87 errors (85 timeouts) + + +---------------- + +Running 60s test @ https://192.168.2.131/alien.png +20 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤ +│ Latency │ 1116 ms │ 1707 ms │ 7481 ms │ 7481 ms │ 1754.83 ms │ 1032.66 ms │ 7481 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘ +┌───────────┬─────┬──────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 0 │ 0 │ 1 │ 1 │ 0.57 │ 0.5 │ 1 │ +├───────────┼─────┼──────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 0 B │ 0 B │ 28.8 kB │ 28.8 kB │ 16.3 kB │ 14.3 kB │ 28.8 kB │ +└───────────┴─────┴──────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 34 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +168 requests in 60.09s, 979 kB read +114 errors (95 timeouts) + + +---------------- + diff --git a/lib/PsychicHttp/benchmark/results/psychic-ssl-websocket-loadtest.log b/lib/PsychicHttp/benchmark/results/psychic-ssl-websocket-loadtest.log new file mode 100644 index 0000000..4e9aa5c --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/psychic-ssl-websocket-loadtest.log @@ -0,0 +1,246 @@ + + +CLIENTS: *** 1 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 1 +Agent: none + +Completed requests: 2039 +Total errors: 0 +Total time: 60.002 s +Mean latency: 27.8 ms +Effective rps: 34 + +Percentage of requests served within a certain time + 50% 24 ms + 90% 34 ms + 95% 62 ms + 99% 97 ms + 100% 109 ms (longest request) + + +CLIENTS: *** 2 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 2 +Agent: none + +Completed requests: 2969 +Total errors: 0 +Total time: 60.003 s +Mean latency: 37.7 ms +Effective rps: 49 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 52 ms + 95% 92 ms + 99% 110 ms + 100% 126 ms (longest request) + + +CLIENTS: *** 3 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 3 +Agent: none + +Completed requests: 2883 +Total errors: 0 +Total time: 60.003 s +Mean latency: 38.2 ms +Effective rps: 48 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 52 ms + 95% 86 ms + 99% 109 ms + 100% 1711 ms (longest request) + + +CLIENTS: *** 4 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 4 +Agent: none + +Completed requests: 2858 +Total errors: 0 +Total time: 60.003 s +Mean latency: 37.9 ms +Effective rps: 48 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 49 ms + 95% 76 ms + 99% 104 ms + 100% 1740 ms (longest request) + + +CLIENTS: *** 5 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 5 +Agent: none + +Completed requests: 2772 +Total errors: 0 +Total time: 60.003 s +Mean latency: 38.6 ms +Effective rps: 46 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 49 ms + 95% 79 ms + 99% 106 ms + 100% 1634 ms (longest request) + + +CLIENTS: *** 6 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 6 +Agent: none + +Completed requests: 2722 +Total errors: 0 +Total time: 60.003 s +Mean latency: 38.7 ms +Effective rps: 45 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 49 ms + 95% 72 ms + 99% 102 ms + 100% 1694 ms (longest request) + + +CLIENTS: *** 7 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 7 +Agent: none + +Completed requests: 2552 +Total errors: 0 +Total time: 60.003 s +Mean latency: 40.7 ms +Effective rps: 43 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 52 ms + 95% 86 ms + 99% 112 ms + 100% 1816 ms (longest request) + + +CLIENTS: *** 8 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 8 +Running on cores: 2 +Agent: none + +Completed requests: 2507 +Total errors: 0 +Total time: 60.005 s +Mean latency: 40.8 ms +Effective rps: 42 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 50 ms + 95% 80 ms + 99% 112 ms + 100% 1646 ms (longest request) + + +CLIENTS: *** 10 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 10 +Running on cores: 2 +Agent: none + +Completed requests: 2265 +Total errors: 0 +Total time: 60.008 s +Mean latency: 43.7 ms +Effective rps: 38 + +Percentage of requests served within a certain time + 50% 33 ms + 90% 52 ms + 95% 79 ms + 99% 114 ms + 100% 1675 ms (longest request) + + +CLIENTS: *** 16 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 16 +Running on cores: 2 +Agent: none + +Completed requests: 1795 +Total errors: 0 +Total time: 60.003 s +Mean latency: 49.7 ms +Effective rps: 30 + +Percentage of requests served within a certain time + 50% 33 ms + 90% 51 ms + 95% 77 ms + 99% 112 ms + 100% 1741 ms (longest request) + + +CLIENTS: *** 20 *** + + +Target URL: wss://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 20 +Running on cores: 2 +Agent: none + +Completed requests: 1603 +Total errors: 0 +Total time: 60.004 s +Mean latency: 54.1 ms +Effective rps: 27 + +Percentage of requests served within a certain time + 50% 33 ms + 90% 60 ms + 95% 94 ms + 99% 133 ms + 100% 1729 ms (longest request) diff --git a/lib/PsychicHttp/benchmark/results/psychic-v1.1-http-loadtest.log b/lib/PsychicHttp/benchmark/results/psychic-v1.1-http-loadtest.log new file mode 100644 index 0000000..9fc5dae --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/psychic-v1.1-http-loadtest.log @@ -0,0 +1,1179 @@ + + +CLIENTS: *** 1 *** + +Running 60s test @ http://192.168.2.131/ +1 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 25 ms │ 34 ms │ 137 ms │ 175 ms │ 44.75 ms │ 33.04 ms │ 363 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 13 │ 14 │ 23 │ 27 │ 22.05 │ 3.62 │ 13 │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 56.4 kB │ 60.7 kB │ 99.8 kB │ 117 kB │ 95.6 kB │ 15.7 kB │ 56.4 kB │ +└───────────┴─────────┴─────────┴─────────┴────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1323 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.06s, 5.74 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +1 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 21 ms │ 29 ms │ 122 ms │ 173 ms │ 40.61 ms │ 38.19 ms │ 646 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬───────┬───────┬─────────┬─────────┬─────────┬─────────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼───────┼───────┼─────────┼─────────┼─────────┼─────────┼───────┤ +│ Req/Sec │ 2 │ 6 │ 27 │ 34 │ 24.29 │ 7.62 │ 2 │ +├───────────┼───────┼───────┼─────────┼─────────┼─────────┼─────────┼───────┤ +│ Bytes/Sec │ 268 B │ 804 B │ 3.62 kB │ 4.56 kB │ 3.25 kB │ 1.02 kB │ 268 B │ +└───────────┴───────┴───────┴─────────┴─────────┴─────────┴─────────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1457 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +1k requests in 60.07s, 195 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +1 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 254 ms │ 291 ms │ 441 ms │ 487 ms │ 311.18 ms │ 52.89 ms │ 503 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 2 │ 3 │ 4 │ 3.2 │ 0.58 │ 2 │ +├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 57.6 kB │ 86.4 kB │ 115 kB │ 92.1 kB │ 16.4 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴─────────┴────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 192 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +193 requests in 60.07s, 5.53 MB read + + +---------------- + + + +CLIENTS: *** 2 *** + +Running 60s test @ http://192.168.2.131/ +2 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 29 ms │ 46 ms │ 184 ms │ 213 ms │ 63.03 ms │ 43.98 ms │ 437 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 13 │ 13 │ 34 │ 43 │ 31.44 │ 7.44 │ 13 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 56.4 kB │ 56.4 kB │ 148 kB │ 187 kB │ 136 kB │ 32.2 kB │ 56.4 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 1886 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +2k requests in 60.07s, 8.18 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +2 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 27 ms │ 37 ms │ 107 ms │ 120 ms │ 44.09 ms │ 20.34 ms │ 188 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬───────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼───────┼───────┼─────────┤ +│ Req/Sec │ 24 │ 25 │ 46 │ 52 │ 44.79 │ 6.1 │ 24 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼───────┼───────┼─────────┤ +│ Bytes/Sec │ 3.22 kB │ 3.35 kB │ 6.17 kB │ 6.97 kB │ 6 kB │ 817 B │ 3.22 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴───────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2687 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.06s, 360 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +2 connections +1 workers + + +┌─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 375 ms │ 552 ms │ 759 ms │ 848 ms │ 556.76 ms │ 95.75 ms │ 875 ms │ +└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 4 │ 4 │ 3.59 │ 0.53 │ 3 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.4 kB │ 86.4 kB │ 115 kB │ 115 kB │ 103 kB │ 15.1 kB │ 86.3 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 215 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +217 requests in 60.09s, 6.19 MB read + + +---------------- + + + +CLIENTS: *** 3 *** + +Running 60s test @ http://192.168.2.131/ +3 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬─────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼─────────┼────────┤ +│ Latency │ 36 ms │ 56 ms │ 167 ms │ 193 ms │ 67.22 ms │ 33.6 ms │ 343 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴─────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 32 │ 34 │ 45 │ 52 │ 44.25 │ 4.31 │ 32 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 139 kB │ 148 kB │ 195 kB │ 226 kB │ 192 kB │ 18.7 kB │ 139 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 2655 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.08s, 11.5 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +3 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬─────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼─────────┼────────┤ +│ Latency │ 30 ms │ 45 ms │ 114 ms │ 128 ms │ 51.89 ms │ 22.2 ms │ 294 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴─────────┴────────┘ +┌───────────┬─────────┬────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 37 │ 44 │ 58 │ 67 │ 57.24 │ 6.16 │ 37 │ +├───────────┼─────────┼────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 4.96 kB │ 5.9 kB │ 7.78 kB │ 8.98 kB │ 7.67 kB │ 825 B │ 4.96 kB │ +└───────────┴─────────┴────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3434 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.1s, 460 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +3 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬───────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼───────────┼───────────┼─────────┤ +│ Latency │ 412 ms │ 786 ms │ 1293 ms │ 1397 ms │ 829.09 ms │ 295.53 ms │ 1412 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴───────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 3 │ 4 │ 4 │ 3.59 │ 0.53 │ 2 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 86.4 kB │ 115 kB │ 115 kB │ 103 kB │ 15.1 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 215 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +218 requests in 60.11s, 6.19 MB read + + +---------------- + + + +CLIENTS: *** 4 *** + +Running 60s test @ http://192.168.2.131/ +4 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 41 ms │ 65 ms │ 189 ms │ 221 ms │ 79.49 ms │ 39.69 ms │ 385 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 41 │ 41 │ 51 │ 56 │ 50 │ 4.07 │ 41 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 178 kB │ 178 kB │ 221 kB │ 243 kB │ 217 kB │ 17.6 kB │ 178 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3000 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.1s, 13 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +4 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 35 ms │ 51 ms │ 128 ms │ 154 ms │ 58.79 ms │ 24.56 ms │ 347 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 38 │ 50 │ 69 │ 77 │ 67.49 │ 7.34 │ 38 │ +├───────────┼─────────┼────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 5.09 kB │ 6.7 kB │ 9.25 kB │ 10.3 kB │ 9.04 kB │ 983 B │ 5.09 kB │ +└───────────┴─────────┴────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4049 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.11s, 543 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +4 connections +1 workers + + +┌─────────┬────────┬────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 630 ms │ 885 ms │ 1840 ms │ 1877 ms │ 1082.82 ms │ 406.47 ms │ 2050 ms │ +└─────────┴────────┴────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 4 │ 5 │ 3.65 │ 0.55 │ 3 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.4 kB │ 86.4 kB │ 115 kB │ 144 kB │ 105 kB │ 15.6 kB │ 86.3 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 219 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +223 requests in 60.08s, 6.3 MB read + + +---------------- + + + +CLIENTS: *** 5 *** + +Running 60s test @ http://192.168.2.131/ +5 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 47 ms │ 77 ms │ 213 ms │ 242 ms │ 91.79 ms │ 44.06 ms │ 398 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 41 │ 42 │ 55 │ 62 │ 54.12 │ 4.67 │ 41 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 178 kB │ 182 kB │ 239 kB │ 269 kB │ 235 kB │ 20.2 kB │ 178 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3247 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +3k requests in 60.08s, 14.1 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +5 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 39 ms │ 60 ms │ 126 ms │ 141 ms │ 65.76 ms │ 21.03 ms │ 172 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬─────────┬─────────┬─────────┬─────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼─────────┼─────────┼─────────┼─────────┼───────┼────────┤ +│ Req/Sec │ 53 │ 58 │ 76 │ 86 │ 75.34 │ 7.04 │ 53 │ +├───────────┼────────┼─────────┼─────────┼─────────┼─────────┼───────┼────────┤ +│ Bytes/Sec │ 7.1 kB │ 7.78 kB │ 10.2 kB │ 11.5 kB │ 10.1 kB │ 943 B │ 7.1 kB │ +└───────────┴────────┴─────────┴─────────┴─────────┴─────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4520 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.08s, 606 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +5 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 832 ms │ 1125 ms │ 2405 ms │ 2530 ms │ 1344.04 ms │ 504.13 ms │ 3485 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 3 │ 4 │ 5 │ 3.69 │ 0.57 │ 2 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 86.4 kB │ 115 kB │ 144 kB │ 106 kB │ 16.2 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 221 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +226 requests in 60.08s, 6.36 MB read + + +---------------- + + + +CLIENTS: *** 6 *** + +Running 60s test @ http://192.168.2.131/ +6 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 51 ms │ 84 ms │ 214 ms │ 249 ms │ 98.05 ms │ 44.48 ms │ 553 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 40 │ 50 │ 62 │ 66 │ 60.87 │ 4.59 │ 40 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 174 kB │ 217 kB │ 269 kB │ 286 kB │ 264 kB │ 19.9 kB │ 174 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3652 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.09s, 15.8 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +6 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 45 ms │ 68 ms │ 144 ms │ 159 ms │ 75.43 ms │ 24.46 ms │ 223 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 53 │ 63 │ 80 │ 91 │ 78.95 │ 7.74 │ 53 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 7.16 kB │ 8.51 kB │ 10.8 kB │ 12.3 kB │ 10.7 kB │ 1.04 kB │ 7.16 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4737 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.08s, 639 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +6 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 893 ms │ 1385 ms │ 3045 ms │ 3336 ms │ 1630.97 ms │ 621.58 ms │ 4350 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 3 │ 4 │ 5 │ 3.62 │ 0.58 │ 2 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 86.4 kB │ 115 kB │ 144 kB │ 104 kB │ 16.7 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 217 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +223 requests in 60.1s, 6.25 MB read + + +---------------- + + + +CLIENTS: *** 7 *** + +Running 60s test @ http://192.168.2.131/ +7 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 59 ms │ 96 ms │ 232 ms │ 260 ms │ 109.85 ms │ 47.04 ms │ 531 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬───────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Req/Sec │ 44 │ 53 │ 65 │ 72 │ 63.39 │ 5.76 │ 44 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼───────┼────────┤ +│ Bytes/Sec │ 191 kB │ 230 kB │ 282 kB │ 313 kB │ 275 kB │ 25 kB │ 191 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴───────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3803 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.08s, 16.5 MB read + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +7 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 48 ms │ 75 ms │ 139 ms │ 152 ms │ 80.37 ms │ 22.69 ms │ 291 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬───────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 52 │ 67 │ 88 │ 96 │ 86.59 │ 7.62 │ 52 │ +├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 7.02 kB │ 9.05 kB │ 11.9 kB │ 13 kB │ 11.7 kB │ 1.03 kB │ 7.02 kB │ +└───────────┴─────────┴─────────┴─────────┴───────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5195 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.11s, 701 kB read + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +7 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 845 ms │ 1642 ms │ 3537 ms │ 3656 ms │ 1887.17 ms │ 728.73 ms │ 6130 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 4 │ 4 │ 3.64 │ 0.52 │ 3 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.4 kB │ 86.4 kB │ 115 kB │ 115 kB │ 105 kB │ 14.8 kB │ 86.3 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 218 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +225 requests in 60.1s, 6.27 MB read + + +---------------- + + + +CLIENTS: *** 8 *** + +Running 60s test @ http://192.168.2.131/ +8 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼────────┤ +│ Latency │ 58 ms │ 96 ms │ 225 ms │ 256 ms │ 108.89 ms │ 45.19 ms │ 571 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴────────┘ +┌───────────┬────────┬────────┬────────┬────────┬────────┬─────────┬────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Req/Sec │ 51 │ 54 │ 65 │ 70 │ 63.92 │ 4.63 │ 51 │ +├───────────┼────────┼────────┼────────┼────────┼────────┼─────────┼────────┤ +│ Bytes/Sec │ 221 kB │ 234 kB │ 282 kB │ 304 kB │ 277 kB │ 20.1 kB │ 221 kB │ +└───────────┴────────┴────────┴────────┴────────┴────────┴─────────┴────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3835 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.07s, 16.6 MB read +6 errors (6 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +8 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬─────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼─────────┼────────┤ +│ Latency │ 50 ms │ 76 ms │ 148 ms │ 166 ms │ 83.61 ms │ 26.5 ms │ 282 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴─────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 63 │ 66 │ 82 │ 98 │ 83.15 │ 8.78 │ 63 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 8.51 kB │ 8.91 kB │ 11.1 kB │ 13.2 kB │ 11.2 kB │ 1.18 kB │ 8.51 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4989 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.08s, 674 kB read +6 errors (6 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +8 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬───────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼───────────┼───────────┼─────────┤ +│ Latency │ 806 ms │ 1614 ms │ 3526 ms │ 3769 ms │ 1851.3 ms │ 712.64 ms │ 5877 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴───────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 4 │ 5 │ 3.72 │ 0.52 │ 3 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.4 kB │ 86.4 kB │ 115 kB │ 144 kB │ 107 kB │ 14.9 kB │ 86.3 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 223 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +237 requests in 60.09s, 6.42 MB read +6 errors (6 timeouts) + + +---------------- + + + +CLIENTS: *** 9 *** + +Running 60s test @ http://192.168.2.131/ +9 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬─────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼─────────┼─────────┤ +│ Latency │ 60 ms │ 98 ms │ 232 ms │ 268 ms │ 111.69 ms │ 57.8 ms │ 1065 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴─────────┴─────────┘ +┌───────────┬───────┬────────┬────────┬────────┬────────┬───────┬───────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼───────┼────────┼────────┼────────┼────────┼───────┼───────┤ +│ Req/Sec │ 3 │ 54 │ 63 │ 72 │ 62.37 │ 8.98 │ 3 │ +├───────────┼───────┼────────┼────────┼────────┼────────┼───────┼───────┤ +│ Bytes/Sec │ 13 kB │ 234 kB │ 273 kB │ 313 kB │ 271 kB │ 39 kB │ 13 kB │ +└───────────┴───────┴────────┴────────┴────────┴────────┴───────┴───────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3742 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.07s, 16.2 MB read +12 errors (12 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +9 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 50 ms │ 77 ms │ 148 ms │ 160 ms │ 83.55 ms │ 24.72 ms │ 275 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬───────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Req/Sec │ 63 │ 67 │ 85 │ 95 │ 83.27 │ 7.2 │ 63 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┼─────────┤ +│ Bytes/Sec │ 8.51 kB │ 9.05 kB │ 11.5 kB │ 12.8 kB │ 11.2 kB │ 972 B │ 8.51 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴───────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4996 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.08s, 674 kB read +12 errors (12 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +9 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 857 ms │ 1631 ms │ 3541 ms │ 3814 ms │ 1883.14 ms │ 730.83 ms │ 6021 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 3 │ 3 │ 4 │ 4 │ 3.67 │ 0.48 │ 3 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 86.4 kB │ 86.4 kB │ 115 kB │ 115 kB │ 106 kB │ 13.5 kB │ 86.3 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 220 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +241 requests in 60.08s, 6.33 MB read +12 errors (12 timeouts) + + +---------------- + + + +CLIENTS: *** 10 *** + +Running 60s test @ http://192.168.2.131/ +10 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼─────────┤ +│ Latency │ 59 ms │ 95 ms │ 235 ms │ 276 ms │ 111.77 ms │ 57.35 ms │ 1010 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴─────────┘ +┌───────────┬─────────┬────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 17 │ 47 │ 64 │ 70 │ 62.32 │ 8.14 │ 17 │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 73.8 kB │ 204 kB │ 278 kB │ 304 kB │ 270 kB │ 35.3 kB │ 73.7 kB │ +└───────────┴─────────┴────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3739 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.08s, 16.2 MB read +18 errors (18 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +10 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 49 ms │ 82 ms │ 179 ms │ 209 ms │ 91.77 ms │ 33.92 ms │ 312 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 46 │ 48 │ 76 │ 92 │ 75.85 │ 11.6 │ 46 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 6.21 kB │ 6.48 kB │ 10.3 kB │ 12.4 kB │ 10.2 kB │ 1.57 kB │ 6.21 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4551 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 614 kB read +18 errors (18 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +10 connections +1 workers + + +┌─────────┬─────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼─────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 1062 ms │ 1673 ms │ 3588 ms │ 3643 ms │ 1903.02 ms │ 693.11 ms │ 5495 ms │ +└─────────┴─────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 2 │ 4 │ 5 │ 3.6 │ 0.64 │ 2 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 57.6 kB │ 115 kB │ 144 kB │ 104 kB │ 18.3 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 216 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +244 requests in 60.08s, 6.22 MB read +18 errors (18 timeouts) + + +---------------- + + + +CLIENTS: *** 15 *** + +Running 60s test @ http://192.168.2.131/ +15 connections +1 workers + + +┌─────────┬───────┬────────┬────────┬────────┬───────────┬─────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼────────┼────────┼────────┼───────────┼─────────┼─────────┤ +│ Latency │ 62 ms │ 103 ms │ 252 ms │ 297 ms │ 119.53 ms │ 58.1 ms │ 1050 ms │ +└─────────┴───────┴────────┴────────┴────────┴───────────┴─────────┴─────────┘ +┌───────────┬─────────┬────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 22 │ 41 │ 60 │ 70 │ 58.27 │ 8.6 │ 22 │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 95.5 kB │ 178 kB │ 260 kB │ 304 kB │ 253 kB │ 37.3 kB │ 95.4 kB │ +└───────────┴─────────┴────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3496 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.06s, 15.2 MB read +48 errors (48 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +15 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬──────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼──────────┼──────────┼────────┤ +│ Latency │ 49 ms │ 75 ms │ 151 ms │ 164 ms │ 82.32 ms │ 25.95 ms │ 313 ms │ +└─────────┴───────┴───────┴────────┴────────┴──────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 61 │ 66 │ 85 │ 99 │ 84.52 │ 8.42 │ 61 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 8.24 kB │ 8.91 kB │ 11.5 kB │ 13.4 kB │ 11.4 kB │ 1.14 kB │ 8.23 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 5071 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 685 kB read +48 errors (48 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +15 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 801 ms │ 1709 ms │ 3676 ms │ 3762 ms │ 1929.08 ms │ 744.64 ms │ 5846 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 3 │ 4 │ 5 │ 3.57 │ 0.59 │ 2 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 86.4 kB │ 115 kB │ 144 kB │ 103 kB │ 16.9 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 214 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +277 requests in 60.09s, 6.16 MB read +48 errors (48 timeouts) + + +---------------- + + + +CLIENTS: *** 20 *** + +Running 60s test @ http://192.168.2.131/ +20 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬───────────┬──────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼───────────┼──────────┼─────────┤ +│ Latency │ 60 ms │ 97 ms │ 232 ms │ 267 ms │ 112.02 ms │ 53.32 ms │ 1054 ms │ +└─────────┴───────┴───────┴────────┴────────┴───────────┴──────────┴─────────┘ +┌───────────┬─────────┬────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 21 │ 52 │ 63 │ 69 │ 62.12 │ 6.59 │ 21 │ +├───────────┼─────────┼────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 91.1 kB │ 226 kB │ 273 kB │ 300 kB │ 269 kB │ 28.6 kB │ 91.1 kB │ +└───────────┴─────────┴────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 3727 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +4k requests in 60.1s, 16.2 MB read +78 errors (78 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/api?foo=bar +20 connections +1 workers + + +┌─────────┬───────┬───────┬────────┬────────┬─────────┬──────────┬────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼───────┼───────┼────────┼────────┼─────────┼──────────┼────────┤ +│ Latency │ 49 ms │ 78 ms │ 164 ms │ 178 ms │ 87.8 ms │ 35.83 ms │ 658 ms │ +└─────────┴───────┴───────┴────────┴────────┴─────────┴──────────┴────────┘ +┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Req/Sec │ 35 │ 55 │ 81 │ 95 │ 79.27 │ 10.5 │ 35 │ +├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ +│ Bytes/Sec │ 4.73 kB │ 7.43 kB │ 10.9 kB │ 12.8 kB │ 10.7 kB │ 1.42 kB │ 4.72 kB │ +└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 4756 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +5k requests in 60.07s, 642 kB read +78 errors (78 timeouts) + + +---------------- + +Running 60s test @ http://192.168.2.131/alien.png +20 connections +1 workers + + +┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬───────────┬─────────┐ +│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │ +├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼───────────┼─────────┤ +│ Latency │ 806 ms │ 1613 ms │ 3348 ms │ 4009 ms │ 1854.07 ms │ 733.32 ms │ 6606 ms │ +└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴───────────┴─────────┘ +┌───────────┬─────────┬─────────┬────────┬────────┬────────┬─────────┬─────────┐ +│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Req/Sec │ 2 │ 3 │ 4 │ 5 │ 3.7 │ 0.62 │ 2 │ +├───────────┼─────────┼─────────┼────────┼────────┼────────┼─────────┼─────────┤ +│ Bytes/Sec │ 57.6 kB │ 86.4 kB │ 115 kB │ 144 kB │ 106 kB │ 17.7 kB │ 57.6 kB │ +└───────────┴─────────┴─────────┴────────┴────────┴────────┴─────────┴─────────┘ +┌──────┬───────┐ +│ Code │ Count │ +├──────┼───────┤ +│ 200 │ 222 │ +└──────┴───────┘ + +Req/Bytes counts sampled once per second. +# of samples: 60 + +320 requests in 60.05s, 6.39 MB read +78 errors (78 timeouts) + + +---------------- + diff --git a/lib/PsychicHttp/benchmark/results/psychic-v1.1-websocket-loadtest.log b/lib/PsychicHttp/benchmark/results/psychic-v1.1-websocket-loadtest.log new file mode 100644 index 0000000..8c507a9 --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/psychic-v1.1-websocket-loadtest.log @@ -0,0 +1,246 @@ + + +CLIENTS: *** 1 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 1 +Agent: none + +Completed requests: 1972 +Total errors: 0 +Total time: 60.003 s +Mean latency: 29.8 ms +Effective rps: 33 + +Percentage of requests served within a certain time + 50% 25 ms + 90% 40 ms + 95% 66 ms + 99% 96 ms + 100% 147 ms (longest request) + + +CLIENTS: *** 2 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 2 +Agent: none + +Completed requests: 3144 +Total errors: 0 +Total time: 60.003 s +Mean latency: 37.6 ms +Effective rps: 52 + +Percentage of requests served within a certain time + 50% 32 ms + 90% 58 ms + 95% 82 ms + 99% 114 ms + 100% 160 ms (longest request) + + +CLIENTS: *** 3 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 3 +Agent: none + +Completed requests: 4113 +Total errors: 0 +Total time: 60.005 s +Mean latency: 43.2 ms +Effective rps: 69 + +Percentage of requests served within a certain time + 50% 38 ms + 90% 63 ms + 95% 88 ms + 99% 119 ms + 100% 339 ms (longest request) + + +CLIENTS: *** 4 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 4 +Agent: none + +Completed requests: 4902 +Total errors: 0 +Total time: 60.004 s +Mean latency: 48.3 ms +Effective rps: 82 + +Percentage of requests served within a certain time + 50% 42 ms + 90% 74 ms + 95% 97 ms + 99% 125 ms + 100% 217 ms (longest request) + + +CLIENTS: *** 5 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 5 +Agent: none + +Completed requests: 5522 +Total errors: 0 +Total time: 60.003 s +Mean latency: 53.7 ms +Effective rps: 92 + +Percentage of requests served within a certain time + 50% 48 ms + 90% 81 ms + 95% 102 ms + 99% 122 ms + 100% 324 ms (longest request) + + +CLIENTS: *** 6 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 6 +Agent: none + +Completed requests: 5808 +Total errors: 0 +Total time: 60.004 s +Mean latency: 61.4 ms +Effective rps: 97 + +Percentage of requests served within a certain time + 50% 54 ms + 90% 94 ms + 95% 117 ms + 99% 142 ms + 100% 348 ms (longest request) + + +CLIENTS: *** 7 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 7 +Agent: none + +Completed requests: 6478 +Total errors: 0 +Total time: 60.006 s +Mean latency: 64.1 ms +Effective rps: 108 + +Percentage of requests served within a certain time + 50% 59 ms + 90% 94 ms + 95% 110 ms + 99% 137 ms + 100% 195 ms (longest request) + + +CLIENTS: *** 8 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 8 +Running on cores: 2 +Agent: none + +Completed requests: 6124 +Total errors: 0 +Total time: 60.004 s +Mean latency: 67.8 ms +Effective rps: 102 + +Percentage of requests served within a certain time + 50% 59 ms + 90% 107 ms + 95% 131 ms + 99% 173 ms + 100% 260 ms (longest request) + + +CLIENTS: *** 10 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 10 +Running on cores: 2 +Agent: none + +Completed requests: 5640 +Total errors: 0 +Total time: 60.004 s +Mean latency: 73.7 ms +Effective rps: 94 + +Percentage of requests served within a certain time + 50% 61 ms + 90% 120 ms + 95% 140 ms + 99% 240 ms + 100% 780 ms (longest request) + + +CLIENTS: *** 16 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 16 +Running on cores: 2 +Agent: none + +Completed requests: 5809 +Total errors: 0 +Total time: 60.006 s +Mean latency: 71.6 ms +Effective rps: 97 + +Percentage of requests served within a certain time + 50% 64 ms + 90% 111 ms + 95% 130 ms + 99% 162 ms + 100% 226 ms (longest request) + + +CLIENTS: *** 20 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 20 +Running on cores: 2 +Agent: none + +Completed requests: 5590 +Total errors: 0 +Total time: 60.003 s +Mean latency: 74.4 ms +Effective rps: 93 + +Percentage of requests served within a certain time + 50% 61 ms + 90% 122 ms + 95% 151 ms + 99% 247 ms + 100% 513 ms (longest request) diff --git a/lib/PsychicHttp/benchmark/results/psychic-websocket-loadtest.log b/lib/PsychicHttp/benchmark/results/psychic-websocket-loadtest.log new file mode 100644 index 0000000..812026c --- /dev/null +++ b/lib/PsychicHttp/benchmark/results/psychic-websocket-loadtest.log @@ -0,0 +1,246 @@ + + +CLIENTS: *** 1 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 1 +Agent: none + +Completed requests: 2304 +Total errors: 0 +Total time: 60.002 s +Mean latency: 25.5 ms +Effective rps: 38 + +Percentage of requests served within a certain time + 50% 22 ms + 90% 32 ms + 95% 58 ms + 99% 92 ms + 100% 105 ms (longest request) + + +CLIENTS: *** 2 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 2 +Agent: none + +Completed requests: 3647 +Total errors: 0 +Total time: 60.002 s +Mean latency: 32.3 ms +Effective rps: 61 + +Percentage of requests served within a certain time + 50% 28 ms + 90% 43 ms + 95% 67 ms + 99% 93 ms + 100% 135 ms (longest request) + + +CLIENTS: *** 3 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 3 +Agent: none + +Completed requests: 4629 +Total errors: 0 +Total time: 60.004 s +Mean latency: 38.3 ms +Effective rps: 77 + +Percentage of requests served within a certain time + 50% 34 ms + 90% 51 ms + 95% 79 ms + 99% 110 ms + 100% 152 ms (longest request) + + +CLIENTS: *** 4 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 4 +Agent: none + +Completed requests: 5290 +Total errors: 0 +Total time: 60.003 s +Mean latency: 44.7 ms +Effective rps: 88 + +Percentage of requests served within a certain time + 50% 40 ms + 90% 67 ms + 95% 92 ms + 99% 115 ms + 100% 159 ms (longest request) + + +CLIENTS: *** 5 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 5 +Agent: none + +Completed requests: 5935 +Total errors: 0 +Total time: 60.002 s +Mean latency: 50 ms +Effective rps: 99 + +Percentage of requests served within a certain time + 50% 45 ms + 90% 74 ms + 95% 97 ms + 99% 123 ms + 100% 172 ms (longest request) + + +CLIENTS: *** 6 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 6 +Agent: none + +Completed requests: 6533 +Total errors: 0 +Total time: 60.003 s +Mean latency: 54.5 ms +Effective rps: 109 + +Percentage of requests served within a certain time + 50% 49 ms + 90% 78 ms + 95% 101 ms + 99% 129 ms + 100% 170 ms (longest request) + + +CLIENTS: *** 7 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 7 +Agent: none + +Completed requests: 7086 +Total errors: 0 +Total time: 60.004 s +Mean latency: 58.6 ms +Effective rps: 118 + +Percentage of requests served within a certain time + 50% 54 ms + 90% 85 ms + 95% 107 ms + 99% 130 ms + 100% 184 ms (longest request) + + +CLIENTS: *** 8 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 8 +Running on cores: 2 +Agent: none + +Completed requests: 6994 +Total errors: 0 +Total time: 60.004 s +Mean latency: 59.3 ms +Effective rps: 117 + +Percentage of requests served within a certain time + 50% 54 ms + 90% 88 ms + 95% 109 ms + 99% 134 ms + 100% 176 ms (longest request) + + +CLIENTS: *** 10 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 10 +Running on cores: 2 +Agent: none + +Completed requests: 7197 +Total errors: 0 +Total time: 60.004 s +Mean latency: 57.7 ms +Effective rps: 120 + +Percentage of requests served within a certain time + 50% 53 ms + 90% 83 ms + 95% 98 ms + 99% 123 ms + 100% 176 ms (longest request) + + +CLIENTS: *** 16 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 16 +Running on cores: 2 +Agent: none + +Completed requests: 7173 +Total errors: 0 +Total time: 60.002 s +Mean latency: 57.9 ms +Effective rps: 120 + +Percentage of requests served within a certain time + 50% 53 ms + 90% 83 ms + 95% 100 ms + 99% 123 ms + 100% 156 ms (longest request) + + +CLIENTS: *** 20 *** + + +Target URL: ws://192.168.2.131/ws +Max time (s): 60 +Concurrent clients: 20 +Running on cores: 2 +Agent: none + +Completed requests: 6883 +Total errors: 0 +Total time: 60.002 s +Mean latency: 60.4 ms +Effective rps: 115 + +Percentage of requests served within a certain time + 50% 55 ms + 90% 92 ms + 95% 111 ms + 99% 138 ms + 100% 175 ms (longest request) diff --git a/lib/PsychicHttp/benchmark/websocket-client-test.js b/lib/PsychicHttp/benchmark/websocket-client-test.js new file mode 100644 index 0000000..3021bb0 --- /dev/null +++ b/lib/PsychicHttp/benchmark/websocket-client-test.js @@ -0,0 +1,36 @@ +#!/usr/bin/env node + +const WebSocket = require('ws'); + +const uri = 'ws://192.168.2.131/ws'; + +async function websocketClient() { + console.log(`Starting test`); + for (let i = 0; i < 1000000; i++) { + const ws = new WebSocket(uri); + + if (i % 100 == 0) + console.log(`Count: ${i}`); + + ws.on('open', () => { + //console.log(`Connected`); + }); + + ws.on('message', (message) => { + //console.log(`Message: ${message}`); + ws.close(); + }); + + ws.on('error', (error) => { + console.error(`Error: ${error.message}`); + }); + + await new Promise((resolve) => { + ws.on('close', () => { + resolve(); + }); + }); + } +} + +websocketClient(); \ No newline at end of file diff --git a/lib/AsyncTCP/component.mk b/lib/PsychicHttp/component.mk similarity index 100% rename from lib/AsyncTCP/component.mk rename to lib/PsychicHttp/component.mk diff --git a/lib/PsychicHttp/examples/arduino/.gitignore b/lib/PsychicHttp/examples/arduino/.gitignore new file mode 100644 index 0000000..9e5f911 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/lib/PsychicHttp/examples/arduino/arduino.ino b/lib/PsychicHttp/examples/arduino/arduino.ino new file mode 100644 index 0000000..c0fe060 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/arduino.ino @@ -0,0 +1,497 @@ +/* + PsychicHTTP Server Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +/********************************************************************************************** +* Note: this demo relies on the following libraries (Install via Library Manager) +* ArduinoJson UrlEncode +**********************************************************************************************/ + +/********************************************************************************************** +* Note: this demo relies on various files to be uploaded on the LittleFS partition +* Follow instructions here: https://randomnerdtutorials.com/esp32-littlefs-arduino-ide/ +**********************************************************************************************/ + +#include +#include +#include +#include +#include +#include "_secret.h" +#include +#include //uncomment this to enable HTTPS / SSL + +#ifndef WIFI_SSID + #error "You need to enter your wifi credentials. Rename secret.h to _secret.h and enter your credentials there." +#endif + +//Enter your WIFI credentials in secret.h +const char *ssid = WIFI_SSID; +const char *password = WIFI_PASS; + +// Set your SoftAP credentials +const char *softap_ssid = "PsychicHttp"; +const char *softap_password = ""; +IPAddress softap_ip(10, 0, 0, 1); + +//credentials for the /auth-basic and /auth-digest examples +const char *app_user = "admin"; +const char *app_pass = "admin"; +const char *app_name = "Your App"; + +//hostname for mdns (psychic.local) +const char *local_hostname = "psychic"; + +//#define PSY_ENABLE_SSL to enable ssl +#ifdef PSY_ENABLE_SSL + bool app_enable_ssl = true; + String server_cert; + String server_key; +#endif + +//our main server object +#ifdef PSY_ENABLE_SSL + PsychicHttpsServer server; +#else + PsychicHttpServer server; +#endif +PsychicWebSocketHandler websocketHandler; +PsychicEventSource eventSource; + +bool connectToWifi() +{ + //dual client and AP mode + WiFi.mode(WIFI_AP_STA); + + // Configure SoftAP + WiFi.softAPConfig(softap_ip, softap_ip, IPAddress(255, 255, 255, 0)); // subnet FF FF FF 00 + WiFi.softAP(softap_ssid, softap_password); + IPAddress myIP = WiFi.softAPIP(); + Serial.print("SoftAP IP Address: "); + Serial.println(myIP); + + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + // Auto reconnect is set true as default + // To set auto connect off, use the following function + // WiFi.setAutoReconnect(false); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + + // We start by connecting to a WiFi network + // To debug, please enable Core Debug Level to Verbose + if (connectToWifi()) + { + //set up our esp32 to listen on the local_hostname.local domain + if (!MDNS.begin(local_hostname)) { + Serial.println("Error starting mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + //look up our keys? + #ifdef PSY_ENABLE_SSL + if (app_enable_ssl) + { + File fp = LittleFS.open("/server.crt"); + if (fp) + { + server_cert = fp.readString(); + + // Serial.println("Server Cert:"); + // Serial.println(server_cert); + } + else + { + Serial.println("server.pem not found, SSL not available"); + app_enable_ssl = false; + } + fp.close(); + + File fp2 = LittleFS.open("/server.key"); + if (fp2) + { + server_key = fp2.readString(); + + // Serial.println("Server Key:"); + // Serial.println(server_key); + } + else + { + Serial.println("server.key not found, SSL not available"); + app_enable_ssl = false; + } + fp2.close(); + } + #endif + + //setup server config stuff here + server.config.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + + #ifdef PSY_ENABLE_SSL + server.ssl_config.httpd.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + + //do we want secure or not? + if (app_enable_ssl) + { + server.listen(443, server_cert.c_str(), server_key.c_str()); + + //this creates a 2nd server listening on port 80 and redirects all requests HTTPS + PsychicHttpServer *redirectServer = new PsychicHttpServer(); + redirectServer->config.ctrl_port = 20424; // just a random port different from the default one + redirectServer->listen(80); + redirectServer->onNotFound([](PsychicRequest *request) { + String url = "https://" + request->host() + request->url(); + return request->redirect(url.c_str()); + }); + } + else + server.listen(80); + #else + server.listen(80); + #endif + + //serve static files from LittleFS/www on / only to clients on same wifi network + //this is where our /index.html file lives + server.serveStatic("/", LittleFS, "/www/")->setFilter(ON_STA_FILTER); + + //serve static files from LittleFS/www-ap on / only to clients on SoftAP + //this is where our /index.html file lives + server.serveStatic("/", LittleFS, "/www-ap/")->setFilter(ON_AP_FILTER); + + //serve static files from LittleFS/img on /img + //it's more efficient to serve everything from a single www directory, but this is also possible. + server.serveStatic("/img", LittleFS, "/img/"); + + //you can also serve single files + server.serveStatic("/myfile.txt", LittleFS, "/custom.txt"); + + //example callback everytime a connection is opened + server.onOpen([](PsychicClient *client) { + Serial.printf("[http] connection #%u connected from %s\n", client->socket(), client->localIP().toString()); + }); + + //example callback everytime a connection is closed + server.onClose([](PsychicClient *client) { + Serial.printf("[http] connection #%u closed from %s\n", client->socket(), client->localIP().toString()); + }); + + //api - json message passed in as post body + server.on("/api", HTTP_POST, [](PsychicRequest *request) + { + //load our JSON request + StaticJsonDocument<1024> json; + String body = request->body(); + DeserializationError err = deserializeJson(json, body); + + //create our response json + StaticJsonDocument<128> output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (json.containsKey("foo")) + { + String foo = json["foo"]; + output["foo"] = foo; + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + return request->reply(200, "application/json", jsonBuffer.c_str()); + }); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/ip", HTTP_GET, [](PsychicRequest *request) + { + String output = "Your IP is: " + request->client()->remoteIP().toString(); + return request->reply(output.c_str()); + }); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/api", HTTP_GET, [](PsychicRequest *request) + { + //create a response object + StaticJsonDocument<128> output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + String foo = request->getParam("foo")->name(); + output["foo"] = foo; + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + return request->reply(200, "application/json", jsonBuffer.c_str()); + }); + + //how to redirect a request + server.on("/redirect", HTTP_GET, [](PsychicRequest *request) + { + return request->redirect("/alien.png"); + }); + + //how to do basic auth + server.on("/auth-basic", HTTP_GET, [](PsychicRequest *request) + { + if (!request->authenticate(app_user, app_pass)) + return request->requestAuthentication(BASIC_AUTH, app_name, "You must log in."); + return request->reply("Auth Basic Success!"); + }); + + //how to do digest auth + server.on("/auth-digest", HTTP_GET, [](PsychicRequest *request) + { + if (!request->authenticate(app_user, app_pass)) + return request->requestAuthentication(DIGEST_AUTH, app_name, "You must log in."); + return request->reply("Auth Digest Success!"); + }); + + //example of getting / setting cookies + server.on("/cookies", HTTP_GET, [](PsychicRequest *request) + { + PsychicResponse response(request); + + int counter = 0; + if (request->hasCookie("counter")) + { + counter = std::stoi(request->getCookie("counter").c_str()); + counter++; + } + + char cookie[10]; + sprintf(cookie, "%i", counter); + + response.setCookie("counter", cookie); + response.setContent(cookie); + return response.send(); + }); + + //example of getting POST variables + server.on("/post", HTTP_POST, [](PsychicRequest *request) + { + String output; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + }); + + //you can set up a custom 404 handler. + server.onNotFound([](PsychicRequest *request) + { + return request->reply(404, "text/html", "Custom 404 Handler"); + }); + + //handle a very basic upload as post body + PsychicUploadHandler *uploadHandler = new PsychicUploadHandler(); + uploadHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + Serial.printf("Writing %d/%d bytes to: %s\n", (int)index+(int)len, request->contentLength(), path.c_str()); + + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + uploadHandler->onRequest([](PsychicRequest *request) + { + String url = "/" + request->getFilename(); + String output = "" + url + ""; + + return request->reply(output.c_str()); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + server.on("/upload/*", HTTP_POST, uploadHandler); + + //a little bit more complicated multipart form + PsychicUploadHandler *multipartHandler = new PsychicUploadHandler(); + multipartHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + //some progress over serial. + Serial.printf("Writing %d bytes to: %s\n", (int)len, path.c_str()); + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + multipartHandler->onRequest([](PsychicRequest *request) + { + PsychicWebParameter *file = request->getParam("file_upload"); + + String url = "/" + file->value(); + String output; + + output += "" + url + "
\n"; + output += "Bytes: " + String(file->size()) + "
\n"; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + server.on("/multipart", HTTP_POST, multipartHandler); + + //a websocket echo server + websocketHandler.onOpen([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u connected from %s\n", client->socket(), client->localIP().toString()); + client->sendMessage("Hello!"); + }); + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { + Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char *)frame->payload); + return request->reply(frame); + }); + websocketHandler.onClose([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->localIP().toString()); + }); + server.on("/ws", &websocketHandler); + + //EventSource server + eventSource.onOpen([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u connected from %s\n", client->socket(), client->localIP().toString()); + client->send("Hello user!", NULL, millis(), 1000); + }); + eventSource.onClose([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u closed from %s\n", client->socket(), client->localIP().toString()); + }); + server.on("/events", &eventSource); + } +} + +unsigned long lastUpdate = 0; +char output[60]; + +void loop() +{ + if (millis() - lastUpdate > 2000) + { + sprintf(output, "Millis: %d\n", millis()); + websocketHandler.sendAll(output); + + sprintf(output, "%d", millis()); + eventSource.send(output, "millis", millis(), 0); + + lastUpdate = millis(); + } +} \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/arduino_captive_portal/README.md b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/README.md new file mode 100644 index 0000000..f965eda --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/README.md @@ -0,0 +1,60 @@ +**1) SUMMARY** + +This example implements a **captive portal** with library DNSServer, ie web page which opens automatically when user connects Wifi network (eg "PsychitHttp"). + +Captiveportal is implemented in **ESPAsyncWebServer** [https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/examples/CaptivePortal/CaptivePortal.ino](url) and in **arduino-esp32 examples** [https://github.com/espressif/arduino-esp32/blob/master/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino](url) + +This feature can be implemented with Psychichttp with a **dedicated handler**, as shown in code below. + +Code highlights are added below for reference. + +**2) CODE** + +**Definitions** +``` +// captiveportal +// credits https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/examples/CaptivePortal/CaptivePortal.ino +//https://github.com/espressif/arduino-esp32/blob/master/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino +#include +DNSServer dnsServer; +class CaptiveRequestHandler : public PsychicWebHandler { // handler +public: + CaptiveRequestHandler() {}; + virtual ~CaptiveRequestHandler() {}; + bool canHandle(PsychicRequest*request){ + // ... if needed some tests ... return(false); + return true; // activate captive portal + } + esp_err_t handleRequest(PsychicRequest *request) { + //PsychicFileResponse response(request, LittleFS, "/captiveportal.html"); // uncomment : for captive portal page, if any, eg "captiveportal.html" + //return response.send(); // uncomment : return captive portal page + return request->reply(200,"text/html","Welcome to captive portal !"); // simple text, comment if captive portal page + } +}; +CaptiveRequestHandler *captivehandler=NULL; // handler for captive portal +``` + +**setup()** +``` + // captive portal + dnsServer.start(53, "*", WiFi.softAPIP()); // DNS requests are executed over port 53 (standard) + captivehandler= new CaptiveRequestHandler(); // create captive portal handler, important : after server.on since handlers are triggered on a first created/first trigerred basis + server.addHandler(captivehandler); // captive portal handler (last handler) +``` + +**loop()** +``` + dnsServer.processNextRequest(); // captive portal +``` + +**3) RESULT** + +**Access Point (web page is opened automatically when connecting to PsychicHttp AP)** +![captive portal access point](images/accesspoint.png) + +**Station (web page is shown whatever url for Station IP, eg 192.168.1.50/abcdefg** +![captive portal station point](images/station.png) + + + + diff --git a/lib/PsychicHttp/examples/arduino/arduino_captive_portal/arduino_captive_portal.ino b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/arduino_captive_portal.ino new file mode 100644 index 0000000..fbe83a3 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/arduino_captive_portal.ino @@ -0,0 +1,144 @@ +/* + PsychicHTTP Server Captive Portal Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +#include +#include +#include +#include +#include + +char* TAG = "CAPTPORT"; + +// captiveportal +// credits https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/examples/CaptivePortal/CaptivePortal.ino +//https://github.com/espressif/arduino-esp32/blob/master/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino +#include +DNSServer dnsServer; +class CaptiveRequestHandler : public PsychicWebHandler { // handler +public: + CaptiveRequestHandler() {}; + virtual ~CaptiveRequestHandler() {}; + bool canHandle(PsychicRequest*request){ + // ... if needed some tests ... return(false); + return true; // activate captive portal + } + esp_err_t handleRequest(PsychicRequest *request) { + //PsychicFileResponse response(request, LittleFS, "/captiveportal.html"); // uncomment : for captive portal page, if any, eg "captiveportal.html" + //return response.send(); // uncomment : return captive portal page + return request->reply(200,"text/html","Welcome to captive portal !"); // simple text, comment if captive portal page + } +}; +CaptiveRequestHandler *captivehandler=NULL; // handler for captive portal + +const char* ssid = "mySSID"; // replace with your SSID (mode STATION) +const char* password = "myPassword"; // replace with you password (mode STATION) + +// Set your SoftAP credentials +const char *softap_ssid = "PsychicHttp"; +const char *softap_password = ""; +IPAddress softap_ip(10, 0, 0, 1); + +//hostname for mdns (psychic.local) +const char *local_hostname = "psychic"; + +//our main server object +PsychicHttpServer server; + +bool connectToWifi() { + //dual client and AP mode + WiFi.mode(WIFI_AP_STA); + + // Configure SoftAP + WiFi.softAPConfig(softap_ip, softap_ip, IPAddress(255, 255, 255, 0)); // subnet FF FF FF 00 + WiFi.softAP(softap_ssid, softap_password); + IPAddress myIP = WiFi.softAPIP(); + ESP_LOGI(TAG,"SoftAP IP Address: %s", myIP.toString().c_str()); + ESP_LOGI(TAG,"[WiFi] Connecting to %s", ssid); + + WiFi.begin(ssid, password); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) { + switch (WiFi.status()) { + case WL_NO_SSID_AVAIL: + ESP_LOGE(TAG,"[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + ESP_LOGI(TAG,"[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + ESP_LOGI(TAG,"[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + ESP_LOGI(TAG,"[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + ESP_LOGI(TAG,"[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + ESP_LOGI(TAG,"[WiFi] WiFi is connected, IP address %s",WiFi.localIP().toString().c_str()); + return true; + break; + default: + ESP_LOGI(TAG,"[WiFi] WiFi Status: %d",WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) { + ESP_LOGI(TAG,"[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else numberOfTries--; + } + + return false; +} // end connectToWifi + +void setup() { + Serial.begin(115200); + delay(10); + + // Wifi + if (connectToWifi()) { // set up our esp32 to listen on the local_hostname.local domain + if (!MDNS.begin(local_hostname)) { + ESP_LOGE(TAG,"Error starting mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + + if(!LittleFS.begin()) { + ESP_LOGI(TAG,"ERROR : LittleFS Mount Failed."); + return; + } + + //setup server config stuff here + server.config.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + server.listen(80); + + DefaultHeaders::Instance().addHeader("Server", "PsychicHttp"); + + // captive portal + dnsServer.start(53, "*", WiFi.softAPIP()); // DNS requests are executed over port 53 (standard) + captivehandler= new CaptiveRequestHandler(); // create captive portal handler, important : after server.on since handlers are triggered on a first created/first trigerred basis + server.addHandler(captivehandler); // captive portal handler (last handler) + } // end set up our esp32 to listen on the local_hostname.local domain +} // end setup + +void loop() { + dnsServer.processNextRequest(); // captive portal +} diff --git a/lib/PsychicHttp/examples/arduino/arduino_captive_portal/images/accesspoint.png b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/images/accesspoint.png new file mode 100644 index 0000000..76c3590 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/images/accesspoint.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_captive_portal/images/station.png b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/images/station.png new file mode 100644 index 0000000..525a530 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_captive_portal/images/station.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/README.md b/lib/PsychicHttp/examples/arduino/arduino_ota/README.md new file mode 100644 index 0000000..d5f8183 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/arduino_ota/README.md @@ -0,0 +1,138 @@ +**OTA update example for PsychicHttp** + +Example of OTA (Over The Air) update implementation for PsychicHttp, using Arduino IDE. + +**Requirements** +Requirements for project are : +- OTA update for code (firmware) +- OTA update for data (littlefs) +- manual restart of ESP32, triggered by User (no automatic restart after code or data file upload) + +**Implementation** + +OTA update relies on handler PsychicUploadHandler. + +Screenshots and Code are shown below. + +**Credits** + +https://github.com/hoeken/PsychicHttp/blob/master/src/PsychicUploadHandler.cpp + +https://github.com/hoeken/PsychicHttp/issues/30 + +**Configuration** + +Example has been implemented with following configuration :\ +Arduino IDE 1.8.19\ +arduino-32 v2.0.15\ +PsychicHttp 1.1.1\ +ESP32S3 + +**Example Files Structure** + +``` +arduino_ota + data + | update.html + arduino_ota.ino + code.bin + littlefs.bin + README +``` +"code.bin" and "littlefs.bin" are example update files which can be used to update respectily code (firmware) or data (littlefs). + +"Real" update files can be generated on Arduino IDE 1.x : +- for code, menu "Sketch -> Export bin" +- for data, using plugin arduino-esp32fs-plugin https://github.com/lorol/arduino-esp32fs-plugin/releases + +**SCREENSHOTS** + +**Update code (firmware)** +![otaupdate1](images/otaupdate1.png) + +![otaupdate2](images/otaupdate2.png)\ +```ESP-ROM:esp32s3-20210327 +Build:Mar 27 2021 +rst:0x1 (POWERON),boot:0x2b (SPI_FAST_FLASH_BOOT) +SPIWP:0xee +mode:DIO, clock div:1 +load:0x3fce3808,len:0x4bc +load:0x403c9700,len:0xbd8 +load:0x403cc700,len:0x2a0c +entry 0x403c98d0 +[332885][I][PsychicHttpServer.cpp:236] openCallback(): [psychic] New client connected 51 +[332895][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 867306 +[332908][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 862016 +[332919][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[332929][I][arduino_ota.ino:133] operator()(): [OTA] update begin, filename code.bin +[333082][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 856272 +[333095][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[snip] +[339557][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 416 +[339566][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 1 +[339718][I][arduino_ota.ino:165] operator()(): [OTA] Update Success: 867072 written +[339726][I][arduino_ota.ino:184] operator()(): [OTA] Update code or data OK Update.errorString() No Error +[339738][I][PsychicHttpServer.cpp:236] openCallback(): [psychic] New client connected 52 +[339747][I][PsychicHttpServer.cpp:262] closeCallback(): [psychic] Client disconnected 52 + +``` + + +**Update data (littlefs)** + +![otaupdate3](images/otaupdate3.png) +``` +[ 48216][I][PsychicHttpServer.cpp:236] openCallback(): [psychic] New client connected 51 +[ 48226][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 1573100 +[ 48239][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 1567810 +[ 48250][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[ 48261][I][arduino_ota.ino:133] operator()(): [OTA] update begin, filename littlefs.bin +[ 48376][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 1562066 +[ 48389][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[ 48408][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 1556322 +[ 48421][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 1550578 +[ 48432][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[snip] +[ 54317][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 16930 +[ 54327][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[ 54340][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 11186 +[ 54351][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[ 54363][I][PsychicUploadHandler.cpp:164] _multipartUploadHandler(): [psychic] Remaining size : 5442 +[ 54375][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 0 +[ 54386][I][arduino_ota.ino:128] operator()(): [OTA] updateHandler->onUpload _error 0 Update.hasError() 0 last 1 +[ 54396][I][arduino_ota.ino:165] operator()(): [OTA] Update Success: 1572864 written +[ 54404][I][arduino_ota.ino:184] operator()(): [OTA] Update code or data OK Update.errorString() No Error +[ 54415][I][PsychicHttpServer.cpp:236] openCallback(): [psychic] New client connected 52 +[ 54424][I][PsychicHttpServer.cpp:262] closeCallback(): [psychic] Client disconnected 52 + +``` + +**Restart** + +![otaupdate4](images/otaupdate4.png) + +![otaupdate5](images/otaupdate5.png) + +``` +[110318][I][PsychicHttpServer.cpp:236] openCallback(): [psychic] New client connected 51 +[110327][I][arduino_ota.ino:205] operator()(): [OTA] Restarting ... +[110338][I][PsychicHttpServer.cpp:236] openCallback(): [psychic] New client connected 52 +[111317][W][WiFiGeneric.cpp:1062] _eventCallback(): Reason: 8 - ASSOC_LEAVE +[111319][I][PsychicHttpServer.cpp:262] closeCallback(): [psychic] Client disconnected 51 +[111332][I][PsychicHttpServer.cpp:262] closeCallback(): [psychic] Client disconnected 52 +ESP-ROM:esp32s3-20210327 +Build:Mar 27 2021 +rst:0xc (RTC_SW_CPU_RST),boot:0x8 (SPI_FAST_FLASH_BOOT) +Saved PC:0x420984ae +SPIWP:0xee +mode:DIO, clock div:1 +load:0x3fce3808,len:0x4bc +load:0x403c9700,len:0xbd8 +load:0x403cc700,len:0x2a0c +entry 0x403c98d0 +[ 283][I][arduino_ota.ino:57] connectToWifi(): [OTA] [WiFi] WiFi is disconnected +[ 791][I][arduino_ota.ino:60] connectToWifi(): [OTA] [WiFi] WiFi is connected, IP address 192.168.1.50 + +``` + + diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/arduino_ota.ino b/lib/PsychicHttp/examples/arduino/arduino_ota/arduino_ota.ino new file mode 100644 index 0000000..47f611f --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/arduino_ota/arduino_ota.ino @@ -0,0 +1,219 @@ +/* + Over The Air (OTA) update example for PsychicHttp web server + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. + +*/ +char *TAG = "OTA"; // ESP_LOG tag + +// PsychicHttp +#include +#include +#include +#include +#include +PsychicHttpServer server; // main server object +const char *local_hostname = "psychichttp"; // hostname for mdns + +// OTA +#include +bool esprestart=false; // true if/when ESP should be restarted, after OTA update + +// Wifi +const char *ssid = "SSID"; // your SSID +const char *password = "PASSWORD"; // your PASSWORD + +bool connectToWifi() { // Wifi + //client in STA mode + WiFi.mode(WIFI_AP_STA); + WiFi.begin(ssid,password); + + WiFi.begin(ssid, password); + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) { + switch (WiFi.status()) { + case WL_NO_SSID_AVAIL: + ESP_LOGE(TAG,"[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + ESP_LOGI(TAG,"[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + ESP_LOGI(TAG,"[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + ESP_LOGI(TAG,"[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + ESP_LOGI(TAG,"[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + ESP_LOGI(TAG,"[WiFi] WiFi is connected, IP address %s",WiFi.localIP().toString().c_str()); + return true; + break; + default: + ESP_LOGI(TAG,"[WiFi] WiFi Status: %d",WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) { + ESP_LOGI(TAG,"[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else numberOfTries--; + } + return false; +} + + +// ======================================================================= +// setup +// ======================================================================= +void setup() +{ Serial.begin(115200); + delay(10); + + // Wifi + if (connectToWifi()) { //set up our esp32 to listen on the local_hostname.local domain + if (!MDNS.begin(local_hostname)) { + ESP_LOGE(TAG,"Error starting mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + + if(!LittleFS.begin()) { + ESP_LOGI(TAG,"ERROR : LittleFS Mount Failed."); + return; + } + + //setup server config stuff here + server.config.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + server.listen(80); + + DefaultHeaders::Instance().addHeader("Server", "PsychicHttp"); + + //server.maxRequestBodySize=2*1024*1024; // 2Mb, change default value if needed + //server.maxUploadSize=64*1024*1024; // 64Mb, change default value if needed + + //you can set up a custom 404 handler. + // curl -i http://psychic.local/404 + server.onNotFound([](PsychicRequest *request) { + return request->reply(404, "text/html", "Custom 404 Handler"); + }); + + // OTA + PsychicUploadHandler *updateHandler = new PsychicUploadHandler(); // create handler for OTA update + updateHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { // onUpload + /* callback to upload code (firmware) or data (littlefs) + * callback is triggered for each file chunk, from first chunk (index is 0) to last chunk (last is true) + * callback is triggered by handler in handleRequest(), after _multipartUploadHandler() * + * filename : name of file to upload, with naming convention below + * "*code.bin" for code (firmware) update, eg "v1_code.bin" + * "*littlefs.bin" for data (little fs) update, eg "v1_littlefs.bin" * + */ + + int command; //command : firmware and filesystem update type, ie code (U_FLASH 0) or data (U_SPIFFS 100) + ESP_LOGI(TAG,"updateHandler->onUpload _error %d Update.hasError() %d last %d", Update.getError(), Update.hasError(), last); + + // Update.abort() replaces 1st error (eg "UPDATE_ERROR_ERASE") with abort error ("UPDATE_ERROR_ABORT") so root cause is lost + if (!Update.hasError()) { // no error encountered so far during update, process current chunk + if (!index){ // index is 0, begin update (first chunk) + ESP_LOGI(TAG,"update begin, filename %s", filename.c_str()); + Update.clearError(); // first chunk, clear Update error if any + // check if update file is code, data or sd card one + if (!filename.endsWith("code.bin") && !filename.endsWith("littlefs.bin")) { // incorrect file name + ESP_LOGE(TAG,"ERROR : filename %s format is incorrect", filename.c_str()); + if (!Update.hasError()) Update.abort(); + return(ESP_FAIL); + } // end incorrect file name + else { // file name is correct + // check update type : code or data + if (filename.endsWith("code.bin")) command=U_FLASH; // update code + else command=U_SPIFFS; // update data + if (!Update.begin(UPDATE_SIZE_UNKNOWN, command)) { // start update with max available size + // error, begin is KO + if (!Update.hasError()) Update.abort(); // abort + ESP_LOGE(TAG,"ERROR : update.begin error Update.errorString() %s",Update.errorString()); + return(ESP_FAIL); + } + } // end file name is correct + } // end begin update + + if ((len) && (!Update.hasError())) { // ongoing update if no error encountered + if (Update.write(data, len) != len) { + // error, write is KO + if (!Update.hasError()) Update.abort(); + ESP_LOGE(TAG,"ERROR : update.write len %d Update.errorString() %s",len, Update.errorString()) ; + return(ESP_FAIL); + } + } // end ongoing update + + if ((last) && (!Update.hasError())) { // last update if no error encountered + if (Update.end(true)) { // update end is OKTEST + ESP_LOGI(TAG, "Update Success: %u written", index+len); + } + else { // update end is KO + if (!Update.hasError()) Update.abort(); // abort + ESP_LOGE(TAG,"ERROR : update end error Update.errorString() %s", Update.errorString()); + return(ESP_FAIL); + } + } // last update if no error encountered + return(ESP_OK); + } // end no error encountered so far during update, process current chunk + else { // error encountered so far during update + return(ESP_FAIL); + } + }); // end onUpload + + updateHandler->onRequest([](PsychicRequest *request) { // triggered when update is completed (either OK or KO) and returns request's response (important) + String result; // request result + // code below is executed when update is finished + if (!Update.hasError()) { // update is OK + ESP_LOGI(TAG,"Update code or data OK Update.errorString() %s", Update.errorString()); + result = "Update done for file."; + return request->reply(200,"text/html",result.c_str()); + // ESP.restart(); // restart ESP if needed + } // end update is OK + else { // update is KO, send request with pretty print error + result = " Update.errorString() " + String(Update.errorString()); + ESP_LOGE(TAG,"ERROR : error %s",result.c_str()); + return request->reply(500, "text/html", result.c_str()); + } // end update is KO + }); + + server.on("/update", HTTP_GET, [](PsychicRequest*request){ + PsychicFileResponse response(request, LittleFS, "/update.html"); + return response.send(); + }); + + server.on("/update", HTTP_POST, updateHandler); + + server.on("/restart", HTTP_POST, [](PsychicRequest *request) { + String output = "Restarting ..."; + ESP_LOGI(TAG,"%s",output.c_str()); + esprestart=true; + return request->reply(output.c_str()); + }); + } // end onRequest + +} // end setup + +// ======================================================================= +// loop +// ======================================================================= +void loop() { + delay(2000); + if (esprestart) ESP.restart(); // restart ESP +} // end loop diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/code.bin b/lib/PsychicHttp/examples/arduino/arduino_ota/code.bin new file mode 100644 index 0000000..f9842f4 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/code.bin differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/data/update.html b/lib/PsychicHttp/examples/arduino/arduino_ota/data/update.html new file mode 100644 index 0000000..aedd817 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/arduino_ota/data/update.html @@ -0,0 +1,166 @@ + + + PSYCHICHTTP + + + + + + + + + +
+

PsychicHttp OTA Update

+
+ +

This page allows to test OTA update with PsychicHttp, and file naming convention below : +

    +
  • "*code.bin" for code (firmware) update, eg "v1_code.bin"
  • +
  • "*littlefs.bin" for data (littlefs) update, eg "v1_littlefs.bin"
  • +
+
+ +
+
+ +
+
+ +
+

Update must be done for each of the files provided (code, littlefs). Once updates are made, the ESP32 can be restarted. + +

+
+ + + + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate1.png b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate1.png new file mode 100644 index 0000000..c47e4e9 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate1.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate2.png b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate2.png new file mode 100644 index 0000000..c6be666 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate2.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate3.png b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate3.png new file mode 100644 index 0000000..ecefade Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate3.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate4.png b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate4.png new file mode 100644 index 0000000..3c86f1c Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate4.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate5.png b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate5.png new file mode 100644 index 0000000..dc87798 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/images/otaupdate5.png differ diff --git a/lib/PsychicHttp/examples/arduino/arduino_ota/littlefs.bin b/lib/PsychicHttp/examples/arduino/arduino_ota/littlefs.bin new file mode 100644 index 0000000..403ad59 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/arduino_ota/littlefs.bin differ diff --git a/lib/PsychicHttp/examples/arduino/data/custom.txt b/lib/PsychicHttp/examples/arduino/data/custom.txt new file mode 100644 index 0000000..d3db23d --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/data/custom.txt @@ -0,0 +1 @@ +Custom text file. \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/data/img/request_flow.png b/lib/PsychicHttp/examples/arduino/data/img/request_flow.png new file mode 100644 index 0000000..1005a38 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/data/img/request_flow.png differ diff --git a/lib/PsychicHttp/examples/arduino/data/server.crt b/lib/PsychicHttp/examples/arduino/data/server.crt new file mode 100644 index 0000000..34a1e01 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/data/server.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDKzCCAhOgAwIBAgIUBxM3WJf2bP12kAfqhmhhjZWv0ukwDQYJKoZIhvcNAQEL +BQAwJTEjMCEGA1UEAwwaRVNQMzIgSFRUUFMgc2VydmVyIGV4YW1wbGUwHhcNMTgx +MDE3MTEzMjU3WhcNMjgxMDE0MTEzMjU3WjAlMSMwIQYDVQQDDBpFU1AzMiBIVFRQ +UyBzZXJ2ZXIgZXhhbXBsZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALBint6nP77RCQcmKgwPtTsGK0uClxg+LwKJ3WXuye3oqnnjqJCwMEneXzGdG09T +sA0SyNPwrEgebLCH80an3gWU4pHDdqGHfJQa2jBL290e/5L5MB+6PTs2NKcojK/k +qcZkn58MWXhDW1NpAnJtjVniK2Ksvr/YIYSbyD+JiEs0MGxEx+kOl9d7hRHJaIzd +GF/vO2pl295v1qXekAlkgNMtYIVAjUy9CMpqaQBCQRL+BmPSJRkXBsYk8GPnieS4 +sUsp53DsNvCCtWDT6fd9D1v+BB6nDk/FCPKhtjYOwOAZlX4wWNSZpRNr5dfrxKsb +jAn4PCuR2akdF4G8WLUeDWECAwEAAaNTMFEwHQYDVR0OBBYEFMnmdJKOEepXrHI/ +ivM6mVqJgAX8MB8GA1UdIwQYMBaAFMnmdJKOEepXrHI/ivM6mVqJgAX8MA8GA1Ud +EwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBADiXIGEkSsN0SLSfCF1VNWO3 +emBurfOcDq4EGEaxRKAU0814VEmU87btIDx80+z5Dbf+GGHCPrY7odIkxGNn0DJY +W1WcF+DOcbiWoUN6DTkAML0SMnp8aGj9ffx3x+qoggT+vGdWVVA4pgwqZT7Ybntx +bkzcNFW0sqmCv4IN1t4w6L0A87ZwsNwVpre/j6uyBw7s8YoJHDLRFT6g7qgn0tcN +ZufhNISvgWCVJQy/SZjNBHSpnIdCUSJAeTY2mkM4sGxY0Widk8LnjydxZUSxC3Nl +hb6pnMh3jRq4h0+5CZielA4/a+TdrNPv/qok67ot/XJdY3qHCCd8O2b14OVq9jo= +-----END CERTIFICATE----- \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/data/server.key b/lib/PsychicHttp/examples/arduino/data/server.key new file mode 100644 index 0000000..a591325 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/data/server.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwYp7epz++0QkH +JioMD7U7BitLgpcYPi8Cid1l7snt6Kp546iQsDBJ3l8xnRtPU7ANEsjT8KxIHmyw +h/NGp94FlOKRw3ahh3yUGtowS9vdHv+S+TAfuj07NjSnKIyv5KnGZJ+fDFl4Q1tT +aQJybY1Z4itirL6/2CGEm8g/iYhLNDBsRMfpDpfXe4URyWiM3Rhf7ztqZdveb9al +3pAJZIDTLWCFQI1MvQjKamkAQkES/gZj0iUZFwbGJPBj54nkuLFLKedw7DbwgrVg +0+n3fQ9b/gQepw5PxQjyobY2DsDgGZV+MFjUmaUTa+XX68SrG4wJ+DwrkdmpHReB +vFi1Hg1hAgMBAAECggEAaTCnZkl/7qBjLexIryC/CBBJyaJ70W1kQ7NMYfniWwui +f0aRxJgOdD81rjTvkINsPp+xPRQO6oOadjzdjImYEuQTqrJTEUnntbu924eh+2D9 +Mf2CAanj0mglRnscS9mmljZ0KzoGMX6Z/EhnuS40WiJTlWlH6MlQU/FDnwC6U34y +JKy6/jGryfsx+kGU/NRvKSru6JYJWt5v7sOrymHWD62IT59h3blOiP8GMtYKeQlX +49om9Mo1VTIFASY3lrxmexbY+6FG8YO+tfIe0tTAiGrkb9Pz6tYbaj9FjEWOv4Vc ++3VMBUVdGJjgqvE8fx+/+mHo4Rg69BUPfPSrpEg7sQKBgQDlL85G04VZgrNZgOx6 +pTlCCl/NkfNb1OYa0BELqWINoWaWQHnm6lX8YjrUjwRpBF5s7mFhguFjUjp/NW6D +0EEg5BmO0ePJ3dLKSeOA7gMo7y7kAcD/YGToqAaGljkBI+IAWK5Su5yldrECTQKG +YnMKyQ1MWUfCYEwHtPvFvE5aPwKBgQDFBWXekpxHIvt/B41Cl/TftAzE7/f58JjV +MFo/JCh9TDcH6N5TMTRS1/iQrv5M6kJSSrHnq8pqDXOwfHLwxetpk9tr937VRzoL +CuG1Ar7c1AO6ujNnAEmUVC2DppL/ck5mRPWK/kgLwZSaNcZf8sydRgphsW1ogJin +7g0nGbFwXwKBgQCPoZY07Pr1TeP4g8OwWTu5F6dSvdU2CAbtZthH5q98u1n/cAj1 +noak1Srpa3foGMTUn9CHu+5kwHPIpUPNeAZZBpq91uxa5pnkDMp3UrLIRJ2uZyr8 +4PxcknEEh8DR5hsM/IbDcrCJQglM19ZtQeW3LKkY4BsIxjDf45ymH407IQKBgE/g +Ul6cPfOxQRlNLH4VMVgInSyyxWx1mODFy7DRrgCuh5kTVh+QUVBM8x9lcwAn8V9/ +nQT55wR8E603pznqY/jX0xvAqZE6YVPcw4kpZcwNwL1RhEl8GliikBlRzUL3SsW3 +q30AfqEViHPE3XpE66PPo6Hb1ymJCVr77iUuC3wtAoGBAIBrOGunv1qZMfqmwAY2 +lxlzRgxgSiaev0lTNxDzZkmU/u3dgdTwJ5DDANqPwJc6b8SGYTp9rQ0mbgVHnhIB +jcJQBQkTfq6Z0H6OoTVi7dPs3ibQJFrtkoyvYAbyk36quBmNRjVh6rc8468bhXYr +v/t+MeGJP/0Zw8v/X2CFll96 +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/data/www-ap/index.html b/lib/PsychicHttp/examples/arduino/data/www-ap/index.html new file mode 100644 index 0000000..73df596 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/data/www-ap/index.html @@ -0,0 +1,15 @@ + + + + + + PsychicHTTP SoftAP Demo + + + +
+

SoftAP Demo

+

You are connected to the ESP in SoftAP mode.

+
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/data/www/alien.png b/lib/PsychicHttp/examples/arduino/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/data/www/alien.png differ diff --git a/lib/PsychicHttp/examples/arduino/data/www/favicon.ico b/lib/PsychicHttp/examples/arduino/data/www/favicon.ico new file mode 100644 index 0000000..bdf785c Binary files /dev/null and b/lib/PsychicHttp/examples/arduino/data/www/favicon.ico differ diff --git a/lib/PsychicHttp/examples/arduino/data/www/index.html b/lib/PsychicHttp/examples/arduino/data/www/index.html new file mode 100644 index 0000000..4ee2491 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/data/www/index.html @@ -0,0 +1,236 @@ + + + + + + PsychicHTTP Demo + + + +
+

Basic Request Examples

+ + +

Static Serving

+

+ + +

+

Text File

+ +

Simple POST Form

+
+ + +
+ + +
+ +
+ +

Basic File Upload

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

Multipart POST Form

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

Websocket Demo

+ + + +
+ +
+ + + +

EventSource Demo

+ +
+ +
+ + +
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/arduino/data/www/text.txt b/lib/PsychicHttp/examples/arduino/data/www/text.txt new file mode 100644 index 0000000..5375816 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/data/www/text.txt @@ -0,0 +1 @@ +Test File. diff --git a/lib/PsychicHttp/examples/arduino/secret.h b/lib/PsychicHttp/examples/arduino/secret.h new file mode 100644 index 0000000..6d4bb15 --- /dev/null +++ b/lib/PsychicHttp/examples/arduino/secret.h @@ -0,0 +1,2 @@ +#define WIFI_SSID "Your_SSID" +#define WIFI_PASS "Your_PASS" \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/.gitignore b/lib/PsychicHttp/examples/esp-idf/.gitignore new file mode 100644 index 0000000..3413246 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/.gitignore @@ -0,0 +1,4 @@ +build/ +sdkconfig +sdkconfig.old +components/ diff --git a/lib/PsychicHttp/examples/esp-idf/CMakeLists.txt b/lib/PsychicHttp/examples/esp-idf/CMakeLists.txt new file mode 100644 index 0000000..634d58e --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/CMakeLists.txt @@ -0,0 +1,19 @@ +# The following lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.5) +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +if(DEFINED ENV{HTTP_PATH}) + set(HTTP_PATH $ENV{HTTP_PATH}) +else() + #these both work + set(HTTP_PATH "../../") + #set(HTTP_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../) + + #this does not work for me... + #set(HTTP_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../PsychicHttp) +endif(DEFINED ENV{HTTP_PATH}) + +set(EXTRA_COMPONENT_DIRS ${HTTP_PATH}) + +project(PsychicHttp_IDF) \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/README.md b/lib/PsychicHttp/examples/esp-idf/README.md new file mode 100644 index 0000000..ef91f3c --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/README.md @@ -0,0 +1,7 @@ +# PsychicHttp - ESP IDF Example +* Download and install [ESP IDF 4.4.7](https://github.com/espressif/esp-idf/releases/tag/v4.4.7) (or later version) +* Clone the project: ```git clone --recursive git@github.com:hoeken/PsychicHttp.git``` +* Run build command: ```cd PsychicHttp/examples/esp-idf``` and then ```idf.py build``` +* Flash the LittleFS filesystem: ```esptool.py write_flash --flash_mode dio --flash_freq 40m --flash_size 4MB 0x317000 build/littlefs.bin``` +* Flash the app firmware: ```idf.py flash monitor``` and visit the IP address shown in the console with a web browser. +* Learn more about [Arduino as ESP-IDF Component](https://docs.espressif.com/projects/arduino-esp32/en/latest/esp-idf_component.html) diff --git a/lib/PsychicHttp/examples/esp-idf/data/custom.txt b/lib/PsychicHttp/examples/esp-idf/data/custom.txt new file mode 100644 index 0000000..d3db23d --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/data/custom.txt @@ -0,0 +1 @@ +Custom text file. \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/data/img/request_flow.png b/lib/PsychicHttp/examples/esp-idf/data/img/request_flow.png new file mode 100644 index 0000000..1005a38 Binary files /dev/null and b/lib/PsychicHttp/examples/esp-idf/data/img/request_flow.png differ diff --git a/lib/PsychicHttp/examples/esp-idf/data/server.crt b/lib/PsychicHttp/examples/esp-idf/data/server.crt new file mode 100644 index 0000000..34a1e01 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/data/server.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDKzCCAhOgAwIBAgIUBxM3WJf2bP12kAfqhmhhjZWv0ukwDQYJKoZIhvcNAQEL +BQAwJTEjMCEGA1UEAwwaRVNQMzIgSFRUUFMgc2VydmVyIGV4YW1wbGUwHhcNMTgx +MDE3MTEzMjU3WhcNMjgxMDE0MTEzMjU3WjAlMSMwIQYDVQQDDBpFU1AzMiBIVFRQ +UyBzZXJ2ZXIgZXhhbXBsZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALBint6nP77RCQcmKgwPtTsGK0uClxg+LwKJ3WXuye3oqnnjqJCwMEneXzGdG09T +sA0SyNPwrEgebLCH80an3gWU4pHDdqGHfJQa2jBL290e/5L5MB+6PTs2NKcojK/k +qcZkn58MWXhDW1NpAnJtjVniK2Ksvr/YIYSbyD+JiEs0MGxEx+kOl9d7hRHJaIzd +GF/vO2pl295v1qXekAlkgNMtYIVAjUy9CMpqaQBCQRL+BmPSJRkXBsYk8GPnieS4 +sUsp53DsNvCCtWDT6fd9D1v+BB6nDk/FCPKhtjYOwOAZlX4wWNSZpRNr5dfrxKsb +jAn4PCuR2akdF4G8WLUeDWECAwEAAaNTMFEwHQYDVR0OBBYEFMnmdJKOEepXrHI/ +ivM6mVqJgAX8MB8GA1UdIwQYMBaAFMnmdJKOEepXrHI/ivM6mVqJgAX8MA8GA1Ud +EwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBADiXIGEkSsN0SLSfCF1VNWO3 +emBurfOcDq4EGEaxRKAU0814VEmU87btIDx80+z5Dbf+GGHCPrY7odIkxGNn0DJY +W1WcF+DOcbiWoUN6DTkAML0SMnp8aGj9ffx3x+qoggT+vGdWVVA4pgwqZT7Ybntx +bkzcNFW0sqmCv4IN1t4w6L0A87ZwsNwVpre/j6uyBw7s8YoJHDLRFT6g7qgn0tcN +ZufhNISvgWCVJQy/SZjNBHSpnIdCUSJAeTY2mkM4sGxY0Widk8LnjydxZUSxC3Nl +hb6pnMh3jRq4h0+5CZielA4/a+TdrNPv/qok67ot/XJdY3qHCCd8O2b14OVq9jo= +-----END CERTIFICATE----- \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/data/server.key b/lib/PsychicHttp/examples/esp-idf/data/server.key new file mode 100644 index 0000000..a591325 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/data/server.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwYp7epz++0QkH +JioMD7U7BitLgpcYPi8Cid1l7snt6Kp546iQsDBJ3l8xnRtPU7ANEsjT8KxIHmyw +h/NGp94FlOKRw3ahh3yUGtowS9vdHv+S+TAfuj07NjSnKIyv5KnGZJ+fDFl4Q1tT +aQJybY1Z4itirL6/2CGEm8g/iYhLNDBsRMfpDpfXe4URyWiM3Rhf7ztqZdveb9al +3pAJZIDTLWCFQI1MvQjKamkAQkES/gZj0iUZFwbGJPBj54nkuLFLKedw7DbwgrVg +0+n3fQ9b/gQepw5PxQjyobY2DsDgGZV+MFjUmaUTa+XX68SrG4wJ+DwrkdmpHReB +vFi1Hg1hAgMBAAECggEAaTCnZkl/7qBjLexIryC/CBBJyaJ70W1kQ7NMYfniWwui +f0aRxJgOdD81rjTvkINsPp+xPRQO6oOadjzdjImYEuQTqrJTEUnntbu924eh+2D9 +Mf2CAanj0mglRnscS9mmljZ0KzoGMX6Z/EhnuS40WiJTlWlH6MlQU/FDnwC6U34y +JKy6/jGryfsx+kGU/NRvKSru6JYJWt5v7sOrymHWD62IT59h3blOiP8GMtYKeQlX +49om9Mo1VTIFASY3lrxmexbY+6FG8YO+tfIe0tTAiGrkb9Pz6tYbaj9FjEWOv4Vc ++3VMBUVdGJjgqvE8fx+/+mHo4Rg69BUPfPSrpEg7sQKBgQDlL85G04VZgrNZgOx6 +pTlCCl/NkfNb1OYa0BELqWINoWaWQHnm6lX8YjrUjwRpBF5s7mFhguFjUjp/NW6D +0EEg5BmO0ePJ3dLKSeOA7gMo7y7kAcD/YGToqAaGljkBI+IAWK5Su5yldrECTQKG +YnMKyQ1MWUfCYEwHtPvFvE5aPwKBgQDFBWXekpxHIvt/B41Cl/TftAzE7/f58JjV +MFo/JCh9TDcH6N5TMTRS1/iQrv5M6kJSSrHnq8pqDXOwfHLwxetpk9tr937VRzoL +CuG1Ar7c1AO6ujNnAEmUVC2DppL/ck5mRPWK/kgLwZSaNcZf8sydRgphsW1ogJin +7g0nGbFwXwKBgQCPoZY07Pr1TeP4g8OwWTu5F6dSvdU2CAbtZthH5q98u1n/cAj1 +noak1Srpa3foGMTUn9CHu+5kwHPIpUPNeAZZBpq91uxa5pnkDMp3UrLIRJ2uZyr8 +4PxcknEEh8DR5hsM/IbDcrCJQglM19ZtQeW3LKkY4BsIxjDf45ymH407IQKBgE/g +Ul6cPfOxQRlNLH4VMVgInSyyxWx1mODFy7DRrgCuh5kTVh+QUVBM8x9lcwAn8V9/ +nQT55wR8E603pznqY/jX0xvAqZE6YVPcw4kpZcwNwL1RhEl8GliikBlRzUL3SsW3 +q30AfqEViHPE3XpE66PPo6Hb1ymJCVr77iUuC3wtAoGBAIBrOGunv1qZMfqmwAY2 +lxlzRgxgSiaev0lTNxDzZkmU/u3dgdTwJ5DDANqPwJc6b8SGYTp9rQ0mbgVHnhIB +jcJQBQkTfq6Z0H6OoTVi7dPs3ibQJFrtkoyvYAbyk36quBmNRjVh6rc8468bhXYr +v/t+MeGJP/0Zw8v/X2CFll96 +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/data/www-ap/index.html b/lib/PsychicHttp/examples/esp-idf/data/www-ap/index.html new file mode 100644 index 0000000..73df596 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/data/www-ap/index.html @@ -0,0 +1,15 @@ + + + + + + PsychicHTTP SoftAP Demo + + + +
+

SoftAP Demo

+

You are connected to the ESP in SoftAP mode.

+
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/data/www/alien.png b/lib/PsychicHttp/examples/esp-idf/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/examples/esp-idf/data/www/alien.png differ diff --git a/lib/PsychicHttp/examples/esp-idf/data/www/favicon.ico b/lib/PsychicHttp/examples/esp-idf/data/www/favicon.ico new file mode 100644 index 0000000..bdf785c Binary files /dev/null and b/lib/PsychicHttp/examples/esp-idf/data/www/favicon.ico differ diff --git a/lib/PsychicHttp/examples/esp-idf/data/www/index.html b/lib/PsychicHttp/examples/esp-idf/data/www/index.html new file mode 100644 index 0000000..4ee2491 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/data/www/index.html @@ -0,0 +1,236 @@ + + + + + + PsychicHTTP Demo + + + +
+

Basic Request Examples

+ + +

Static Serving

+

+ + +

+

Text File

+ +

Simple POST Form

+
+ + +
+ + +
+ +
+ +

Basic File Upload

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

Multipart POST Form

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

Websocket Demo

+ + + +
+ +
+ + + +

EventSource Demo

+ +
+ +
+ + +
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/data/www/text.txt b/lib/PsychicHttp/examples/esp-idf/data/www/text.txt new file mode 100644 index 0000000..5375816 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/data/www/text.txt @@ -0,0 +1 @@ +Test File. diff --git a/lib/PsychicHttp/examples/esp-idf/include/README b/lib/PsychicHttp/examples/esp-idf/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/esp-idf/lib/README b/lib/PsychicHttp/examples/esp-idf/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/esp-idf/main/CMakeLists.txt b/lib/PsychicHttp/examples/esp-idf/main/CMakeLists.txt new file mode 100644 index 0000000..ad22981 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/main/CMakeLists.txt @@ -0,0 +1,8 @@ +# This file was automatically generated for projects +# without default 'CMakeLists.txt' file. + +idf_component_register( + SRCS "main.cpp" + INCLUDE_DIRS ".") + +littlefs_create_partition_image(littlefs ${project_dir}/data) \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/main/main.cpp b/lib/PsychicHttp/examples/esp-idf/main/main.cpp new file mode 100644 index 0000000..21c18e4 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/main/main.cpp @@ -0,0 +1,510 @@ +/* + PsychicHTTP Server Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +/********************************************************************************************** +* Note: this demo relies on the following libraries (Install via Library Manager) +* ArduinoJson UrlEncode +**********************************************************************************************/ + +/********************************************************************************************** +* Note: this demo relies on various files to be uploaded on the LittleFS partition +* Follow instructions here: https://randomnerdtutorials.com/esp32-littlefs-arduino-ide/ +**********************************************************************************************/ + +#include +#include +#include +#include +#include +#include "secret.h" +#include +#ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE //set this to y in menuconfig to enable SSL +#include +#endif + +#ifndef WIFI_SSID + #error "You need to enter your wifi credentials. Rename secret.h to _secret.h and enter your credentials there." +#endif + +//Enter your WIFI credentials in secret.h +const char *ssid = WIFI_SSID; +const char *password = WIFI_PASS; + +// Set your SoftAP credentials +const char *softap_ssid = "PsychicHttp"; +const char *softap_password = ""; +IPAddress softap_ip(10, 0, 0, 1); + +//credentials for the /auth-basic and /auth-digest examples +const char *app_user = "admin"; +const char *app_pass = "admin"; +const char *app_name = "Your App"; + +//hostname for mdns (psychic.local) +const char *local_hostname = "psychic"; + +//#define CONFIG_ESP_HTTPS_SERVER_ENABLE to enable ssl +#ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE + bool app_enable_ssl = true; + String server_cert; + String server_key; +#endif + +//our main server object +#ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE + PsychicHttpsServer server; +#else + PsychicHttpServer server; +#endif +PsychicWebSocketHandler websocketHandler; +PsychicEventSource eventSource; + +bool connectToWifi() +{ + //dual client and AP mode + WiFi.mode(WIFI_AP_STA); + + // Configure SoftAP + WiFi.softAPConfig(softap_ip, softap_ip, IPAddress(255, 255, 255, 0)); // subnet FF FF FF 00 + WiFi.softAP(softap_ssid, softap_password); + IPAddress myIP = WiFi.softAPIP(); + Serial.print("SoftAP IP Address: "); + Serial.println(myIP); + + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + // Auto reconnect is set true as default + // To set auto connect off, use the following function + // WiFi.setAutoReconnect(false); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + + // We start by connecting to a WiFi network + // To debug, please enable Core Debug Level to Verbose + if (connectToWifi()) + { + //set up our esp32 to listen on the local_hostname.local domain + if (!MDNS.begin(local_hostname)) { + Serial.println("Error starting mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + //look up our keys? + #ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE + if (app_enable_ssl) + { + File fp = LittleFS.open("/server.crt"); + if (fp) + { + server_cert = fp.readString(); + + // Serial.println("Server Cert:"); + // Serial.println(server_cert); + } + else + { + Serial.println("server.pem not found, SSL not available"); + app_enable_ssl = false; + } + fp.close(); + + File fp2 = LittleFS.open("/server.key"); + if (fp2) + { + server_key = fp2.readString(); + + // Serial.println("Server Key:"); + // Serial.println(server_key); + } + else + { + Serial.println("server.key not found, SSL not available"); + app_enable_ssl = false; + } + fp2.close(); + } + #endif + + //setup server config stuff here + server.config.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + + #ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE + server.ssl_config.httpd.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + + //do we want secure or not? + if (app_enable_ssl) + { + server.listen(443, server_cert.c_str(), server_key.c_str()); + + //this creates a 2nd server listening on port 80 and redirects all requests HTTPS + PsychicHttpServer *redirectServer = new PsychicHttpServer(); + redirectServer->config.ctrl_port = 20424; // just a random port different from the default one + redirectServer->listen(80); + redirectServer->onNotFound([](PsychicRequest *request) { + String url = "https://" + request->host() + request->url(); + return request->redirect(url.c_str()); + }); + } + else + server.listen(80); + #else + server.listen(80); + #endif + + //serve static files from LittleFS/www on / only to clients on same wifi network + //this is where our /index.html file lives + server.serveStatic("/", LittleFS, "/www/")->setFilter(ON_STA_FILTER); + + //serve static files from LittleFS/www-ap on / only to clients on SoftAP + //this is where our /index.html file lives + server.serveStatic("/", LittleFS, "/www-ap/")->setFilter(ON_AP_FILTER); + + //serve static files from LittleFS/img on /img + //it's more efficient to serve everything from a single www directory, but this is also possible. + server.serveStatic("/img", LittleFS, "/img/"); + + //you can also serve single files + server.serveStatic("/myfile.txt", LittleFS, "/custom.txt"); + + //example callback everytime a connection is opened + server.onOpen([](PsychicClient *client) { + Serial.printf("[http] connection #%u connected from %s\n", client->socket(), client->localIP().toString().c_str()); + }); + + //example callback everytime a connection is closed + server.onClose([](PsychicClient *client) { + Serial.printf("[http] connection #%u closed from %s\n", client->socket(), client->localIP().toString().c_str()); + }); + + //api - json message passed in as post body + server.on("/api", HTTP_POST, [](PsychicRequest *request) + { + //load our JSON request + JsonDocument json; + String body = request->body(); + DeserializationError err = deserializeJson(json, body); + + //create our response json + JsonDocument output; + output["msg"] = "status"; + + //did it parse? + if (err) + { + output["status"] = "failure"; + output["error"] = err.c_str(); + } + else + { + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (json.containsKey("foo")) + { + String foo = json["foo"]; + output["foo"] = foo; + } + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + return request->reply(200, "application/json", jsonBuffer.c_str()); + }); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/ip", HTTP_GET, [](PsychicRequest *request) + { + String output = "Your IP is: " + request->client()->remoteIP().toString(); + return request->reply(output.c_str()); + }); + + //api - parameters passed in via query eg. /api/endpoint?foo=bar + server.on("/api", HTTP_GET, [](PsychicRequest *request) + { + //create a response object + JsonDocument output; + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + String foo = request->getParam("foo")->name(); + output["foo"] = foo; + } + + //serialize and return + String jsonBuffer; + serializeJson(output, jsonBuffer); + return request->reply(200, "application/json", jsonBuffer.c_str()); + }); + + //how to redirect a request + server.on("/redirect", HTTP_GET, [](PsychicRequest *request) + { + return request->redirect("/alien.png"); + }); + + //how to do basic auth + server.on("/auth-basic", HTTP_GET, [](PsychicRequest *request) + { + if (!request->authenticate(app_user, app_pass)) + return request->requestAuthentication(BASIC_AUTH, app_name, "You must log in."); + return request->reply("Auth Basic Success!"); + }); + + //how to do digest auth + server.on("/auth-digest", HTTP_GET, [](PsychicRequest *request) + { + if (!request->authenticate(app_user, app_pass)) + return request->requestAuthentication(DIGEST_AUTH, app_name, "You must log in."); + return request->reply("Auth Digest Success!"); + }); + + //example of getting / setting cookies + server.on("/cookies", HTTP_GET, [](PsychicRequest *request) + { + PsychicResponse response(request); + + int counter = 0; + if (request->hasCookie("counter")) + { + counter = std::stoi(request->getCookie("counter").c_str()); + counter++; + } + + char cookie[12]; + sprintf(cookie, "%i", counter); + + response.setCookie("counter", cookie); + response.setContent(cookie); + return response.send(); + }); + + //example of getting POST variables + server.on("/post", HTTP_POST, [](PsychicRequest *request) + { + String output; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + }); + + //you can set up a custom 404 handler. + server.onNotFound([](PsychicRequest *request) + { + return request->reply(404, "text/html", "Custom 404 Handler"); + }); + + //handle a very basic upload as post body + PsychicUploadHandler *uploadHandler = new PsychicUploadHandler(); + uploadHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + Serial.printf("Writing %d/%d bytes to: %s\n", (int)index+(int)len, request->contentLength(), path.c_str()); + + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + uploadHandler->onRequest([](PsychicRequest *request) + { + String url = "/" + request->getFilename(); + String output = "" + url + ""; + + return request->reply(output.c_str()); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + server.on("/upload/*", HTTP_POST, uploadHandler); + + //a little bit more complicated multipart form + PsychicUploadHandler *multipartHandler = new PsychicUploadHandler(); + multipartHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + //some progress over serial. + Serial.printf("Writing %d bytes to: %s\n", (int)len, path.c_str()); + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + multipartHandler->onRequest([](PsychicRequest *request) + { + PsychicWebParameter *file = request->getParam("file_upload"); + + String url = "/" + file->value(); + String output; + + output += "" + url + "
\n"; + output += "Bytes: " + String(file->size()) + "
\n"; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + server.on("/multipart", HTTP_POST, multipartHandler); + + //a websocket echo server + websocketHandler.onOpen([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u connected from %s\n", client->socket(), client->localIP().toString().c_str()); + client->sendMessage("Hello!"); + }); + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { + Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char *)frame->payload); + return request->reply(frame); + }); + websocketHandler.onClose([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->localIP().toString().c_str()); + }); + server.on("/ws", &websocketHandler); + + //EventSource server + eventSource.onOpen([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u connected from %s\n", client->socket(), client->localIP().toString().c_str()); + client->send("Hello user!", NULL, millis(), 1000); + }); + eventSource.onClose([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u closed from %s\n", client->socket(), client->localIP().toString().c_str()); + }); + server.on("/events", &eventSource); + } +} + +unsigned long lastUpdate = 0; +char output[60]; + +void loop() +{ + if (millis() - lastUpdate > 2000) + { + sprintf(output, "Millis: %lu\n", millis()); + websocketHandler.sendAll(output); + + sprintf(output, "%lu", millis()); + eventSource.send(output, "millis", millis(), 0); + + lastUpdate = millis(); + } + vTaskDelay(1 / portTICK_PERIOD_MS); // Feed WDT +} \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/main/secret.h b/lib/PsychicHttp/examples/esp-idf/main/secret.h new file mode 100644 index 0000000..97048cf --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/main/secret.h @@ -0,0 +1,2 @@ +#define WIFI_SSID "WIFI_SSID" +#define WIFI_PASS "WIFI_PASS" \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/partitions_custom.csv b/lib/PsychicHttp/examples/esp-idf/partitions_custom.csv new file mode 100644 index 0000000..57f4354 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/partitions_custom.csv @@ -0,0 +1,7 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x11000, 0xC000 +otadata, data, ota, 0x1D000, 0x2000 +phy_init, data, phy, 0x1F000, 0x1000 +app0, app, ota_0, 0x20000, 0x177000 +app1, app, ota_1, 0x1A0000, 0x177000 +littlefs, data, spiffs, 0x317000, 0xE1000 \ No newline at end of file diff --git a/lib/PsychicHttp/examples/esp-idf/sdkconfig.defaults b/lib/PsychicHttp/examples/esp-idf/sdkconfig.defaults new file mode 100644 index 0000000..6b0dc83 --- /dev/null +++ b/lib/PsychicHttp/examples/esp-idf/sdkconfig.defaults @@ -0,0 +1,64 @@ +CONFIG_AUTOSTART_ARDUINO=y +# CONFIG_WS2812_LED_ENABLE is not set +CONFIG_FREERTOS_HZ=1000 + +CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_COMPILER_OPTIMIZATION_SIZE=y + +# +# Serial flasher config +# +CONFIG_ESPTOOLPY_FLASHMODE_QIO=y +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_ESPTOOLPY_FLASHSIZE="4MB" + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_custom.csv" +#CONFIG_PARTITION_TABLE_FILENAME="partitions_custom.csv" +#CONFIG_PARTITION_TABLE_OFFSET=0xE000 +CONFIG_PARTITION_TABLE_MD5=y + +# +# ESP HTTPS OTA +# +CONFIG_ESP_HTTPS_OTA_DECRYPT_CB=y +CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=y +# end of ESP HTTPS OTA + + +# +# ESP HTTP client +# +CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH=y +# end of ESP HTTP client + +# +# HTTP Server +# +CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024 +CONFIG_HTTPD_MAX_URI_LEN=512 +CONFIG_HTTPD_ERR_RESP_NO_DELAY=y +CONFIG_HTTPD_PURGE_BUF_LEN=32 +# CONFIG_HTTPD_LOG_PURGE_DATA is not set +CONFIG_HTTPD_WS_SUPPORT=y +# end of HTTP Server + +# +# ESP HTTPS server +# +CONFIG_ESP_HTTPS_SERVER_ENABLE=n +# end of ESP HTTPS server + + +# +# TLS Key Exchange Methods +# +# 2 option require for arduino Arduino +CONFIG_MBEDTLS_PSK_MODES=y +CONFIG_MBEDTLS_KEY_EXCHANGE_PSK=y + diff --git a/lib/PsychicHttp/examples/old/esp_ota_http_server/.gitignore b/lib/PsychicHttp/examples/old/esp_ota_http_server/.gitignore new file mode 100644 index 0000000..be2b7e8 --- /dev/null +++ b/lib/PsychicHttp/examples/old/esp_ota_http_server/.gitignore @@ -0,0 +1,39 @@ +.pioenvs +.clang_complete +.gcc-flags.json +# Compiled Object files +*.slo +*.lo +*.o +*.obj +# Precompiled Headers +*.gch +*.pch +# Compiled Dynamic libraries +*.so +*.dylib +*.dll +# Fortran module files +*.mod +# Compiled Static libraries +*.lai +*.la +*.a +*.lib +# Executables +*.exe +*.out +*.app +# Visual Studio/VisualMicro stuff +Visual\ Micro +*.sdf +*.opensdf +*.suo +.pioenvs +.piolibdeps +.pio +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/settings.json +.vscode/.browse.c_cpp.db* +.vscode/ipch \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/esp_ota_http_server/include/README b/lib/PsychicHttp/examples/old/esp_ota_http_server/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/old/esp_ota_http_server/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/old/esp_ota_http_server/lib/README b/lib/PsychicHttp/examples/old/esp_ota_http_server/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/old/esp_ota_http_server/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/old/esp_ota_http_server/platformio.ini b/lib/PsychicHttp/examples/old/esp_ota_http_server/platformio.ini new file mode 100644 index 0000000..8a0c120 --- /dev/null +++ b/lib/PsychicHttp/examples/old/esp_ota_http_server/platformio.ini @@ -0,0 +1,74 @@ +; 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 + +[common] +lib_deps = ArduinoMongoose +monitor_speed = 115200 +monitor_port = /dev/ttyUSB1 +build_flags = + -DENABLE_DEBUG +# -DCS_ENABLE_STDIO + -DMG_ENABLE_HTTP_STREAMING_MULTIPART=1 + +build_flags_secure = + -DSIMPLE_SERVER_SECURE + -DMG_ENABLE_SSL=1 + +# -DMG_SSL_IF=MG_SSL_IF_OPENSSL +# -DKR_VERSION + + -DMG_SSL_MBED_DUMMY_RANDOM=1 + -DMG_SSL_IF=MG_SSL_IF_MBEDTLS + -DMG_SSL_IF_MBEDTLS_FREE_CERTS=1 + -DMG_SSL_IF_MBEDTLS_MAX_FRAG_LEN=2048 + +build_flags_auth = + -DADMIN_USER='"admin"' + -DADMIN_PASS='"admin"' + -DADMIN_REALM='"esp_ota_http_server"' + +#[env:huzzah] +#platform = espressif8266 +#board = huzzah +#framework = arduino +#monitor_speed = ${common.monitor_speed} +#monitor_port = ${common.monitor_port} +#lib_deps = ${common.lib_deps} +#build_flags = ${common.build_flags} + +[env:esp-wrover-kit] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} + +[env:esp-wrover-kit-secure] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} ${common.build_flags_secure} + +[env:esp-wrover-kit-auth] +extends = env:esp-wrover-kit +build_flags = ${common.build_flags} ${common.build_flags_auth} -ggdb + +#[env:linux_x86_64] +#platform = linux_x86_64 +#framework = arduino +#board = generic +#lib_deps = ${common.lib_deps} +#build_flags = ${common.build_flags} +#build_flags = -DSERIAL_TO_CONSOLE \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/esp_ota_http_server/src/esp_ota_http_server.cpp b/lib/PsychicHttp/examples/old/esp_ota_http_server/src/esp_ota_http_server.cpp new file mode 100644 index 0000000..9d9d35b --- /dev/null +++ b/lib/PsychicHttp/examples/old/esp_ota_http_server/src/esp_ota_http_server.cpp @@ -0,0 +1,229 @@ +// +// A simple server implementation showing how to: +// * serve static messages +// * read GET and POST parameters +// * handle missing pages / 404s +// + +#include +#include +#include +#include + +#ifdef ESP32 +#include +#define START_ESP_WIFI +#elif defined(ESP8266) +#include +#define START_ESP_WIFI +#else +#error Platform not supported +#endif + +MongooseHttpServer server; + +const char *ssid = "wifi"; +const char *password = "password"; + +const char *server_pem = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIDDjCCAfagAwIBAgIBBDANBgkqhkiG9w0BAQsFADA/MRkwFwYDVQQDDBB0ZXN0\r\n" +"LmNlc2FudGEuY29tMRAwDgYDVQQKDAdDZXNhbnRhMRAwDgYDVQQLDAd0ZXN0aW5n\r\n" +"MB4XDTE2MTExMzEzMTgwMVoXDTI2MDgxMzEzMTgwMVowFDESMBAGA1UEAwwJbG9j\r\n" +"YWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAro8CW1X0xaGm\r\n" +"GkDaMxKbXWA5Lw+seA61tioGrSIQzuqLYeJoFnwVgF0jB5PTj+3EiGMBcA/mh73V\r\n" +"AthTFmJBxj+agIp7/cvUBpgfLClmSYL2fZi6Fodz+f9mcry3XRw7O6vlamtWfTX8\r\n" +"TAmMSR6PXVBHLgjs5pDOFFmrNAsM5sLYU1/1MFvE2Z9InTI5G437IE1WchRSbpYd\r\n" +"HchC39XzpDGoInZB1a3OhcHm+xUtLpMJ0G0oE5VFEynZreZoEIY4JxspQ7LPsay9\r\n" +"fx3Tlk09gEMQgVCeCNiQwUxZdtLau2x61LNcdZCKN7FbFLJszv1U2uguELsTmi7E\r\n" +"6pHrTziosQIDAQABo0AwPjAJBgNVHRMEAjAAMAsGA1UdDwQEAwIDqDATBgNVHSUE\r\n" +"DDAKBggrBgEFBQcDATAPBgNVHREECDAGhwR/AAABMA0GCSqGSIb3DQEBCwUAA4IB\r\n" +"AQBUw0hbTcT6crzODO4QAXU7z4Xxn0LkxbXEsoThG1QCVgMc4Bhpx8gyz5CLyHYz\r\n" +"AiJOBFEeV0XEqoGTNMMFelR3Q5Tg9y1TYO3qwwAWxe6/brVzpts6NiG1uEMBnBFg\r\n" +"oN1x3I9x4NpOxU5MU1dlIxvKs5HQCoNJ8D0SqOX9BV/pZqwEgiCbuWDWQAlxkFpn\r\n" +"iLonlkVI5hTuybCSBsa9FEI9M6JJn9LZmlH90FYHeS4t6P8eOJCeekHL0jUG4Iae\r\n" +"DMP12h8Sd0yxIKmmZ+Q/p/D/BkuHf5Idv3hgyLkZ4mNznjK49wHaYM+BgBoL3Zeg\r\n" +"gJ2sWjUlokrbHswSBLLbUJIF\r\n" +"-----END CERTIFICATE-----\r\n"; + +const char *server_key = +"-----BEGIN PRIVATE KEY-----\r\n" +"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCujwJbVfTFoaYa\r\n" +"QNozEptdYDkvD6x4DrW2KgatIhDO6oth4mgWfBWAXSMHk9OP7cSIYwFwD+aHvdUC\r\n" +"2FMWYkHGP5qAinv9y9QGmB8sKWZJgvZ9mLoWh3P5/2ZyvLddHDs7q+Vqa1Z9NfxM\r\n" +"CYxJHo9dUEcuCOzmkM4UWas0CwzmwthTX/UwW8TZn0idMjkbjfsgTVZyFFJulh0d\r\n" +"yELf1fOkMagidkHVrc6Fweb7FS0ukwnQbSgTlUUTKdmt5mgQhjgnGylDss+xrL1/\r\n" +"HdOWTT2AQxCBUJ4I2JDBTFl20tq7bHrUs1x1kIo3sVsUsmzO/VTa6C4QuxOaLsTq\r\n" +"ketPOKixAgMBAAECggEAI+uNwpnHirue4Jwjyoqzqd1ZJxQEm5f7UIcJZKsz5kBh\r\n" +"ej0KykWybv27bZ2/1UhKPv6QlyzOdXRc1v8I6fxCKLeB5Z2Zsjo1YT4AfCfwwoPO\r\n" +"kT3SXTx2YyVpQYcP/HsIvVi8FtALtixbxJHaall9iugwHYr8pN17arihAE6d0wZC\r\n" +"JXtXRjUWwjKzXP8FoH4KhyadhHbDwIbbJe3cyLfdvp54Gr0YHha0JcOxYgDYNya4\r\n" +"OKxlCluI+hPF31iNzOmFLQVrdYynyPcR6vY5XOiANKE2iNbqCzRb54CvW9WMqObX\r\n" +"RD9t3DMOxGsbVNIwyzZndWy13HoQMGnrHfnGak9ueQKBgQDiVtOqYfLnUnTxvJ/b\r\n" +"qlQZr2ZmsYPZztxlP+DSqZGPD+WtGSo9+rozWfzjTv3KGIDLvf+GFVmjVHwlLQfd\r\n" +"u7eTemWHFc4HK68wruzPO/FdyVpQ4w9v3Usg+ll4a/PDEId0fDMjAr6kk4LC6t8y\r\n" +"9fJR0HjOz57jVnlrDt3v50G8BwKBgQDFbw+jRiUxXnBbDyXZLi+I4iGBGdC+CbaJ\r\n" +"CmsM6/TsOFc+GRsPwQF1gCGqdaURw76noIVKZJOSc8I+yiwU6izyh/xaju5JiWQd\r\n" +"kwbU1j4DE6GnxmT3ARmB7VvCxjaEZEAtICWs1QTKRz7PcTV8yr7Ng1A3VIy+NSpo\r\n" +"LFMMmk83hwKBgQDVCEwpLg/mUeHoNVVw95w4oLKNLb+gHeerFLiTDy8FrDzM88ai\r\n" +"l37yHly7xflxYia3nZkHpsi7xiUjCINC3BApKyasQoWskh1OgRY653yCfaYYQ96f\r\n" +"t3WjEH9trI2+p6wWo1+uMEMnu/9zXoW9/WeaQdGzNg+igh29+jxCNTPVuQKBgGV4\r\n" +"CN9vI5pV4QTLqjYOSJvfLDz/mYqxz0BrPE1tz3jAFAZ0PLZCCY/sBGFpCScyJQBd\r\n" +"vWNYgYeZOtGuci1llSgov4eDQfBFTlDsyWwFl+VY55IkoqtXw1ZFOQ3HdSlhpKIM\r\n" +"jZBgApA7QYq3sjeqs5lHzahCKftvs5XKgfxOKjxtAoGBALdnYe6xkDvGLvI51Yr+\r\n" +"Dy0TNcB5W84SxUKvM7DVEomy1QPB57ZpyQaoBq7adOz0pWJXfp7qo4950ZOhBGH1\r\n" +"hKbZ6c4ggwVJy2j49EgMok5NGCKvPAtabbR6H8Mz8DW9aXURxhWJvij+Qw1fWK4b\r\n" +"7G/qUI9iE5iUU7MkIcLIbTf/\r\n" +"-----END PRIVATE KEY-----\r\n"; + +const char* server_index = +"" +"
" + "" + "" +"
" +"
progress: 0%
" +""; + +#include + +bool updateCompleted = false; + +static void updateError(MongooseHttpServerRequest *request) +{ + MongooseHttpServerResponseStream *resp = request->beginResponseStream(); + resp->setCode(500); + resp->setContentType("text/plain"); + resp->printf("Error: %d", Update.getError()); + request->send(resp); + + // Anoyingly this uses Stream rather than Print... + Update.printError(Serial); +} + +void setup() +{ + Serial.begin(115200); + +#ifdef START_ESP_WIFI + 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()); + Serial.print("Hostname: "); +#ifdef ESP32 + Serial.println(WiFi.getHostname()); +#elif defined(ESP8266) + Serial.println(WiFi.hostname()); +#endif +#endif + + Mongoose.begin(); + +#ifdef SIMPLE_SERVER_SECURE + if(false == server.begin(443, server_pem, server_key)) { + Serial.print("Failed to start server"); + return; + } +#else + server.begin(80); +#endif + + server.on("/$", HTTP_GET, [](MongooseHttpServerRequest *request) { +#if defined(ADMIN_USER) && defined(ADMIN_PASS) && defined(ADMIN_REALM) + if(false == request->authenticate(ADMIN_USER, ADMIN_PASS)) { + request->requestAuthentication(ADMIN_REALM); + return; + } +#endif + + request->send(200, "text/html", server_index); + }); + + server.on("/update$", HTTP_POST)-> + onRequest([](MongooseHttpServerRequest *request) { +#if defined(ADMIN_USER) && defined(ADMIN_PASS) && defined(ADMIN_REALM) + if(false == request->authenticate(ADMIN_USER, ADMIN_PASS)) { + request->requestAuthentication(ADMIN_REALM); + return; + } +#endif + updateCompleted = false; + })-> + onUpload([](MongooseHttpServerRequest *request, int ev, MongooseString filename, uint64_t index, uint8_t *data, size_t len) + { + if(MG_EV_HTTP_PART_BEGIN == ev) { + Serial.printf("Update Start: %s\n", filename.c_str()); + + if (!Update.begin()) { //start with max available size + updateError(request); + } + } + + if(!Update.hasError()) + { + Serial.printf("Update Writing %llu\n", index); + if(Update.write(data, len) != len) { + updateError(request); + } + } + + if(MG_EV_HTTP_PART_END == ev) { + Serial.println("Data finished"); + if(Update.end(true)) { + Serial.printf("Update Success: %lluB\n", index+len); + request->send(200, "text/plain", "OK"); + updateCompleted = true; + } else { + updateError(request); + } + } + + return len; + })-> + onClose([](MongooseHttpServerRequest *request) + { + if(updateCompleted) { + ESP.restart(); + } + }); +} + +void loop() +{ + Mongoose.poll(1000); +} diff --git a/lib/PsychicHttp/examples/old/esp_ota_http_server/test/README b/lib/PsychicHttp/examples/old/esp_ota_http_server/test/README new file mode 100644 index 0000000..df5066e --- /dev/null +++ b/lib/PsychicHttp/examples/old/esp_ota_http_server/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/lib/PsychicHttp/examples/old/simple_http_server/.gitignore b/lib/PsychicHttp/examples/old/simple_http_server/.gitignore new file mode 100644 index 0000000..be2b7e8 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/.gitignore @@ -0,0 +1,39 @@ +.pioenvs +.clang_complete +.gcc-flags.json +# Compiled Object files +*.slo +*.lo +*.o +*.obj +# Precompiled Headers +*.gch +*.pch +# Compiled Dynamic libraries +*.so +*.dylib +*.dll +# Fortran module files +*.mod +# Compiled Static libraries +*.lai +*.la +*.a +*.lib +# Executables +*.exe +*.out +*.app +# Visual Studio/VisualMicro stuff +Visual\ Micro +*.sdf +*.opensdf +*.suo +.pioenvs +.piolibdeps +.pio +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/settings.json +.vscode/.browse.c_cpp.db* +.vscode/ipch \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/simple_http_server/include/README b/lib/PsychicHttp/examples/old/simple_http_server/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/old/simple_http_server/lib/README b/lib/PsychicHttp/examples/old/simple_http_server/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/old/simple_http_server/platformio.ini b/lib/PsychicHttp/examples/old/simple_http_server/platformio.ini new file mode 100644 index 0000000..5da8a5a --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/platformio.ini @@ -0,0 +1,64 @@ +; 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 + +[common] +lib_deps = ArduinoMongoose +monitor_speed = 115200 +monitor_port = /dev/ttyUSB1 +build_flags = + -DENABLE_DEBUG +# -DCS_ENABLE_STDIO + +build_flags_secure = + -DSIMPLE_SERVER_SECURE + -DMG_ENABLE_SSL=1 + +# -DMG_SSL_IF=MG_SSL_IF_OPENSSL +# -DKR_VERSION + + -DMG_SSL_MBED_DUMMY_RANDOM=1 + -DMG_SSL_IF=MG_SSL_IF_MBEDTLS + -DMG_SSL_IF_MBEDTLS_FREE_CERTS=1 + -DMG_SSL_IF_MBEDTLS_MAX_FRAG_LEN=2048 + +[env:huzzah] +platform = espressif8266 +board = huzzah +framework = arduino +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} + +[env:esp-wrover-kit] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} + +[env:esp-wrover-kit-secure] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} ${common.build_flags_secure} + +#[env:linux_x86_64] +#platform = linux_x86_64 +#framework = arduino +#board = generic +#lib_deps = ${common.lib_deps} +#build_flags = ${common.build_flags} +#build_flags = -DSERIAL_TO_CONSOLE \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/simple_http_server/src/simple_http_server.cpp b/lib/PsychicHttp/examples/old/simple_http_server/src/simple_http_server.cpp new file mode 100644 index 0000000..ffa1e4d --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/src/simple_http_server.cpp @@ -0,0 +1,211 @@ +// +// A simple server implementation showing how to: +// * serve static messages +// * read GET and POST parameters +// * handle missing pages / 404s +// + +#include +#include +#include + +#ifdef ESP32 +#include +#define START_ESP_WIFI +#elif defined(ESP8266) +#include +#define START_ESP_WIFI +#else +#error Platform not supported +#endif + +MongooseHttpServer server; + +const char *ssid = "wifi"; +const char *password = "password"; + +const char *PARAM_MESSAGE = "message"; + +const char *server_pem = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIDDjCCAfagAwIBAgIBBDANBgkqhkiG9w0BAQsFADA/MRkwFwYDVQQDDBB0ZXN0\r\n" +"LmNlc2FudGEuY29tMRAwDgYDVQQKDAdDZXNhbnRhMRAwDgYDVQQLDAd0ZXN0aW5n\r\n" +"MB4XDTE2MTExMzEzMTgwMVoXDTI2MDgxMzEzMTgwMVowFDESMBAGA1UEAwwJbG9j\r\n" +"YWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAro8CW1X0xaGm\r\n" +"GkDaMxKbXWA5Lw+seA61tioGrSIQzuqLYeJoFnwVgF0jB5PTj+3EiGMBcA/mh73V\r\n" +"AthTFmJBxj+agIp7/cvUBpgfLClmSYL2fZi6Fodz+f9mcry3XRw7O6vlamtWfTX8\r\n" +"TAmMSR6PXVBHLgjs5pDOFFmrNAsM5sLYU1/1MFvE2Z9InTI5G437IE1WchRSbpYd\r\n" +"HchC39XzpDGoInZB1a3OhcHm+xUtLpMJ0G0oE5VFEynZreZoEIY4JxspQ7LPsay9\r\n" +"fx3Tlk09gEMQgVCeCNiQwUxZdtLau2x61LNcdZCKN7FbFLJszv1U2uguELsTmi7E\r\n" +"6pHrTziosQIDAQABo0AwPjAJBgNVHRMEAjAAMAsGA1UdDwQEAwIDqDATBgNVHSUE\r\n" +"DDAKBggrBgEFBQcDATAPBgNVHREECDAGhwR/AAABMA0GCSqGSIb3DQEBCwUAA4IB\r\n" +"AQBUw0hbTcT6crzODO4QAXU7z4Xxn0LkxbXEsoThG1QCVgMc4Bhpx8gyz5CLyHYz\r\n" +"AiJOBFEeV0XEqoGTNMMFelR3Q5Tg9y1TYO3qwwAWxe6/brVzpts6NiG1uEMBnBFg\r\n" +"oN1x3I9x4NpOxU5MU1dlIxvKs5HQCoNJ8D0SqOX9BV/pZqwEgiCbuWDWQAlxkFpn\r\n" +"iLonlkVI5hTuybCSBsa9FEI9M6JJn9LZmlH90FYHeS4t6P8eOJCeekHL0jUG4Iae\r\n" +"DMP12h8Sd0yxIKmmZ+Q/p/D/BkuHf5Idv3hgyLkZ4mNznjK49wHaYM+BgBoL3Zeg\r\n" +"gJ2sWjUlokrbHswSBLLbUJIF\r\n" +"-----END CERTIFICATE-----\r\n"; + +const char *server_key = +"-----BEGIN PRIVATE KEY-----\r\n" +"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCujwJbVfTFoaYa\r\n" +"QNozEptdYDkvD6x4DrW2KgatIhDO6oth4mgWfBWAXSMHk9OP7cSIYwFwD+aHvdUC\r\n" +"2FMWYkHGP5qAinv9y9QGmB8sKWZJgvZ9mLoWh3P5/2ZyvLddHDs7q+Vqa1Z9NfxM\r\n" +"CYxJHo9dUEcuCOzmkM4UWas0CwzmwthTX/UwW8TZn0idMjkbjfsgTVZyFFJulh0d\r\n" +"yELf1fOkMagidkHVrc6Fweb7FS0ukwnQbSgTlUUTKdmt5mgQhjgnGylDss+xrL1/\r\n" +"HdOWTT2AQxCBUJ4I2JDBTFl20tq7bHrUs1x1kIo3sVsUsmzO/VTa6C4QuxOaLsTq\r\n" +"ketPOKixAgMBAAECggEAI+uNwpnHirue4Jwjyoqzqd1ZJxQEm5f7UIcJZKsz5kBh\r\n" +"ej0KykWybv27bZ2/1UhKPv6QlyzOdXRc1v8I6fxCKLeB5Z2Zsjo1YT4AfCfwwoPO\r\n" +"kT3SXTx2YyVpQYcP/HsIvVi8FtALtixbxJHaall9iugwHYr8pN17arihAE6d0wZC\r\n" +"JXtXRjUWwjKzXP8FoH4KhyadhHbDwIbbJe3cyLfdvp54Gr0YHha0JcOxYgDYNya4\r\n" +"OKxlCluI+hPF31iNzOmFLQVrdYynyPcR6vY5XOiANKE2iNbqCzRb54CvW9WMqObX\r\n" +"RD9t3DMOxGsbVNIwyzZndWy13HoQMGnrHfnGak9ueQKBgQDiVtOqYfLnUnTxvJ/b\r\n" +"qlQZr2ZmsYPZztxlP+DSqZGPD+WtGSo9+rozWfzjTv3KGIDLvf+GFVmjVHwlLQfd\r\n" +"u7eTemWHFc4HK68wruzPO/FdyVpQ4w9v3Usg+ll4a/PDEId0fDMjAr6kk4LC6t8y\r\n" +"9fJR0HjOz57jVnlrDt3v50G8BwKBgQDFbw+jRiUxXnBbDyXZLi+I4iGBGdC+CbaJ\r\n" +"CmsM6/TsOFc+GRsPwQF1gCGqdaURw76noIVKZJOSc8I+yiwU6izyh/xaju5JiWQd\r\n" +"kwbU1j4DE6GnxmT3ARmB7VvCxjaEZEAtICWs1QTKRz7PcTV8yr7Ng1A3VIy+NSpo\r\n" +"LFMMmk83hwKBgQDVCEwpLg/mUeHoNVVw95w4oLKNLb+gHeerFLiTDy8FrDzM88ai\r\n" +"l37yHly7xflxYia3nZkHpsi7xiUjCINC3BApKyasQoWskh1OgRY653yCfaYYQ96f\r\n" +"t3WjEH9trI2+p6wWo1+uMEMnu/9zXoW9/WeaQdGzNg+igh29+jxCNTPVuQKBgGV4\r\n" +"CN9vI5pV4QTLqjYOSJvfLDz/mYqxz0BrPE1tz3jAFAZ0PLZCCY/sBGFpCScyJQBd\r\n" +"vWNYgYeZOtGuci1llSgov4eDQfBFTlDsyWwFl+VY55IkoqtXw1ZFOQ3HdSlhpKIM\r\n" +"jZBgApA7QYq3sjeqs5lHzahCKftvs5XKgfxOKjxtAoGBALdnYe6xkDvGLvI51Yr+\r\n" +"Dy0TNcB5W84SxUKvM7DVEomy1QPB57ZpyQaoBq7adOz0pWJXfp7qo4950ZOhBGH1\r\n" +"hKbZ6c4ggwVJy2j49EgMok5NGCKvPAtabbR6H8Mz8DW9aXURxhWJvij+Qw1fWK4b\r\n" +"7G/qUI9iE5iUU7MkIcLIbTf/\r\n" +"-----END PRIVATE KEY-----\r\n"; + +static void notFound(MongooseHttpServerRequest *request); + +#include + +void setup() +{ + Serial.begin(115200); + +#ifdef START_ESP_WIFI + 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()); + Serial.print("Hostname: "); +#ifdef ESP32 + Serial.println(WiFi.getHostname()); +#elif defined(ESP8266) + Serial.println(WiFi.hostname()); +#endif +#endif + + Mongoose.begin(); + +#ifdef SIMPLE_SERVER_SECURE + if(false == server.begin(443, server_pem, server_key)) { + Serial.print("Failed to start server"); + return; + } +#else + server.begin(80); +#endif + + server.on("/$", HTTP_GET, [](MongooseHttpServerRequest *request) { + request->send(200, "text/plain", "Hello world"); + }); + + // Send a GET request to /get?message= + server.on("/get$", HTTP_GET, [](MongooseHttpServerRequest *request) { + String message; + if (request->hasParam(PARAM_MESSAGE)) + { + message = request->getParam(PARAM_MESSAGE); + } + 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, [](MongooseHttpServerRequest *request) { + String message; + if (request->hasParam(PARAM_MESSAGE)) + { + message = request->getParam(PARAM_MESSAGE); + } + else + { + message = "No message sent"; + } + request->send(200, "text/plain", "Hello, POST: " + message); + }); + + // Test the basic response class + server.on("/basic$", HTTP_GET, [](MongooseHttpServerRequest *request) { + MongooseHttpServerResponseBasic *resp = request->beginResponse(); + resp->setCode(200); + resp->setContentType("text/html"); + resp->addHeader("Cache-Control", "max-age=300"); + resp->addHeader("X-hello", "world"); + resp->setContent( + "\n" + "\n" + "Basic Page\n" + "\n" + "\n" + "

Basic Page

\n" + "

\n" + "This page has been sent using the MongooseHttpServerResponseBasic class\n" + "

\n" + "\n" + "\n"); + request->send(resp); + }); + + // Test the stream response class + server.on("/stream$", HTTP_GET, [](MongooseHttpServerRequest *request) { + MongooseHttpServerResponseStream *resp = request->beginResponseStream(); + resp->setCode(200); + resp->setContentType("text/html"); + resp->addHeader("Cache-Control", "max-age=300"); + resp->addHeader("X-hello", "world"); + + resp->println(""); + resp->println(""); + resp->println("Stream Page"); + resp->println(""); + resp->println(""); + resp->println("

Stream Page

"); + resp->println("

"); + resp->println("This page has been sent using the MongooseHttpServerResponseStream class"); + resp->println("

"); + resp->println("

"); + resp->printf("micros = %lu
", micros()); + resp->printf("free = %u
", ESP.getFreeHeap()); + resp->println("

"); + resp->println(""); + resp->println(""); + + request->send(resp); + }); + + server.onNotFound(notFound); +} + +void loop() +{ + Mongoose.poll(1000); + Serial.printf("Free memory %u\n", ESP.getFreeHeap()); +} + +static void notFound(MongooseHttpServerRequest *request) +{ + request->send(404, "text/plain", "Not found"); +} diff --git a/lib/PsychicHttp/examples/old/simple_http_server/test/README b/lib/PsychicHttp/examples/old/simple_http_server/test/README new file mode 100644 index 0000000..df5066e --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/lib/PsychicHttp/examples/old/simple_http_server/test/tests.rest b/lib/PsychicHttp/examples/old/simple_http_server/test/tests.rest new file mode 100644 index 0000000..4072428 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simple_http_server/test/tests.rest @@ -0,0 +1,35 @@ +# Name: REST Client +# Id: humao.rest-client +# Description: REST Client for Visual Studio Code +# Version: 0.21.3 +# Publisher: Huachao Mao +# VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=humao.rest-client + +@baseUrl = http://172.16.0.87 + +### + +GET {{baseUrl}}/ HTTP/1.1 + +### + +GET {{baseUrl}}/get?message=Hello+World HTTP/1.1 + +### + +POST {{baseUrl}}/post HTTP/1.1 +Content-Type: application/x-www-form-urlencoded;charset=UTF-8 + +message=Hello+World + +### + +GET {{baseUrl}}/someRandomFile HTTP/1.1 + +### + +GET {{baseUrl}}/basic HTTP/1.1 + +### + +GET {{baseUrl}}/stream HTTP/1.1 diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/.gitignore b/lib/PsychicHttp/examples/old/simplest_web_server_esp/.gitignore new file mode 100644 index 0000000..be2b7e8 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/.gitignore @@ -0,0 +1,39 @@ +.pioenvs +.clang_complete +.gcc-flags.json +# Compiled Object files +*.slo +*.lo +*.o +*.obj +# Precompiled Headers +*.gch +*.pch +# Compiled Dynamic libraries +*.so +*.dylib +*.dll +# Fortran module files +*.mod +# Compiled Static libraries +*.lai +*.la +*.a +*.lib +# Executables +*.exe +*.out +*.app +# Visual Studio/VisualMicro stuff +Visual\ Micro +*.sdf +*.opensdf +*.suo +.pioenvs +.piolibdeps +.pio +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/settings.json +.vscode/.browse.c_cpp.db* +.vscode/ipch \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/.travis.yml b/lib/PsychicHttp/examples/old/simplest_web_server_esp/.travis.yml new file mode 100644 index 0000000..7c486f1 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/include/README b/lib/PsychicHttp/examples/old/simplest_web_server_esp/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/lib/README b/lib/PsychicHttp/examples/old/simplest_web_server_esp/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/platformio.ini b/lib/PsychicHttp/examples/old/simplest_web_server_esp/platformio.ini new file mode 100644 index 0000000..d02c3bc --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/platformio.ini @@ -0,0 +1,40 @@ +; 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 + +[common] +lib_deps = ArduinoMongoose +monitor_speed = 115200 +build_flags = + +[espressif8266] +build_flags = -DMG_ESP8266 + +[espressif32] +build_flags = + +[env:huzzah] +platform = espressif8266 +framework = arduino +board = huzzah +monitor_speed = ${common.monitor_speed} +lib_deps = ${common.lib_deps} +build_flags = + ${espressif8266.build_flags} + ${common.build_flags} + +[env:espwroverkit] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +lib_deps = ${common.lib_deps} +build_flags = + ${espressif32.build_flags} + ${common.build_flags} diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/src/simplest_web_server.cpp b/lib/PsychicHttp/examples/old/simplest_web_server_esp/src/simplest_web_server.cpp new file mode 100644 index 0000000..cedb9c2 --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/src/simplest_web_server.cpp @@ -0,0 +1,97 @@ +// Copyright (c) 2015 Cesanta Software Limited +// All rights reserved + +#include + +#ifdef ESP32 +#include +#elif defined(ESP8266) +#include +#else +#error Platform not supported +#endif + +#include "mongoose.h" + +const char* ssid = "my-ssid"; +const char* password = "my-password"; + +static const char *s_http_port = "80"; +//static struct mg_serve_http_opts s_http_server_opts; + +static void ev_handler(struct mg_connection *nc, int ev, void *p, void *d) { + static const char *reply_fmt = + "HTTP/1.0 200 OK\r\n" + "Connection: close\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello %s\n"; + + switch (ev) { + case MG_EV_ACCEPT: { + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), + MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + Serial.printf("Connection %p from %s\n", nc, addr); + break; + } + case MG_EV_HTTP_REQUEST: { + char addr[32]; + struct http_message *hm = (struct http_message *) p; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), + MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + Serial.printf("HTTP request from %s: %.*s %.*s\n", addr, (int) hm->method.len, + hm->method.p, (int) hm->uri.len, hm->uri.p); + mg_printf(nc, reply_fmt, addr); + nc->flags |= MG_F_SEND_AND_CLOSE; + break; + } + case MG_EV_CLOSE: { + Serial.printf("Connection %p closed\n", nc); + break; + } + } +} + +struct mg_mgr mgr; +struct mg_connection *nc; + +void setup() +{ + Serial.begin(115200); + + Serial.print("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + + mg_mgr_init(&mgr, NULL); + Serial.printf("Starting web server on port %s\n", s_http_port); + nc = mg_bind(&mgr, s_http_port, ev_handler, NULL); + if (nc == NULL) { + Serial.printf("Failed to create listener\n"); + return; + } + + // Set up HTTP server parameters + mg_set_protocol_http_websocket(nc); +// s_http_server_opts.document_root = "."; // Serve current directory +// s_http_server_opts.enable_directory_listing = "yes"; +} + +static uint32_t count = 0; +void loop() +{ + mg_mgr_poll(&mgr, 1000); + //Serial.println(count++); +} diff --git a/lib/PsychicHttp/examples/old/simplest_web_server_esp/test/README b/lib/PsychicHttp/examples/old/simplest_web_server_esp/test/README new file mode 100644 index 0000000..df5066e --- /dev/null +++ b/lib/PsychicHttp/examples/old/simplest_web_server_esp/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/lib/PsychicHttp/examples/old/websocket_chat/.gitignore b/lib/PsychicHttp/examples/old/websocket_chat/.gitignore new file mode 100644 index 0000000..be2b7e8 --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/.gitignore @@ -0,0 +1,39 @@ +.pioenvs +.clang_complete +.gcc-flags.json +# Compiled Object files +*.slo +*.lo +*.o +*.obj +# Precompiled Headers +*.gch +*.pch +# Compiled Dynamic libraries +*.so +*.dylib +*.dll +# Fortran module files +*.mod +# Compiled Static libraries +*.lai +*.la +*.a +*.lib +# Executables +*.exe +*.out +*.app +# Visual Studio/VisualMicro stuff +Visual\ Micro +*.sdf +*.opensdf +*.suo +.pioenvs +.piolibdeps +.pio +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/settings.json +.vscode/.browse.c_cpp.db* +.vscode/ipch \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/websocket_chat/include/README b/lib/PsychicHttp/examples/old/websocket_chat/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/old/websocket_chat/lib/README b/lib/PsychicHttp/examples/old/websocket_chat/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/old/websocket_chat/platformio.ini b/lib/PsychicHttp/examples/old/websocket_chat/platformio.ini new file mode 100644 index 0000000..165b7ac --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/platformio.ini @@ -0,0 +1,64 @@ +; 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 + +[common] +lib_deps = ArduinoMongoose +monitor_speed = 115200 +monitor_port = /dev/ttyUSB2 +build_flags = + -DENABLE_DEBUG +# -DCS_ENABLE_STDIO + +build_flags_secure = + -DSIMPLE_SERVER_SECURE + -DMG_ENABLE_SSL=1 + +# -DMG_SSL_IF=MG_SSL_IF_OPENSSL +# -DKR_VERSION + + -DMG_SSL_MBED_DUMMY_RANDOM=1 + -DMG_SSL_IF=MG_SSL_IF_MBEDTLS + -DMG_SSL_IF_MBEDTLS_FREE_CERTS=1 + -DMG_SSL_IF_MBEDTLS_MAX_FRAG_LEN=2048 + +[env:huzzah] +platform = espressif8266 +board = huzzah +framework = arduino +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} + +[env:esp-wrover-kit] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} + +[env:esp-wrover-kit-secure] +platform = espressif32 +framework = arduino +board = esp-wrover-kit +monitor_speed = ${common.monitor_speed} +monitor_port = ${common.monitor_port} +lib_deps = ${common.lib_deps} +build_flags = ${common.build_flags} ${common.build_flags_secure} + +#[env:linux_x86_64] +#platform = linux_x86_64 +#framework = arduino +#board = generic +#lib_deps = ${common.lib_deps} +#build_flags = ${common.build_flags} +#build_flags = -DSERIAL_TO_CONSOLE \ No newline at end of file diff --git a/lib/PsychicHttp/examples/old/websocket_chat/src/websocket_chat.cpp b/lib/PsychicHttp/examples/old/websocket_chat/src/websocket_chat.cpp new file mode 100644 index 0000000..47a04cf --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/src/websocket_chat.cpp @@ -0,0 +1,235 @@ +// +// A simple server implementation showing how to: +// * serve static messages +// * read GET and POST parameters +// * handle missing pages / 404s +// + +#include +#include +#include + +#ifdef ESP32 +#include +#define START_ESP_WIFI +#elif defined(ESP8266) +#include +#define START_ESP_WIFI +#else +#error Platform not supported +#endif + +MongooseHttpServer server; + +const char *ssid = "wifi"; +const char *password = "password"; + +const char *server_pem = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIDDjCCAfagAwIBAgIBBDANBgkqhkiG9w0BAQsFADA/MRkwFwYDVQQDDBB0ZXN0\r\n" +"LmNlc2FudGEuY29tMRAwDgYDVQQKDAdDZXNhbnRhMRAwDgYDVQQLDAd0ZXN0aW5n\r\n" +"MB4XDTE2MTExMzEzMTgwMVoXDTI2MDgxMzEzMTgwMVowFDESMBAGA1UEAwwJbG9j\r\n" +"YWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAro8CW1X0xaGm\r\n" +"GkDaMxKbXWA5Lw+seA61tioGrSIQzuqLYeJoFnwVgF0jB5PTj+3EiGMBcA/mh73V\r\n" +"AthTFmJBxj+agIp7/cvUBpgfLClmSYL2fZi6Fodz+f9mcry3XRw7O6vlamtWfTX8\r\n" +"TAmMSR6PXVBHLgjs5pDOFFmrNAsM5sLYU1/1MFvE2Z9InTI5G437IE1WchRSbpYd\r\n" +"HchC39XzpDGoInZB1a3OhcHm+xUtLpMJ0G0oE5VFEynZreZoEIY4JxspQ7LPsay9\r\n" +"fx3Tlk09gEMQgVCeCNiQwUxZdtLau2x61LNcdZCKN7FbFLJszv1U2uguELsTmi7E\r\n" +"6pHrTziosQIDAQABo0AwPjAJBgNVHRMEAjAAMAsGA1UdDwQEAwIDqDATBgNVHSUE\r\n" +"DDAKBggrBgEFBQcDATAPBgNVHREECDAGhwR/AAABMA0GCSqGSIb3DQEBCwUAA4IB\r\n" +"AQBUw0hbTcT6crzODO4QAXU7z4Xxn0LkxbXEsoThG1QCVgMc4Bhpx8gyz5CLyHYz\r\n" +"AiJOBFEeV0XEqoGTNMMFelR3Q5Tg9y1TYO3qwwAWxe6/brVzpts6NiG1uEMBnBFg\r\n" +"oN1x3I9x4NpOxU5MU1dlIxvKs5HQCoNJ8D0SqOX9BV/pZqwEgiCbuWDWQAlxkFpn\r\n" +"iLonlkVI5hTuybCSBsa9FEI9M6JJn9LZmlH90FYHeS4t6P8eOJCeekHL0jUG4Iae\r\n" +"DMP12h8Sd0yxIKmmZ+Q/p/D/BkuHf5Idv3hgyLkZ4mNznjK49wHaYM+BgBoL3Zeg\r\n" +"gJ2sWjUlokrbHswSBLLbUJIF\r\n" +"-----END CERTIFICATE-----\r\n"; + +const char *server_key = +"-----BEGIN PRIVATE KEY-----\r\n" +"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCujwJbVfTFoaYa\r\n" +"QNozEptdYDkvD6x4DrW2KgatIhDO6oth4mgWfBWAXSMHk9OP7cSIYwFwD+aHvdUC\r\n" +"2FMWYkHGP5qAinv9y9QGmB8sKWZJgvZ9mLoWh3P5/2ZyvLddHDs7q+Vqa1Z9NfxM\r\n" +"CYxJHo9dUEcuCOzmkM4UWas0CwzmwthTX/UwW8TZn0idMjkbjfsgTVZyFFJulh0d\r\n" +"yELf1fOkMagidkHVrc6Fweb7FS0ukwnQbSgTlUUTKdmt5mgQhjgnGylDss+xrL1/\r\n" +"HdOWTT2AQxCBUJ4I2JDBTFl20tq7bHrUs1x1kIo3sVsUsmzO/VTa6C4QuxOaLsTq\r\n" +"ketPOKixAgMBAAECggEAI+uNwpnHirue4Jwjyoqzqd1ZJxQEm5f7UIcJZKsz5kBh\r\n" +"ej0KykWybv27bZ2/1UhKPv6QlyzOdXRc1v8I6fxCKLeB5Z2Zsjo1YT4AfCfwwoPO\r\n" +"kT3SXTx2YyVpQYcP/HsIvVi8FtALtixbxJHaall9iugwHYr8pN17arihAE6d0wZC\r\n" +"JXtXRjUWwjKzXP8FoH4KhyadhHbDwIbbJe3cyLfdvp54Gr0YHha0JcOxYgDYNya4\r\n" +"OKxlCluI+hPF31iNzOmFLQVrdYynyPcR6vY5XOiANKE2iNbqCzRb54CvW9WMqObX\r\n" +"RD9t3DMOxGsbVNIwyzZndWy13HoQMGnrHfnGak9ueQKBgQDiVtOqYfLnUnTxvJ/b\r\n" +"qlQZr2ZmsYPZztxlP+DSqZGPD+WtGSo9+rozWfzjTv3KGIDLvf+GFVmjVHwlLQfd\r\n" +"u7eTemWHFc4HK68wruzPO/FdyVpQ4w9v3Usg+ll4a/PDEId0fDMjAr6kk4LC6t8y\r\n" +"9fJR0HjOz57jVnlrDt3v50G8BwKBgQDFbw+jRiUxXnBbDyXZLi+I4iGBGdC+CbaJ\r\n" +"CmsM6/TsOFc+GRsPwQF1gCGqdaURw76noIVKZJOSc8I+yiwU6izyh/xaju5JiWQd\r\n" +"kwbU1j4DE6GnxmT3ARmB7VvCxjaEZEAtICWs1QTKRz7PcTV8yr7Ng1A3VIy+NSpo\r\n" +"LFMMmk83hwKBgQDVCEwpLg/mUeHoNVVw95w4oLKNLb+gHeerFLiTDy8FrDzM88ai\r\n" +"l37yHly7xflxYia3nZkHpsi7xiUjCINC3BApKyasQoWskh1OgRY653yCfaYYQ96f\r\n" +"t3WjEH9trI2+p6wWo1+uMEMnu/9zXoW9/WeaQdGzNg+igh29+jxCNTPVuQKBgGV4\r\n" +"CN9vI5pV4QTLqjYOSJvfLDz/mYqxz0BrPE1tz3jAFAZ0PLZCCY/sBGFpCScyJQBd\r\n" +"vWNYgYeZOtGuci1llSgov4eDQfBFTlDsyWwFl+VY55IkoqtXw1ZFOQ3HdSlhpKIM\r\n" +"jZBgApA7QYq3sjeqs5lHzahCKftvs5XKgfxOKjxtAoGBALdnYe6xkDvGLvI51Yr+\r\n" +"Dy0TNcB5W84SxUKvM7DVEomy1QPB57ZpyQaoBq7adOz0pWJXfp7qo4950ZOhBGH1\r\n" +"hKbZ6c4ggwVJy2j49EgMok5NGCKvPAtabbR6H8Mz8DW9aXURxhWJvij+Qw1fWK4b\r\n" +"7G/qUI9iE5iUU7MkIcLIbTf/\r\n" +"-----END PRIVATE KEY-----\r\n"; + +const char *index_page = +"\n" +"\n" +"\n" +" \n" +" WebSocket Test\n" +" \n" +" \n" +"\n" +"\n" +"\n" +"\n" +"
\n" +"

Websocket PubSub Demonstration

\n" +"\n" +"

\n" +" This page demonstrates how Mongoose could be used to implement\n" +" \n" +" publish–subscribe pattern. Open this page in several browser\n" +" windows. Each window initiates persistent\n" +" WebSocket\n" +" connection with the server, making each browser window a websocket client.\n" +" Send messages, and see messages sent by other clients.\n" +"

\n" +"\n" +"
\n" +"
\n" +"\n" +"

\n" +" \n" +" \n" +"

\n" +"
\n" +"\n" +"\n"; + +#include + +void broadcast(MongooseHttpWebSocketConnection *from, MongooseString msg) +{ + char buf[500]; + char addr[32]; + mg_sock_addr_to_str(from->getRemoteAddress(), addr, sizeof(addr), + MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + + snprintf(buf, sizeof(buf), "%s %.*s", addr, (int) msg.length(), msg.c_str()); + printf("%s\n", buf); + server.sendAll(from, buf); +} + +void setup() +{ + Serial.begin(115200); + +#ifdef START_ESP_WIFI + 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()); + Serial.print("Hostname: "); +#ifdef ESP32 + Serial.println(WiFi.getHostname()); +#elif defined(ESP8266) + Serial.println(WiFi.hostname()); +#endif +#endif + + Mongoose.begin(); + +#ifdef SIMPLE_SERVER_SECURE + if(false == server.begin(443, server_pem, server_key)) { + Serial.print("Failed to start server"); + return; + } +#else + server.begin(80); +#endif + + server.on("/$", HTTP_GET, [](MongooseHttpServerRequest *request) { + request->send(200, "text/html", index_page); + }); + + // Test the stream response class + server.on("/ws$")-> + onConnect([](MongooseHttpWebSocketConnection *connection) { + broadcast(connection, MongooseString("++ joined")); + })-> + onClose([](MongooseHttpServerRequest *c) { + MongooseHttpWebSocketConnection *connection = static_cast(c); + broadcast(connection, MongooseString("++ left")); + })-> + onFrame([](MongooseHttpWebSocketConnection *connection, int flags, uint8_t *data, size_t len) { + broadcast(connection, MongooseString((const char *)data, len)); + }); +} + +void loop() +{ + Mongoose.poll(1000); + Serial.printf("Free memory %u\n", ESP.getFreeHeap()); +} diff --git a/lib/PsychicHttp/examples/old/websocket_chat/test/README b/lib/PsychicHttp/examples/old/websocket_chat/test/README new file mode 100644 index 0000000..df5066e --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/lib/PsychicHttp/examples/old/websocket_chat/test/tests.rest b/lib/PsychicHttp/examples/old/websocket_chat/test/tests.rest new file mode 100644 index 0000000..4072428 --- /dev/null +++ b/lib/PsychicHttp/examples/old/websocket_chat/test/tests.rest @@ -0,0 +1,35 @@ +# Name: REST Client +# Id: humao.rest-client +# Description: REST Client for Visual Studio Code +# Version: 0.21.3 +# Publisher: Huachao Mao +# VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=humao.rest-client + +@baseUrl = http://172.16.0.87 + +### + +GET {{baseUrl}}/ HTTP/1.1 + +### + +GET {{baseUrl}}/get?message=Hello+World HTTP/1.1 + +### + +POST {{baseUrl}}/post HTTP/1.1 +Content-Type: application/x-www-form-urlencoded;charset=UTF-8 + +message=Hello+World + +### + +GET {{baseUrl}}/someRandomFile HTTP/1.1 + +### + +GET {{baseUrl}}/basic HTTP/1.1 + +### + +GET {{baseUrl}}/stream HTTP/1.1 diff --git a/lib/PsychicHttp/examples/platformio/.gitignore b/lib/PsychicHttp/examples/platformio/.gitignore new file mode 100644 index 0000000..9e5f911 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/lib/PsychicHttp/examples/platformio/data/custom.txt b/lib/PsychicHttp/examples/platformio/data/custom.txt new file mode 100644 index 0000000..d3db23d --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/data/custom.txt @@ -0,0 +1 @@ +Custom text file. \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/data/img/request_flow.png b/lib/PsychicHttp/examples/platformio/data/img/request_flow.png new file mode 100644 index 0000000..1005a38 Binary files /dev/null and b/lib/PsychicHttp/examples/platformio/data/img/request_flow.png differ diff --git a/lib/PsychicHttp/examples/platformio/data/server.crt b/lib/PsychicHttp/examples/platformio/data/server.crt new file mode 100644 index 0000000..34a1e01 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/data/server.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDKzCCAhOgAwIBAgIUBxM3WJf2bP12kAfqhmhhjZWv0ukwDQYJKoZIhvcNAQEL +BQAwJTEjMCEGA1UEAwwaRVNQMzIgSFRUUFMgc2VydmVyIGV4YW1wbGUwHhcNMTgx +MDE3MTEzMjU3WhcNMjgxMDE0MTEzMjU3WjAlMSMwIQYDVQQDDBpFU1AzMiBIVFRQ +UyBzZXJ2ZXIgZXhhbXBsZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALBint6nP77RCQcmKgwPtTsGK0uClxg+LwKJ3WXuye3oqnnjqJCwMEneXzGdG09T +sA0SyNPwrEgebLCH80an3gWU4pHDdqGHfJQa2jBL290e/5L5MB+6PTs2NKcojK/k +qcZkn58MWXhDW1NpAnJtjVniK2Ksvr/YIYSbyD+JiEs0MGxEx+kOl9d7hRHJaIzd +GF/vO2pl295v1qXekAlkgNMtYIVAjUy9CMpqaQBCQRL+BmPSJRkXBsYk8GPnieS4 +sUsp53DsNvCCtWDT6fd9D1v+BB6nDk/FCPKhtjYOwOAZlX4wWNSZpRNr5dfrxKsb +jAn4PCuR2akdF4G8WLUeDWECAwEAAaNTMFEwHQYDVR0OBBYEFMnmdJKOEepXrHI/ +ivM6mVqJgAX8MB8GA1UdIwQYMBaAFMnmdJKOEepXrHI/ivM6mVqJgAX8MA8GA1Ud +EwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBADiXIGEkSsN0SLSfCF1VNWO3 +emBurfOcDq4EGEaxRKAU0814VEmU87btIDx80+z5Dbf+GGHCPrY7odIkxGNn0DJY +W1WcF+DOcbiWoUN6DTkAML0SMnp8aGj9ffx3x+qoggT+vGdWVVA4pgwqZT7Ybntx +bkzcNFW0sqmCv4IN1t4w6L0A87ZwsNwVpre/j6uyBw7s8YoJHDLRFT6g7qgn0tcN +ZufhNISvgWCVJQy/SZjNBHSpnIdCUSJAeTY2mkM4sGxY0Widk8LnjydxZUSxC3Nl +hb6pnMh3jRq4h0+5CZielA4/a+TdrNPv/qok67ot/XJdY3qHCCd8O2b14OVq9jo= +-----END CERTIFICATE----- \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/data/server.key b/lib/PsychicHttp/examples/platformio/data/server.key new file mode 100644 index 0000000..a591325 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/data/server.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwYp7epz++0QkH +JioMD7U7BitLgpcYPi8Cid1l7snt6Kp546iQsDBJ3l8xnRtPU7ANEsjT8KxIHmyw +h/NGp94FlOKRw3ahh3yUGtowS9vdHv+S+TAfuj07NjSnKIyv5KnGZJ+fDFl4Q1tT +aQJybY1Z4itirL6/2CGEm8g/iYhLNDBsRMfpDpfXe4URyWiM3Rhf7ztqZdveb9al +3pAJZIDTLWCFQI1MvQjKamkAQkES/gZj0iUZFwbGJPBj54nkuLFLKedw7DbwgrVg +0+n3fQ9b/gQepw5PxQjyobY2DsDgGZV+MFjUmaUTa+XX68SrG4wJ+DwrkdmpHReB +vFi1Hg1hAgMBAAECggEAaTCnZkl/7qBjLexIryC/CBBJyaJ70W1kQ7NMYfniWwui +f0aRxJgOdD81rjTvkINsPp+xPRQO6oOadjzdjImYEuQTqrJTEUnntbu924eh+2D9 +Mf2CAanj0mglRnscS9mmljZ0KzoGMX6Z/EhnuS40WiJTlWlH6MlQU/FDnwC6U34y +JKy6/jGryfsx+kGU/NRvKSru6JYJWt5v7sOrymHWD62IT59h3blOiP8GMtYKeQlX +49om9Mo1VTIFASY3lrxmexbY+6FG8YO+tfIe0tTAiGrkb9Pz6tYbaj9FjEWOv4Vc ++3VMBUVdGJjgqvE8fx+/+mHo4Rg69BUPfPSrpEg7sQKBgQDlL85G04VZgrNZgOx6 +pTlCCl/NkfNb1OYa0BELqWINoWaWQHnm6lX8YjrUjwRpBF5s7mFhguFjUjp/NW6D +0EEg5BmO0ePJ3dLKSeOA7gMo7y7kAcD/YGToqAaGljkBI+IAWK5Su5yldrECTQKG +YnMKyQ1MWUfCYEwHtPvFvE5aPwKBgQDFBWXekpxHIvt/B41Cl/TftAzE7/f58JjV +MFo/JCh9TDcH6N5TMTRS1/iQrv5M6kJSSrHnq8pqDXOwfHLwxetpk9tr937VRzoL +CuG1Ar7c1AO6ujNnAEmUVC2DppL/ck5mRPWK/kgLwZSaNcZf8sydRgphsW1ogJin +7g0nGbFwXwKBgQCPoZY07Pr1TeP4g8OwWTu5F6dSvdU2CAbtZthH5q98u1n/cAj1 +noak1Srpa3foGMTUn9CHu+5kwHPIpUPNeAZZBpq91uxa5pnkDMp3UrLIRJ2uZyr8 +4PxcknEEh8DR5hsM/IbDcrCJQglM19ZtQeW3LKkY4BsIxjDf45ymH407IQKBgE/g +Ul6cPfOxQRlNLH4VMVgInSyyxWx1mODFy7DRrgCuh5kTVh+QUVBM8x9lcwAn8V9/ +nQT55wR8E603pznqY/jX0xvAqZE6YVPcw4kpZcwNwL1RhEl8GliikBlRzUL3SsW3 +q30AfqEViHPE3XpE66PPo6Hb1ymJCVr77iUuC3wtAoGBAIBrOGunv1qZMfqmwAY2 +lxlzRgxgSiaev0lTNxDzZkmU/u3dgdTwJ5DDANqPwJc6b8SGYTp9rQ0mbgVHnhIB +jcJQBQkTfq6Z0H6OoTVi7dPs3ibQJFrtkoyvYAbyk36quBmNRjVh6rc8468bhXYr +v/t+MeGJP/0Zw8v/X2CFll96 +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/data/www-ap/index.html b/lib/PsychicHttp/examples/platformio/data/www-ap/index.html new file mode 100644 index 0000000..73df596 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/data/www-ap/index.html @@ -0,0 +1,15 @@ + + + + + + PsychicHTTP SoftAP Demo + + + +
+

SoftAP Demo

+

You are connected to the ESP in SoftAP mode.

+
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/data/www/alien.png b/lib/PsychicHttp/examples/platformio/data/www/alien.png new file mode 100644 index 0000000..a030da0 Binary files /dev/null and b/lib/PsychicHttp/examples/platformio/data/www/alien.png differ diff --git a/lib/PsychicHttp/examples/platformio/data/www/favicon.ico b/lib/PsychicHttp/examples/platformio/data/www/favicon.ico new file mode 100644 index 0000000..bdf785c Binary files /dev/null and b/lib/PsychicHttp/examples/platformio/data/www/favicon.ico differ diff --git a/lib/PsychicHttp/examples/platformio/data/www/index.html b/lib/PsychicHttp/examples/platformio/data/www/index.html new file mode 100644 index 0000000..76f14a9 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/data/www/index.html @@ -0,0 +1,236 @@ + + + + + + PsychicHTTP Demo + + + +
+

Basic Request Examples

+ + +

Static Serving

+

+ + +

+

Text File

+ +

Simple POST Form

+
+ + +
+ + +
+ +
+ +

Basic File Upload

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

Multipart POST Form

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

Websocket Demo

+ + + +
+ +
+ + + +

EventSource Demo

+ +
+ +
+ + +
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/data/www/text.txt b/lib/PsychicHttp/examples/platformio/data/www/text.txt new file mode 100644 index 0000000..5375816 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/data/www/text.txt @@ -0,0 +1 @@ +Test File. diff --git a/lib/PsychicHttp/examples/platformio/include/README b/lib/PsychicHttp/examples/platformio/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/platformio/lib/README b/lib/PsychicHttp/examples/platformio/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/platformio/platformio.ini b/lib/PsychicHttp/examples/platformio/platformio.ini new file mode 100644 index 0000000..77a33bc --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/platformio.ini @@ -0,0 +1,30 @@ +; 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 + +[env] +platform = espressif32 +framework = arduino +board = esp32-s3-devkitc-1 +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder +lib_deps = + ; devmode: with this disabled make a symlink from platformio/lib to the PsychicHttp directory + ;hoeken/PsychicHttp + bblanchon/ArduinoJson +board_build.filesystem = littlefs + +[env:default] +build_flags = + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_WARN + ;-D ENABLE_ASYNC + +; [env:arduino3] +; platform = https://github.com/platformio/platform-espressif32.git +; platform_packages = framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32#master \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/src/main.cpp b/lib/PsychicHttp/examples/platformio/src/main.cpp new file mode 100644 index 0000000..eb52479 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/src/main.cpp @@ -0,0 +1,583 @@ +/* + PsychicHTTP Server Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +/********************************************************************************************** +* Note: this demo relies on various files to be uploaded on the LittleFS partition +* PlatformIO -> Build Filesystem Image and then PlatformIO -> Upload Filesystem Image +**********************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "_secret.h" +#include +//#include //uncomment this to enable HTTPS / SSL + +#ifndef WIFI_SSID + #error "You need to enter your wifi credentials. Rename secret.h to _secret.h and enter your credentials there." +#endif + +//Enter your WIFI credentials in secret.h +const char *ssid = WIFI_SSID; +const char *password = WIFI_PASS; + +// Set your SoftAP credentials +const char *softap_ssid = "PsychicHttp"; +const char *softap_password = ""; +IPAddress softap_ip(10, 0, 0, 1); + +//credentials for the /auth-basic and /auth-digest examples +const char *app_user = "admin"; +const char *app_pass = "admin"; +const char *app_name = "Your App"; + +//hostname for mdns (psychic.local) +const char *local_hostname = "psychic"; + +//#define PSY_ENABLE_SSL to enable ssl +#ifdef PSY_ENABLE_SSL + bool app_enable_ssl = true; + String server_cert; + String server_key; +#endif + +//our main server object +#ifdef PSY_ENABLE_SSL + PsychicHttpsServer server; +#else + PsychicHttpServer server; +#endif +PsychicWebSocketHandler websocketHandler; +PsychicEventSource eventSource; + +//NTP server stuff +const char *ntpServer1 = "pool.ntp.org"; +const char *ntpServer2 = "time.nist.gov"; +const long gmtOffset_sec = 0; +const int daylightOffset_sec = 0; +struct tm timeinfo; + +// Callback function (gets called when time adjusts via NTP) +void timeAvailable(struct timeval *t) +{ + if (!getLocalTime(&timeinfo)) { + Serial.println("Failed to obtain time"); + return; + } + + Serial.print("NTP update: "); + char buffer[40]; + strftime(buffer, 40, "%FT%T%z", &timeinfo); + Serial.println(buffer); +} + +bool connectToWifi() +{ + //dual client and AP mode + WiFi.mode(WIFI_AP_STA); + + // Configure SoftAP + WiFi.softAPConfig(softap_ip, softap_ip, IPAddress(255, 255, 255, 0)); // subnet FF FF FF 00 + WiFi.softAP(softap_ssid, softap_password); + IPAddress myIP = WiFi.softAPIP(); + Serial.print("SoftAP IP Address: "); + Serial.println(myIP); + + Serial.println(); + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + // Auto reconnect is set true as default + // To set auto connect off, use the following function + // WiFi.setAutoReconnect(false); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + + // We start by connecting to a WiFi network + // To debug, please enable Core Debug Level to Verbose + if (connectToWifi()) + { + //Setup our NTP to get the current time. + sntp_set_time_sync_notification_cb(timeAvailable); + sntp_servermode_dhcp(1); // (optional) + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2); + + //set up our esp32 to listen on the local_hostname.local domain + if (!MDNS.begin(local_hostname)) { + Serial.println("Error starting mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + //look up our keys? + #ifdef PSY_ENABLE_SSL + if (app_enable_ssl) + { + File fp = LittleFS.open("/server.crt"); + if (fp) + { + server_cert = fp.readString(); + + // Serial.println("Server Cert:"); + // Serial.println(server_cert); + } + else + { + Serial.println("server.pem not found, SSL not available"); + app_enable_ssl = false; + } + fp.close(); + + File fp2 = LittleFS.open("/server.key"); + if (fp2) + { + server_key = fp2.readString(); + + // Serial.println("Server Key:"); + // Serial.println(server_key); + } + else + { + Serial.println("server.key not found, SSL not available"); + app_enable_ssl = false; + } + fp2.close(); + } + #endif + + //setup server config stuff here + server.config.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + + #ifdef PSY_ENABLE_SSL + server.ssl_config.httpd.max_uri_handlers = 20; //maximum number of uri handlers (.on() calls) + + //do we want secure or not? + if (app_enable_ssl) + { + server.listen(443, server_cert.c_str(), server_key.c_str()); + + //this creates a 2nd server listening on port 80 and redirects all requests HTTPS + PsychicHttpServer *redirectServer = new PsychicHttpServer(); + redirectServer->config.ctrl_port = 20424; // just a random port different from the default one + redirectServer->listen(80); + redirectServer->onNotFound([](PsychicRequest *request) { + String url = "https://" + request->host() + request->url(); + return request->redirect(url.c_str()); + }); + } + else + server.listen(80); + #else + server.listen(80); + #endif + + DefaultHeaders::Instance().addHeader("Server", "PsychicHttp"); + + //serve static files from LittleFS/www on / only to clients on same wifi network + //this is where our /index.html file lives + // curl -i http://psychic.local/ + PsychicStaticFileHandler* handler = server.serveStatic("/", LittleFS, "/www/"); + handler->setFilter(ON_STA_FILTER); + handler->setCacheControl("max-age=60"); + + //serve static files from LittleFS/www-ap on / only to clients on SoftAP + //this is where our /index.html file lives + server.serveStatic("/", LittleFS, "/www-ap/")->setFilter(ON_AP_FILTER); + + //serve static files from LittleFS/img on /img + //it's more efficient to serve everything from a single www directory, but this is also possible. + // curl -i http://psychic.local/img/request_flow.png + server.serveStatic("/img", LittleFS, "/img/"); + + //you can also serve single files + // curl -i http://psychic.local/myfile.txt + server.serveStatic("/myfile.txt", LittleFS, "/custom.txt"); + + //example callback everytime a connection is opened + server.onOpen([](PsychicClient *client) { + Serial.printf("[http] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + }); + + //example callback everytime a connection is closed + server.onClose([](PsychicClient *client) { + Serial.printf("[http] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + + //api - json message passed in as post body + // curl -i -X POST -H "Content-Type: application/json" -d '{"foo":"bar"}' http://psychic.local/api + server.on("/api", HTTP_POST, [](PsychicRequest *request, JsonVariant &json) + { + JsonObject input = json.as(); + + //create our response json + PsychicJsonResponse response = PsychicJsonResponse(request); + JsonObject output = response.getRoot(); + + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (input.containsKey("foo")) + { + String foo = input["foo"]; + output["foo"] = foo; + } + + return response.send(); + }); + + //ip - get info about the client + // curl -i http://psychic.local/ip + server.on("/ip", HTTP_GET, [](PsychicRequest *request) + { + String output = "Your IP is: " + request->client()->remoteIP().toString(); + return request->reply(output.c_str()); + }); + + //client connect/disconnect to a url + // curl -i http://psychic.local/handler + PsychicWebHandler *connectionHandler = new PsychicWebHandler(); + connectionHandler->onRequest([](PsychicRequest *request) + { + return request->reply("OK"); + }); + connectionHandler->onOpen([](PsychicClient *client) { + Serial.printf("[handler] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + }); + connectionHandler->onClose([](PsychicClient *client) { + Serial.printf("[handler] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + + //add it to our server + server.on("/handler", connectionHandler); + + //api - parameters passed in via query eg. /api?foo=bar + // curl -i 'http://psychic.local/api?foo=bar' + server.on("/api", HTTP_GET, [](PsychicRequest *request) + { + //showcase some of the variables + Serial.println(request->host()); + Serial.println(request->uri()); + Serial.println(request->path()); + Serial.println(request->queryString()); + + //create a response object + //create our response json + PsychicJsonResponse response = PsychicJsonResponse(request); + JsonObject output = response.getRoot(); + + output["msg"] = "status"; + output["status"] = "success"; + output["millis"] = millis(); + + //work with some params + if (request->hasParam("foo")) + { + String foo = request->getParam("foo")->value(); + output["foo"] = foo; + } + + return response.send(); + }); + + //JsonResponse example + // curl -i http://psychic.local/json + server.on("/json", HTTP_GET, [](PsychicRequest *request) + { + PsychicJsonResponse response = PsychicJsonResponse(request); + + char key[16]; + char value[32]; + JsonObject root = response.getRoot(); + for (int i=0; i<100; i++) + { + sprintf(key, "key%d", i); + sprintf(value, "value is %d", i); + root[key] = value; + } + + return response.send(); + }); + + //how to redirect a request + // curl -i http://psychic.local/redirect + server.on("/redirect", HTTP_GET, [](PsychicRequest *request) + { + return request->redirect("/alien.png"); + }); + + //how to do basic auth + // curl -i --user admin:admin http://psychic.local/auth-basic + server.on("/auth-basic", HTTP_GET, [](PsychicRequest *request) + { + if (!request->authenticate(app_user, app_pass)) + return request->requestAuthentication(BASIC_AUTH, app_name, "You must log in."); + return request->reply("Auth Basic Success!"); + }); + + //how to do digest auth + // curl -i --user admin:admin http://psychic.local/auth-digest + server.on("/auth-digest", HTTP_GET, [](PsychicRequest *request) + { + if (!request->authenticate(app_user, app_pass)) + return request->requestAuthentication(DIGEST_AUTH, app_name, "You must log in."); + return request->reply("Auth Digest Success!"); + }); + + //example of getting / setting cookies + // curl -i -b cookie.txt -c cookie.txt http://psychic.local/cookies + server.on("/cookies", HTTP_GET, [](PsychicRequest *request) + { + PsychicResponse response(request); + + int counter = 0; + if (request->hasCookie("counter")) + { + counter = std::stoi(request->getCookie("counter").c_str()); + counter++; + } + + char cookie[10]; + sprintf(cookie, "%i", counter); + + response.setCookie("counter", cookie); + response.setContent(cookie); + return response.send(); + }); + + //example of getting POST variables + // curl -i -d "param1=value1¶m2=value2" -X POST http://psychic.local/post + server.on("/post", HTTP_POST, [](PsychicRequest *request) + { + String output; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + }); + + //you can set up a custom 404 handler. + // curl -i http://psychic.local/404 + server.onNotFound([](PsychicRequest *request) + { + return request->reply(404, "text/html", "Custom 404 Handler"); + }); + + //handle a very basic upload as post body + PsychicUploadHandler *uploadHandler = new PsychicUploadHandler(); + uploadHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + Serial.printf("Writing %d/%d bytes to: %s\n", (int)index+(int)len, request->contentLength(), path.c_str()); + + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + uploadHandler->onRequest([](PsychicRequest *request) + { + String url = "/" + request->getFilename(); + String output = "" + url + ""; + + return request->reply(output.c_str()); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + // use http://psychic.local/ to test + server.on("/upload/*", HTTP_POST, uploadHandler); + + //a little bit more complicated multipart form + PsychicUploadHandler *multipartHandler = new PsychicUploadHandler(); + multipartHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { + File file; + String path = "/www/" + filename; + + //some progress over serial. + Serial.printf("Writing %d bytes to: %s\n", (int)len, path.c_str()); + if (last) + Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); + + //our first call? + if (!index) + file = LittleFS.open(path, FILE_WRITE); + else + file = LittleFS.open(path, FILE_APPEND); + + if(!file) { + Serial.println("Failed to open file"); + return ESP_FAIL; + } + + if(!file.write(data, len)) { + Serial.println("Write failed"); + return ESP_FAIL; + } + + return ESP_OK; + }); + + //gets called after upload has been handled + multipartHandler->onRequest([](PsychicRequest *request) + { + if (request->hasParam("file_upload")) + { + PsychicWebParameter *file = request->getParam("file_upload"); + + String url = "/" + file->value(); + String output; + + output += "" + url + "
\n"; + output += "Bytes: " + String(file->size()) + "
\n"; + output += "Param 1: " + request->getParam("param1")->value() + "
\n"; + output += "Param 2: " + request->getParam("param2")->value() + "
\n"; + + return request->reply(output.c_str()); + } + else + return request->reply("No upload."); + }); + + //wildcard basic file upload - POST to /upload/filename.ext + // use http://psychic.local/ to test + server.on("/multipart", HTTP_POST, multipartHandler); + + //a websocket echo server + // npm install -g wscat + // wscat -c ws://psychic.local/ws + websocketHandler.onOpen([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + client->sendMessage("Hello!"); + }); + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { + Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char *)frame->payload); + return request->reply(frame); + }); + websocketHandler.onClose([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + server.on("/ws", &websocketHandler); + + //EventSource server + // curl -i -N http://psychic.local/events + eventSource.onOpen([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + client->send("Hello user!", NULL, millis(), 1000); + }); + eventSource.onClose([](PsychicEventSourceClient *client) { + Serial.printf("[eventsource] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + server.on("/events", &eventSource); + } +} + +unsigned long lastUpdate = 0; +char output[60]; + +void loop() +{ + if (millis() - lastUpdate > 2000) + { + sprintf(output, "Millis: %d\n", millis()); + websocketHandler.sendAll(output); + + sprintf(output, "%d", millis()); + eventSource.send(output, "millis", millis(), 0); + + lastUpdate = millis(); + } +} \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/src/secret.h b/lib/PsychicHttp/examples/platformio/src/secret.h new file mode 100644 index 0000000..6d4bb15 --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/src/secret.h @@ -0,0 +1,2 @@ +#define WIFI_SSID "Your_SSID" +#define WIFI_PASS "Your_PASS" \ No newline at end of file diff --git a/lib/PsychicHttp/examples/platformio/test/README b/lib/PsychicHttp/examples/platformio/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/lib/PsychicHttp/examples/platformio/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html diff --git a/lib/PsychicHttp/examples/websockets/.gitignore b/lib/PsychicHttp/examples/websockets/.gitignore new file mode 100644 index 0000000..e37ccaa --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/.gitignore @@ -0,0 +1,8 @@ +.pio +.vscode/ +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch +src/_secret.h +lib/PsychicHttp/ \ No newline at end of file diff --git a/lib/PsychicHttp/examples/websockets/data/www/favicon.ico b/lib/PsychicHttp/examples/websockets/data/www/favicon.ico new file mode 100644 index 0000000..bdf785c Binary files /dev/null and b/lib/PsychicHttp/examples/websockets/data/www/favicon.ico differ diff --git a/lib/PsychicHttp/examples/websockets/data/www/index.html b/lib/PsychicHttp/examples/websockets/data/www/index.html new file mode 100644 index 0000000..c4ba4d9 --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/data/www/index.html @@ -0,0 +1,76 @@ + + + + + + PsychicHTTP Websocket Demo + + + +
+

Websocket Demo

+ + + +
+ +
+ + +
+ + \ No newline at end of file diff --git a/lib/PsychicHttp/examples/websockets/include/README b/lib/PsychicHttp/examples/websockets/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/PsychicHttp/examples/websockets/lib/README b/lib/PsychicHttp/examples/websockets/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/PsychicHttp/examples/websockets/platformio.ini b/lib/PsychicHttp/examples/websockets/platformio.ini new file mode 100644 index 0000000..4849f9e --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/platformio.ini @@ -0,0 +1,25 @@ +; 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 + +[env] +platform = espressif32 +framework = arduino +board = esp32dev +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder +lib_deps = + ; devmode: with this disabled make a symlink from platformio/lib to the PsychicHttp directory + ;hoeken/PsychicHttp + bblanchon/ArduinoJson +board_build.filesystem = littlefs + +[env:default] +build_flags = + -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_WARN \ No newline at end of file diff --git a/lib/PsychicHttp/examples/websockets/src/main.cpp b/lib/PsychicHttp/examples/websockets/src/main.cpp new file mode 100644 index 0000000..a7c79b4 --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/src/main.cpp @@ -0,0 +1,225 @@ +/* + PsychicHTTP Server Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +/********************************************************************************************** +* Note: this demo relies on various files to be uploaded on the LittleFS partition +* PlatformIO -> Build Filesystem Image and then PlatformIO -> Upload Filesystem Image +**********************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "_secret.h" +#include +#include + +#ifndef WIFI_SSID + #error "You need to enter your wifi credentials. Rename secret.h to _secret.h and enter your credentials there." +#endif + +//Enter your WIFI credentials in secret.h +const char *ssid = WIFI_SSID; +const char *password = WIFI_PASS; + +//hostname for mdns (psychic.local) +const char *local_hostname = "psychic"; + +PsychicHttpServer server; +PsychicWebSocketHandler websocketHandler; + +typedef struct { + int socket; + char *buffer; + size_t len; +} WebsocketMessage; + +QueueHandle_t wsMessages; + +bool connectToWifi() +{ + Serial.print("[WiFi] Connecting to "); + Serial.println(ssid); + + //setup our wifi + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + + // Will try for about 10 seconds (20x 500ms) + int tryDelay = 500; + int numberOfTries = 20; + + // Wait for the WiFi event + while (true) + { + switch (WiFi.status()) + { + case WL_NO_SSID_AVAIL: + Serial.println("[WiFi] SSID not found"); + break; + case WL_CONNECT_FAILED: + Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); + return false; + break; + case WL_CONNECTION_LOST: + Serial.println("[WiFi] Connection was lost"); + break; + case WL_SCAN_COMPLETED: + Serial.println("[WiFi] Scan is completed"); + break; + case WL_DISCONNECTED: + Serial.println("[WiFi] WiFi is disconnected"); + break; + case WL_CONNECTED: + Serial.println("[WiFi] WiFi is connected!"); + Serial.print("[WiFi] IP address: "); + Serial.println(WiFi.localIP()); + return true; + break; + default: + Serial.print("[WiFi] WiFi Status: "); + Serial.println(WiFi.status()); + break; + } + delay(tryDelay); + + if (numberOfTries <= 0) + { + Serial.print("[WiFi] Failed to connect to WiFi!"); + // Use disconnect function to force stop trying to connect + WiFi.disconnect(); + return false; + } + else + { + numberOfTries--; + } + } + + return false; +} + +void setup() +{ + Serial.begin(115200); + delay(10); + + //prepare our message queue of 10 messages + wsMessages = xQueueCreate(10, sizeof(WebsocketMessage)); + if (wsMessages == 0) + Serial.printf("Failed to create queue= %p\n", wsMessages); + + // We start by connecting to a WiFi network + // To debug, please enable Core Debug Level to Verbose + if (connectToWifi()) + { + //set up our esp32 to listen on the local_hostname.local domain + if (!MDNS.begin(local_hostname)) { + Serial.println("Error starting mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + + if(!LittleFS.begin()) + { + Serial.println("LittleFS Mount Failed. Do Platform -> Build Filesystem Image and Platform -> Upload Filesystem Image from VSCode"); + return; + } + + server.listen(80); + + //this is where our /index.html file lives + // curl -i http://psychic.local/ + PsychicStaticFileHandler* handler = server.serveStatic("/", LittleFS, "/www/"); + + //a websocket echo server + // npm install -g wscat + // wscat -c ws://psychic.local/ws + websocketHandler.onOpen([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); + client->sendMessage("Hello!"); + }); + websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) + { + Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char *)frame->payload); + + //we are allocating memory here, and the worker will free it + WebsocketMessage wm; + wm.socket = request->client()->socket(); + wm.len = frame->len; + wm.buffer = (char *)malloc(frame->len); + + //did we flame out? + if (wm.buffer == NULL) + { + Serial.printf("Queue message: unable to allocate %d bytes\n", frame->len); + return ESP_FAIL; + } + + //okay, copy it over + memcpy(wm.buffer, frame->payload, frame->len); + + //try to throw it in our queue + if (xQueueSend(wsMessages, &wm, 1) != pdTRUE) + { + Serial.printf("[socket] queue full #%d\n", wm.socket); + + //free the memory... no worker to do it for us. + free(wm.buffer); + } + + //send a throttle message if we're full + if (!uxQueueSpacesAvailable(wsMessages)) + return request->reply("Queue Full"); + + return ESP_OK; + }); + websocketHandler.onClose([](PsychicWebSocketClient *client) { + Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); + }); + server.on("/ws", &websocketHandler); + } +} + +unsigned long lastUpdate = 0; +char output[60]; + +void loop() +{ + //process our websockets outside the callback. + WebsocketMessage message; + while (xQueueReceive(wsMessages, &message, 0) == pdTRUE) + { + //make sure our client is still good. + PsychicWebSocketClient *client = websocketHandler.getClient(message.socket); + if (client == NULL) { + Serial.printf("[socket] client #%d bad, bailing\n", message.socket); + return; + } + + //echo it back to the client. + //alternatively, this is where you would deserialize a json message, parse it, and generate a response if needed + client->sendMessage(HTTPD_WS_TYPE_TEXT, message.buffer, message.len); + + //make sure to release our memory! + free(message.buffer); + } + + //send a periodic update to all clients + if (millis() - lastUpdate > 2000) + { + sprintf(output, "Millis: %d\n", millis()); + websocketHandler.sendAll(output); + + lastUpdate = millis(); + } +} \ No newline at end of file diff --git a/lib/PsychicHttp/examples/websockets/src/secret.h b/lib/PsychicHttp/examples/websockets/src/secret.h new file mode 100644 index 0000000..6d4bb15 --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/src/secret.h @@ -0,0 +1,2 @@ +#define WIFI_SSID "Your_SSID" +#define WIFI_PASS "Your_PASS" \ No newline at end of file diff --git a/lib/PsychicHttp/examples/websockets/test/README b/lib/PsychicHttp/examples/websockets/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/lib/PsychicHttp/examples/websockets/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html diff --git a/lib/PsychicHttp/library.json b/lib/PsychicHttp/library.json new file mode 100644 index 0000000..e732d31 --- /dev/null +++ b/lib/PsychicHttp/library.json @@ -0,0 +1,53 @@ +{ + "name": "PsychicHttp", + "version": "1.2.1", + "description": "Arduino style wrapper around ESP-IDF HTTP library. HTTP server with SSL + websockets. Works on esp32 and probably esp8266", + "keywords": "network,http,https,tcp,ssl,tls,websocket,espasyncwebserver", + "repository": + { + "type": "git", + "url": "https://github.com/hoeken/PsychicHttp" + }, + "authors": + [ + { + "name": "Zach Hoeken", + "email": "hoeken@gmail.com", + "maintainer": true + } + ], + "license" : "MIT", + "examples": [ + { + "name": "platformio", + "base": "examples/platformio", + "files": [ + "src/main.cpp" + ] + } + ], + "frameworks": "arduino", + "platforms": "espressif32", + "dependencies": [ + { + "owner": "bblanchon", + "name": "ArduinoJson", + "version": "^7.0.4" + }, + { + "owner": "plageoj", + "name" : "UrlEncode", + "version" : "^1.0.1" + } + ], + "export": { + "include": [ + "examples/platformio", + "src", + "library.json", + "library.properties", + "LICENSE", + "README.md" + ] + } +} diff --git a/lib/PsychicHttp/library.properties b/lib/PsychicHttp/library.properties new file mode 100644 index 0000000..885afb5 --- /dev/null +++ b/lib/PsychicHttp/library.properties @@ -0,0 +1,11 @@ +name=PsychicHttp +version=1.2.1 +author=Zach Hoeken +maintainer=Zach Hoeken +sentence=PsychicHttp is a robust webserver that supports http/https + websockets. +paragraph=This library is based on the ESP-IDF HTTP Server library which is asynchronous, does http / https+ssl and supports websockets. +category=Communication +architectures=esp32 +url=https://github.com/hoeken/PsychicHttp +includes=PsychicHttp.h +depends=ArduinoJson,UrlEncode \ No newline at end of file diff --git a/lib/PsychicHttp/request flow.drawio b/lib/PsychicHttp/request flow.drawio new file mode 100644 index 0000000..8915583 --- /dev/null +++ b/lib/PsychicHttp/request flow.drawio @@ -0,0 +1 @@ +7Vxbd5s4EP41Pmf3wTkgAcaPza3Zbq/bbNM+yiAbNhi5ICd2f/0KIxmQFIypsZ1jpw+1hBCS5pv5ZgaJHryaLt4maBZ8ID6OesDwFz143QPANIDD/stqlnnNwIJ5xSQJfd6oqPga/sLiTl47D32cVhpSQiIazqqVHolj7NFKHUoS8lxtNiZR9akzNMFKxVcPRWrtQ+jTIK91waCov8PhJBBPNp1hfmWKRGM+kzRAPnkuVcGbHrxKCKH5r+niCkfZ4ol1efhr+RC9f3TevvuS/kT/Xv59//FbP+/sdptb1lNIcExbd+0/B97S/uJ9MrxvX76P0/f9+Gff5MvwhKI5XzA+WboUK5iQeezjrBezBy+fg5DirzPkZVefGWZYXUCnEb+8XiSDFcYkphwRbL3ZRXZbGE9Y0c6uhlF0RSKSrB4Dx3b2j99Vqs//srtpQh5x6Yqz+mNXGq4PX8cnnFC8KKGDr9dbTKaYJkvWRFwVIObYN21efi6QZA95XVBCkevwSsTRO1n3XUiI/eBC0gvsevkufbie3t/Yd9blDfz0bvHQ70NzG4EZVeH8hyldcoGgOSWsiiQ0IBMSo+g9ITPeriQ3Myvj2H+TqSIrjyLiPeZVt2E29NUzWIm3d9eCEtqmoCJCIxxdIu9xshqoEGhMYpx15TP15XMpBndT1LKHsYX8nnV2YYvij/VAWOF6USktRWkR0tJtrPSDDy/7XdyUFcQ9KUUJFXPnI9wObSmZJx6uUUEuP/agCaZ1kueQyhaoFrwJjhANn6r2TwdEfutnErKJrEEPbFgBPRyCahf5jPhdZYOzoSPbkDrKp6x0tNKL9XwaqYpWAODkNaU9UrXtoIpUbTtn10BtajHrRl2Cwd39/WdW8w/+Occp/T2+KwOAzfFyEqE0XRuPWulK/Ocj7I49Lc95Lh6Nu+Q5t6qpQGhqiedMoOE5awc0p52CpQjtB3MiT0x92xLdjtXeaaj2ptlQ7znq+sYFgIZbQV7f5N53WxITTch4nOJ6foKGdVB+shWMfyQKxDej5FUrQTdQ3YhA4c8b+wObVTWxljHYK9gcBWw3sT/jY/yAqBdkELpVTWxApqN52iLwu0XTMMpme4ejJ0xDD2noEkXhJGYFj8kfJ3o0rYNGpyjdr9DLaEINI8dj4Glp1HdGjt1puDiUPGdnoNKooQsXu6JRU40WP6dLLwi9OxT7EVvxs/MjOz+2uUfnRxvpaaR2it5Pi3B9/x6TXoCamH5XLpMNoC25TPtjMcuQWAxILNY2N2ANm9EhwydalpqtGCzVTErQrmSSLRfUj0um6Wp79iMfQVturoVLSd9XjJyxHnAiBqDLEbPUzoSuoOqgaWaH41Ga/ScM+Zm7f4sFZP9sr9ytR4WauLjGYzSPMrgWztvJ87cle12udWE3ZHC7K9mp+YvTi+0KMq5QccHMOyHjjXlzoUdHGBRam4LCpnQKZTo1O4su9Wus5jLOHuur8lib5vZbeKyOpST5Duix2m1VTNJVW3Z9d+Sx2rIqH6XHqqaTPuJnVnGV7+IISax1SA/jnBwyJSS/WXEbJhdAZ26luuMjxQmb0QWJP81wnAkRRdGImcFjkZ9vY9e3dPJzwQh2ugMEwqrpAoODJ4eGivxUx7KgRS9b9dCriqbKw4K2zBJpFRS2iba69O0205bm3VQt6jfSVnlnj0as9m8y1xpWktEWsNqalVw5ISN11LHjB9QgtUQBzJREJH3hxcLJc4Fra1IMe+UCoIapQZ5OYmSwEp2af1qTxQvXBXnUef8nwx6Sb+ZCt2lqQnZTdydzNVQ7Xf4AmrCnVlOOlD9Mw2ob1khGadgwEb8rAhG7GktwvA3jMA2OxXyMXQ/rCWPk2pa9PSjbE8YQNCSMzpxPCGoIg0cPPaC8o0hn2AvHzIoAwzvTw4v0MBCm+HDyVd25kyAH7cZstyE3CKU4Fm4wq6hybPNiWP5rSRTWVt3ujja0smmA0y6Tzes3HK9ub2ibHHV7vapNIZcVq+5kROcHHuTMrt0yGJc7GkCwV6VQXSnGdRQnf/yZ0fI5Bte4VPY+87H6E3iK0DwU55s6znJ7UW4OPLTcVE+YcUnAph16iJ5FVyO6g6ucmvVK8qNAbwoJhiTOZHgc0sMmi1IGOukNnQFE+4xRtNKzzD1K70TzV03PjtYh/kgjlIHV0uFSAmi5o44dLleBYp4N4ScLzwZEY/4HB2du9QVqgtMZiVN8kTLLcZaaRmpu00MR3fnJanRzULu/r+1adfZ8o90fHrfdbxtoy9sdlY52tRdLvPYRzg//FMJL45LbD7bcuzXY8d4tvSKpkcvpKpKhKlLtEY1j1ST56HJTTbLEkQaxed6W7PeONMmxqs8RX815aVxyewjr28vnfKT2HWnSkb0tOagmNd6Of9ya5LTXJAmBg272B8uaIcqvW5PUlIw4p0zprFf6VotxGzFlkrWMebW0qldVl5m/Vin717xKOcSW+cihh6I3/MI09P3VGxed21/VXuVzZ8q30PiIre10r7nbDiTh6T7kAsUOj7I2we3ddlYsvn2XA6H4giC8+R8=7Vtbc5s4FP41ntk+tGMQAvyYOLdNp9NOvTttn3ZkkDGNQA7It/z6FUayBcK3xNhMA34I5+iCdL5P5xwJ0gH9aHGfoMn4C/Ux6Zhdf9EBNx3TNLqmzf9kmmWucSyQK4Ik9EWljWIQvmDZUminoY/TQkVGKWHhpKj0aBxjjxV0KEnovFhtREnxqRMUYE0x8BDRtT9Cn41zrWs6G/0DDoOxfLJh9/KSCMnKYibpGPl0rqjAbQf0E0pZfhct+phkxpN2ue69/J493t0Yzy/92Xf/3v3nKviYd3Z3TJP1FBIcs9N2beZdzxCZCnuJubKlNGBCp7GPs06MDriej0OGBxPkZaVzThmuG7OIiOK1jbpcGNGYCUJwc/NC3iyMAy7CrDQkpE8JTVaPASOY/UQrRZ9fWWuW0CeslNiri5dEdIaGq+FmQ0hwGr6oMmWIKTInOFZl7IeqKHioaA60vkBphhOGFwr3BBr3mEaYJUteRZTyueVNxMoCUBBtvuEpsIVurHDUcoQSibURrPve4M9vBAWOoENPo8MPPHxAsU9w8jZiKFwwuE2uA4LSVPAkR1auTp1GRaL4CLsjr5IQnouHozoRc7sFxCwANcQMswqxugCTA1AQE3Clq2HxUZndPiJkiLynVIOQz5uVFnDBqDGNcQkBoUIkDGIuetzEnBvgOrNiyN3ulSiIQt/PHlNJjA11yn4CVjoRMWKrNmANWFyKbsVS7Dk6sOAEwBqfH8jEnz7+9yv4m4HH5+gruhe+XMWVxt/x8xSn7K8PjVmKELu+VbUUXXMIVr65LsQsGcDlUrQOXIpmXYgZGmIaTDj2r7KUJls3mdFDr4hMcVlwiyXLn6rwKxM+QSneLNTCm6WUFiH7KYMbv1dacWnTKBNkm+NgSuk08fD+OMJQEmC2w2YCC+wXcjgddAVUWIGp1CWYIBbOiplfFdDiCd9oyKercKrk3iEsdpHPW7RSU61yR3axI2Bbn3rqVew2N5PW7YqFayO8nph6jseD+oB6T5i1oX1baLfNM4b2SthARQT4OsFx6/4r3L/dvbT7tyrguktQhFu8qvA6NHOuDS89caZxn9C0xasSL/vSeNnvM73aFdH3pldWs9IroxhiofHa9Ao4uzuqOaFymkLF42i1ly6gWXTpljIy60R0sctp/Ra6cADRUqk2ySqkh/NbDnjruMr1jUJ9fpOP4KTcdf9Q7sJ3wl2zodx1zsBd/XT63wmhyG93sdt2sevIeLFdrORJe5B5YKYNL3+Q+U5PMnf5nL3xR/K8KQGodJQJwYmOMi3rNUeZbw1HcviHhiMIzxCODLPCteURqfVsVZ7t4md0hn5IdyHPdpzN93sfs1nep3sq71Pe6dvnSX+P9jfn2LoZ+pHl7YzzZ5DHsKY4nOZkv845P8+ohkw/tWxf4mwNEM6h79zqCxD68Uj7VmAHYBd/K2Dq28s/JKLbjY7ozqs/jQBbKFRzRHfgcRHdAWeI6GZjdtqnZq/7TthbTmybwt63HcdycfNZe159888B4PZ/ \ No newline at end of file diff --git a/lib/PsychicHttp/src/ChunkPrinter.cpp b/lib/PsychicHttp/src/ChunkPrinter.cpp new file mode 100644 index 0000000..b3f8713 --- /dev/null +++ b/lib/PsychicHttp/src/ChunkPrinter.cpp @@ -0,0 +1,85 @@ + +#include "ChunkPrinter.h" + +ChunkPrinter::ChunkPrinter(PsychicResponse *response, uint8_t *buffer, size_t len) : + _response(response), + _buffer(buffer), + _length(len), + _pos(0) +{} + +ChunkPrinter::~ChunkPrinter() +{ + flush(); +} + +size_t ChunkPrinter::write(uint8_t c) +{ + esp_err_t err; + + //if we're full, send a chunk + if (_pos == _length) + { + _pos = 0; + err = _response->sendChunk(_buffer, _length); + + if (err != ESP_OK) + return 0; + } + + _buffer[_pos] = c; + _pos++; + return 1; +} + +size_t ChunkPrinter::write(const uint8_t *buffer, size_t size) +{ + size_t written = 0; + + while (written < size) + { + size_t space = _length - _pos; + size_t blockSize = std::min(space, size - written); + + memcpy(_buffer + _pos, buffer + written, blockSize); + _pos += blockSize; + + if (_pos == _length) + { + _pos = 0; + + if (_response->sendChunk(_buffer, _length) != ESP_OK) + return written; + } + written += blockSize; //Update if sent correctly. + } + return written; +} + +void ChunkPrinter::flush() +{ + if (_pos) + { + _response->sendChunk(_buffer, _pos); + _pos = 0; + } +} + +size_t ChunkPrinter::copyFrom(Stream &stream) +{ + size_t count = 0; + + while (stream.available()){ + + if (_pos == _length) + { + _response->sendChunk(_buffer, _length); + _pos = 0; + } + + size_t readBytes = stream.readBytes(_buffer + _pos, _length - _pos); + _pos += readBytes; + count += readBytes; + } + return count; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/ChunkPrinter.h b/lib/PsychicHttp/src/ChunkPrinter.h new file mode 100644 index 0000000..f63fac0 --- /dev/null +++ b/lib/PsychicHttp/src/ChunkPrinter.h @@ -0,0 +1,27 @@ +#ifndef ChunkPrinter_h +#define ChunkPrinter_h + +#include "PsychicResponse.h" +#include + +class ChunkPrinter : public Print +{ + private: + PsychicResponse *_response; + uint8_t *_buffer; + size_t _length; + size_t _pos; + + public: + ChunkPrinter(PsychicResponse *response, uint8_t *buffer, size_t len); + ~ChunkPrinter(); + + size_t write(uint8_t c) override; + size_t write(const uint8_t *buffer, size_t size) override; + + size_t copyFrom(Stream &stream); + + void flush() override; +}; + +#endif \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicClient.cpp b/lib/PsychicHttp/src/PsychicClient.cpp new file mode 100644 index 0000000..fd7820d --- /dev/null +++ b/lib/PsychicHttp/src/PsychicClient.cpp @@ -0,0 +1,72 @@ +#include "PsychicClient.h" +#include "PsychicHttpServer.h" +#include + +PsychicClient::PsychicClient(httpd_handle_t server, int socket) : + _server(server), + _socket(socket), + _friend(NULL), + isNew(false) +{} + +PsychicClient::~PsychicClient() { +} + +httpd_handle_t PsychicClient::server() { + return _server; +} + +int PsychicClient::socket() { + return _socket; +} + +// I'm not sure this is entirely safe to call. I was having issues with race conditions when highly loaded using this. +esp_err_t PsychicClient::close() +{ + esp_err_t err = httpd_sess_trigger_close(_server, _socket); + //PsychicHttpServer::closeCallback(_server, _socket); // call this immediately so the client is taken off the list. + + return err; +} + +IPAddress PsychicClient::localIP() +{ + IPAddress address(0,0,0,0); + + char ipstr[INET6_ADDRSTRLEN]; + struct sockaddr_in6 addr; // esp_http_server uses IPv6 addressing + socklen_t addr_size = sizeof(addr); + + if (getsockname(_socket, (struct sockaddr *)&addr, &addr_size) < 0) { + ESP_LOGE(PH_TAG, "Error getting client IP"); + return address; + } + + // Convert to IPv4 string + inet_ntop(AF_INET, &addr.sin6_addr.un.u32_addr[3], ipstr, sizeof(ipstr)); + //ESP_LOGD(PH_TAG, "Client Local IP => %s", ipstr); + address.fromString(ipstr); + + return address; +} + +IPAddress PsychicClient::remoteIP() +{ + IPAddress address(0,0,0,0); + + char ipstr[INET6_ADDRSTRLEN]; + struct sockaddr_in6 addr; // esp_http_server uses IPv6 addressing + socklen_t addr_size = sizeof(addr); + + if (getpeername(_socket, (struct sockaddr *)&addr, &addr_size) < 0) { + ESP_LOGE(PH_TAG, "Error getting client IP"); + return address; + } + + // Convert to IPv4 string + inet_ntop(AF_INET, &addr.sin6_addr.un.u32_addr[3], ipstr, sizeof(ipstr)); + //ESP_LOGD(PH_TAG, "Client Remote IP => %s", ipstr); + address.fromString(ipstr); + + return address; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicClient.h b/lib/PsychicHttp/src/PsychicClient.h new file mode 100644 index 0000000..b823df7 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicClient.h @@ -0,0 +1,35 @@ +#ifndef PsychicClient_h +#define PsychicClient_h + +#include "PsychicCore.h" + +/* +* PsychicClient :: Generic wrapper around the ESP-IDF socket +*/ + +class PsychicClient { + protected: + httpd_handle_t _server; + int _socket; + + public: + PsychicClient(httpd_handle_t server, int socket); + ~PsychicClient(); + + //no idea if this is the right way to do it or not, but lets see. + //pointer to our derived class (eg. PsychicWebSocketConnection) + void *_friend; + + bool isNew = false; + + bool operator==(PsychicClient& rhs) const { return _socket == rhs.socket(); } + + httpd_handle_t server(); + int socket(); + esp_err_t close(); + + IPAddress localIP(); + IPAddress remoteIP(); +}; + +#endif \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicCore.h b/lib/PsychicHttp/src/PsychicCore.h new file mode 100644 index 0000000..fe88b38 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicCore.h @@ -0,0 +1,107 @@ +#ifndef PsychicCore_h +#define PsychicCore_h + +#define PH_TAG "psychic" + +//version numbers +#define PSYCHIC_HTTP_VERSION_MAJOR 1 +#define PSYCHIC_HTTP_VERSION_MINOR 1 +#define PSYCHIC_HTTP_VERSION_PATCH 0 + +#ifndef MAX_COOKIE_SIZE + #define MAX_COOKIE_SIZE 512 +#endif + +#ifndef FILE_CHUNK_SIZE + #define FILE_CHUNK_SIZE 8*1024 +#endif + +#ifndef STREAM_CHUNK_SIZE + #define STREAM_CHUNK_SIZE 1024 +#endif + +#ifndef MAX_UPLOAD_SIZE + #define MAX_UPLOAD_SIZE (2048*1024) // 2MB +#endif + +#ifndef MAX_REQUEST_BODY_SIZE + #define MAX_REQUEST_BODY_SIZE (16*1024) //16K +#endif + +#ifdef ARDUINO + #include +#endif + +#include +#include +#include +#include +#include "esp_random.h" +#include "MD5Builder.h" +#include +#include "FS.h" +#include + +enum HTTPAuthMethod { BASIC_AUTH, DIGEST_AUTH }; + +String urlDecode(const char* encoded); + +class PsychicHttpServer; +class PsychicRequest; +class PsychicWebSocketRequest; +class PsychicClient; + +//filter function definition +typedef std::function PsychicRequestFilterFunction; + +//client connect callback +typedef std::function PsychicClientCallback; + +//callback definitions +typedef std::function PsychicHttpRequestCallback; +typedef std::function PsychicJsonRequestCallback; + +struct HTTPHeader { + char * field; + char * value; +}; + +class DefaultHeaders { + std::list _headers; + +public: + DefaultHeaders() {} + + void addHeader(const String& field, const String& value) + { + addHeader(field.c_str(), value.c_str()); + } + + void addHeader(const char * field, const char * value) + { + HTTPHeader header; + + //these are just going to stick around forever. + header.field =(char *)malloc(strlen(field)+1); + header.value = (char *)malloc(strlen(value)+1); + + strlcpy(header.field, field, strlen(field)+1); + strlcpy(header.value, value, strlen(value)+1); + + _headers.push_back(header); + } + + const std::list& getHeaders() { return _headers; } + + //delete the copy constructor, singleton class + DefaultHeaders(DefaultHeaders const &) = delete; + DefaultHeaders &operator=(DefaultHeaders const &) = delete; + + //single static class interface + static DefaultHeaders &Instance() { + static DefaultHeaders instance; + return instance; + } +}; + +#endif //PsychicCore_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicEndpoint.cpp b/lib/PsychicHttp/src/PsychicEndpoint.cpp new file mode 100644 index 0000000..e692658 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicEndpoint.cpp @@ -0,0 +1,90 @@ +#include "PsychicEndpoint.h" +#include "PsychicHttpServer.h" + +PsychicEndpoint::PsychicEndpoint() : + _server(NULL), + _uri(""), + _method(HTTP_GET), + _handler(NULL) +{ +} + +PsychicEndpoint::PsychicEndpoint(PsychicHttpServer *server, http_method method, const char * uri) : + _server(server), + _uri(uri), + _method(method), + _handler(NULL) +{ +} + +PsychicEndpoint * PsychicEndpoint::setHandler(PsychicHandler *handler) +{ + //clean up old / default handler + if (_handler != NULL) + delete _handler; + + //get our new pointer + _handler = handler; + + //keep a pointer to the server + _handler->_server = _server; + + return this; +} + +PsychicHandler * PsychicEndpoint::handler() +{ + return _handler; +} + +String PsychicEndpoint::uri() { + return _uri; +} + +esp_err_t PsychicEndpoint::requestCallback(httpd_req_t *req) +{ + #ifdef ENABLE_ASYNC + if (is_on_async_worker_thread() == false) { + if (submit_async_req(req, PsychicEndpoint::requestCallback) == ESP_OK) { + return ESP_OK; + } else { + httpd_resp_set_status(req, "503 Busy"); + httpd_resp_sendstr(req, "No workers available. Server busy."); + return ESP_OK; + } + } + #endif + + PsychicEndpoint *self = (PsychicEndpoint *)req->user_ctx; + PsychicHandler *handler = self->handler(); + PsychicRequest request(self->_server, req); + + //make sure we have a handler + if (handler != NULL) + { + if (handler->filter(&request) && handler->canHandle(&request)) + { + //check our credentials + if (handler->needsAuthentication(&request)) + return handler->authenticate(&request); + + //pass it to our handler + return handler->handleRequest(&request); + } + //pass it to our generic handlers + else + return PsychicHttpServer::notFoundHandler(req, HTTPD_500_INTERNAL_SERVER_ERROR); + } + else + return request.reply(500, "text/html", "No handler registered."); +} + +PsychicEndpoint* PsychicEndpoint::setFilter(PsychicRequestFilterFunction fn) { + _handler->setFilter(fn); + return this; +} + +PsychicEndpoint* PsychicEndpoint::setAuthentication(const char *username, const char *password, HTTPAuthMethod method, const char *realm, const char *authFailMsg) { + _handler->setAuthentication(username, password, method, realm, authFailMsg); + return this; +}; \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicEndpoint.h b/lib/PsychicHttp/src/PsychicEndpoint.h new file mode 100644 index 0000000..540b294 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicEndpoint.h @@ -0,0 +1,37 @@ +#ifndef PsychicEndpoint_h +#define PsychicEndpoint_h + +#include "PsychicCore.h" + +class PsychicHandler; + +#ifdef ENABLE_ASYNC + #include "async_worker.h" +#endif + +class PsychicEndpoint +{ + friend PsychicHttpServer; + + private: + PsychicHttpServer *_server; + String _uri; + http_method _method; + PsychicHandler *_handler; + + public: + PsychicEndpoint(); + PsychicEndpoint(PsychicHttpServer *server, http_method method, const char * uri); + + PsychicEndpoint *setHandler(PsychicHandler *handler); + PsychicHandler *handler(); + + PsychicEndpoint* setFilter(PsychicRequestFilterFunction fn); + PsychicEndpoint* setAuthentication(const char *username, const char *password, HTTPAuthMethod method = BASIC_AUTH, const char *realm = "", const char *authFailMsg = ""); + + String uri(); + + static esp_err_t requestCallback(httpd_req_t *req); +}; + +#endif // PsychicEndpoint_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicEventSource.cpp b/lib/PsychicHttp/src/PsychicEventSource.cpp new file mode 100644 index 0000000..25f947d --- /dev/null +++ b/lib/PsychicHttp/src/PsychicEventSource.cpp @@ -0,0 +1,225 @@ +/* + 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 "PsychicEventSource.h" + +/*****************************************/ +// PsychicEventSource - Handler +/*****************************************/ + +PsychicEventSource::PsychicEventSource() : + PsychicHandler(), + _onOpen(NULL), + _onClose(NULL) +{} + +PsychicEventSource::~PsychicEventSource() { +} + +PsychicEventSourceClient * PsychicEventSource::getClient(int socket) +{ + PsychicClient *client = PsychicHandler::getClient(socket); + + if (client == NULL) + return NULL; + + return (PsychicEventSourceClient *)client->_friend; +} + +PsychicEventSourceClient * PsychicEventSource::getClient(PsychicClient *client) { + return getClient(client->socket()); +} + +esp_err_t PsychicEventSource::handleRequest(PsychicRequest *request) +{ + //start our open ended HTTP response + PsychicEventSourceResponse response(request); + esp_err_t err = response.send(); + + //lookup our client + PsychicClient *client = checkForNewClient(request->client()); + if (client->isNew) + { + //did we get our last id? + if(request->hasHeader("Last-Event-ID")) + { + PsychicEventSourceClient *buddy = getClient(client); + buddy->_lastId = atoi(request->header("Last-Event-ID").c_str()); + } + + //let our handler know. + openCallback(client); + } + + return err; +} + +PsychicEventSource * PsychicEventSource::onOpen(PsychicEventSourceClientCallback fn) { + _onOpen = fn; + return this; +} + +PsychicEventSource * PsychicEventSource::onClose(PsychicEventSourceClientCallback fn) { + _onClose = fn; + return this; +} + +void PsychicEventSource::addClient(PsychicClient *client) { + client->_friend = new PsychicEventSourceClient(client); + PsychicHandler::addClient(client); +} + +void PsychicEventSource::removeClient(PsychicClient *client) { + PsychicHandler::removeClient(client); + delete (PsychicEventSourceClient*)client->_friend; + client->_friend = NULL; +} + +void PsychicEventSource::openCallback(PsychicClient *client) { + PsychicEventSourceClient *buddy = getClient(client); + if (buddy == NULL) + { + return; + } + + if (_onOpen != NULL) + _onOpen(buddy); +} + +void PsychicEventSource::closeCallback(PsychicClient *client) { + PsychicEventSourceClient *buddy = getClient(client); + if (buddy == NULL) + { + return; + } + + if (_onClose != NULL) + _onClose(getClient(buddy)); +} + +void PsychicEventSource::send(const char *message, const char *event, uint32_t id, uint32_t reconnect) +{ + String ev = generateEventMessage(message, event, id, reconnect); + for(PsychicClient *c : _clients) { + ((PsychicEventSourceClient*)c->_friend)->sendEvent(ev.c_str()); + } +} + +/*****************************************/ +// PsychicEventSourceClient +/*****************************************/ + +PsychicEventSourceClient::PsychicEventSourceClient(PsychicClient *client) : + PsychicClient(client->server(), client->socket()), + _lastId(0) +{ +} + +PsychicEventSourceClient::~PsychicEventSourceClient(){ +} + +void PsychicEventSourceClient::send(const char *message, const char *event, uint32_t id, uint32_t reconnect){ + String ev = generateEventMessage(message, event, id, reconnect); + sendEvent(ev.c_str()); +} + +void PsychicEventSourceClient::sendEvent(const char *event) { + int result; + do { + result = httpd_socket_send(this->server(), this->socket(), event, strlen(event), 0); + } while (result == HTTPD_SOCK_ERR_TIMEOUT); + + //if (result < 0) + //error log here +} + +/*****************************************/ +// PsychicEventSourceResponse +/*****************************************/ + +PsychicEventSourceResponse::PsychicEventSourceResponse(PsychicRequest *request) + : PsychicResponse(request) +{ +} + +esp_err_t PsychicEventSourceResponse::send() { + + //build our main header + String out = String(); + out.concat("HTTP/1.1 200 OK\r\n"); + out.concat("Content-Type: text/event-stream\r\n"); + out.concat("Cache-Control: no-cache\r\n"); + out.concat("Connection: keep-alive\r\n"); + + //get our global headers out of the way first + for (HTTPHeader header : DefaultHeaders::Instance().getHeaders()) + out.concat(String(header.field) + ": " + String(header.value) + "\r\n"); + + //separator + out.concat("\r\n"); + + int result; + do { + result = httpd_send(_request->request(), out.c_str(), out.length()); + } while (result == HTTPD_SOCK_ERR_TIMEOUT); + + if (result < 0) + ESP_LOGE(PH_TAG, "EventSource send failed with %s", esp_err_to_name(result)); + + if (result > 0) + return ESP_OK; + else + return ESP_ERR_HTTPD_RESP_SEND; +} + +/*****************************************/ +// Event Message Generator +/*****************************************/ + +String generateEventMessage(const char *message, const char *event, uint32_t id, uint32_t reconnect) { + String ev = ""; + + if(reconnect){ + ev += "retry: "; + ev += String(reconnect); + ev += "\r\n"; + } + + if(id){ + ev += "id: "; + ev += String(id); + ev += "\r\n"; + } + + if(event != NULL){ + ev += "event: "; + ev += String(event); + ev += "\r\n"; + } + + if(message != NULL){ + ev += "data: "; + ev += String(message); + ev += "\r\n"; + } + ev += "\r\n"; + + return ev; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicEventSource.h b/lib/PsychicHttp/src/PsychicEventSource.h new file mode 100644 index 0000000..ab31980 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicEventSource.h @@ -0,0 +1,82 @@ +/* + 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 PsychicEventSource_H_ +#define PsychicEventSource_H_ + +#include "PsychicCore.h" +#include "PsychicHandler.h" +#include "PsychicClient.h" +#include "PsychicResponse.h" + +class PsychicEventSource; +class PsychicEventSourceResponse; +class PsychicEventSourceClient; +class PsychicResponse; + +typedef std::function PsychicEventSourceClientCallback; + +class PsychicEventSourceClient : public PsychicClient { + friend PsychicEventSource; + + protected: + uint32_t _lastId; + + public: + PsychicEventSourceClient(PsychicClient *client); + ~PsychicEventSourceClient(); + + uint32_t lastId() const { return _lastId; } + void send(const char *message, const char *event=NULL, uint32_t id=0, uint32_t reconnect=0); + void sendEvent(const char *event); +}; + +class PsychicEventSource : public PsychicHandler { + private: + PsychicEventSourceClientCallback _onOpen; + PsychicEventSourceClientCallback _onClose; + + public: + PsychicEventSource(); + ~PsychicEventSource(); + + PsychicEventSourceClient * getClient(int socket) override; + PsychicEventSourceClient * getClient(PsychicClient *client) override; + void addClient(PsychicClient *client) override; + void removeClient(PsychicClient *client) override; + void openCallback(PsychicClient *client) override; + void closeCallback(PsychicClient *client) override; + + PsychicEventSource *onOpen(PsychicEventSourceClientCallback fn); + PsychicEventSource *onClose(PsychicEventSourceClientCallback fn); + + esp_err_t handleRequest(PsychicRequest *request) override final; + + void send(const char *message, const char *event=NULL, uint32_t id=0, uint32_t reconnect=0); +}; + +class PsychicEventSourceResponse: public PsychicResponse { + public: + PsychicEventSourceResponse(PsychicRequest *request); + virtual esp_err_t send() override; +}; + +String generateEventMessage(const char *message, const char *event, uint32_t id, uint32_t reconnect); + +#endif /* PsychicEventSource_H_ */ \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicFileResponse.cpp b/lib/PsychicHttp/src/PsychicFileResponse.cpp new file mode 100644 index 0000000..5fc9822 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicFileResponse.cpp @@ -0,0 +1,159 @@ +#include "PsychicFileResponse.h" +#include "PsychicResponse.h" +#include "PsychicRequest.h" + + +PsychicFileResponse::PsychicFileResponse(PsychicRequest *request, FS &fs, const String& path, const String& contentType, bool download) + : PsychicResponse(request) { + //_code = 200; + String _path(path); + + if(!download && !fs.exists(_path) && fs.exists(_path+".gz")){ + _path = _path+".gz"; + addHeader("Content-Encoding", "gzip"); + } + + _content = fs.open(_path, "r"); + _contentLength = _content.size(); + + if(contentType == "") + _setContentType(path); + else + setContentType(contentType.c_str()); + + 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(buf, sizeof (buf), "attachment; filename=\"%s\"", filename); + } else { + // set filename and force rendering + snprintf(buf, sizeof (buf), "inline; filename=\"%s\"", filename); + } + addHeader("Content-Disposition", buf); +} + +PsychicFileResponse::PsychicFileResponse(PsychicRequest *request, File content, const String& path, const String& contentType, bool download) + : PsychicResponse(request) { + String _path(path); + + if(!download && String(content.name()).endsWith(".gz") && !path.endsWith(".gz")){ + addHeader("Content-Encoding", "gzip"); + } + + _content = content; + _contentLength = _content.size(); + + if(contentType == "") + _setContentType(path); + else + setContentType(contentType.c_str()); + + int filenameStart = path.lastIndexOf('/') + 1; + char buf[26+path.length()-filenameStart]; + char* filename = (char*)path.c_str() + filenameStart; + + if(download) { + snprintf(buf, sizeof (buf), "attachment; filename=\"%s\"", filename); + } else { + snprintf(buf, sizeof (buf), "inline; filename=\"%s\"", filename); + } + addHeader("Content-Disposition", buf); +} + +PsychicFileResponse::~PsychicFileResponse() +{ + if(_content) + _content.close(); +} + +void PsychicFileResponse::_setContentType(const String& path){ + const char *_contentType; + + if (path.endsWith(".html")) _contentType = "text/html"; + else if (path.endsWith(".htm")) _contentType = "text/html"; + else if (path.endsWith(".css")) _contentType = "text/css"; + else if (path.endsWith(".json")) _contentType = "application/json"; + else if (path.endsWith(".js")) _contentType = "application/javascript"; + else if (path.endsWith(".png")) _contentType = "image/png"; + else if (path.endsWith(".gif")) _contentType = "image/gif"; + else if (path.endsWith(".jpg")) _contentType = "image/jpeg"; + else if (path.endsWith(".ico")) _contentType = "image/x-icon"; + else if (path.endsWith(".svg")) _contentType = "image/svg+xml"; + else if (path.endsWith(".eot")) _contentType = "font/eot"; + else if (path.endsWith(".woff")) _contentType = "font/woff"; + else if (path.endsWith(".woff2")) _contentType = "font/woff2"; + else if (path.endsWith(".ttf")) _contentType = "font/ttf"; + else if (path.endsWith(".xml")) _contentType = "text/xml"; + else if (path.endsWith(".pdf")) _contentType = "application/pdf"; + else if (path.endsWith(".zip")) _contentType = "application/zip"; + else if(path.endsWith(".gz")) _contentType = "application/x-gzip"; + else _contentType = "text/plain"; + + setContentType(_contentType); +} + +esp_err_t PsychicFileResponse::send() +{ + esp_err_t err = ESP_OK; + + //just send small files directly + size_t size = getContentLength(); + if (size < FILE_CHUNK_SIZE) + { + uint8_t *buffer = (uint8_t *)malloc(size); + if (buffer == NULL) + { + /* Respond with 500 Internal Server Error */ + httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); + return ESP_FAIL; + } + + size_t readSize = _content.readBytes((char *)buffer, size); + + this->setContent(buffer, readSize); + err = PsychicResponse::send(); + + free(buffer); + } + else + { + /* Retrieve the pointer to scratch buffer for temporary storage */ + char *chunk = (char *)malloc(FILE_CHUNK_SIZE); + if (chunk == NULL) + { + /* Respond with 500 Internal Server Error */ + httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); + return ESP_FAIL; + } + + this->sendHeaders(); + + size_t chunksize; + do { + /* Read file in chunks into the scratch buffer */ + chunksize = _content.readBytes(chunk, FILE_CHUNK_SIZE); + if (chunksize > 0) + { + err = this->sendChunk((uint8_t *)chunk, chunksize); + if (err != ESP_OK) + break; + } + + /* Keep looping till the whole file is sent */ + } while (chunksize != 0); + + //keep track of our memory + free(chunk); + + if (err == ESP_OK) + { + ESP_LOGD(PH_TAG, "File sending complete"); + this->finishChunking(); + } + } + + return err; +} diff --git a/lib/PsychicHttp/src/PsychicFileResponse.h b/lib/PsychicHttp/src/PsychicFileResponse.h new file mode 100644 index 0000000..8eb75fc --- /dev/null +++ b/lib/PsychicHttp/src/PsychicFileResponse.h @@ -0,0 +1,23 @@ +#ifndef PsychicFileResponse_h +#define PsychicFileResponse_h + +#include "PsychicCore.h" +#include "PsychicResponse.h" + +class PsychicRequest; + +class PsychicFileResponse: public PsychicResponse +{ + using File = fs::File; + using FS = fs::FS; + private: + File _content; + void _setContentType(const String& path); + public: + PsychicFileResponse(PsychicRequest *request, FS &fs, const String& path, const String& contentType=String(), bool download=false); + PsychicFileResponse(PsychicRequest *request, File content, const String& path, const String& contentType=String(), bool download=false); + ~PsychicFileResponse(); + esp_err_t send(); +}; + +#endif // PsychicFileResponse_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHandler.cpp b/lib/PsychicHttp/src/PsychicHandler.cpp new file mode 100644 index 0000000..097b30e --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHandler.cpp @@ -0,0 +1,111 @@ +#include "PsychicHandler.h" + +PsychicHandler::PsychicHandler() : + _filter(NULL), + _server(NULL), + _username(""), + _password(""), + _method(DIGEST_AUTH), + _realm(""), + _authFailMsg(""), + _subprotocol("") + {} + +PsychicHandler::~PsychicHandler() { + // actual PsychicClient deletion handled by PsychicServer + // for (PsychicClient *client : _clients) + // delete(client); + _clients.clear(); +} + +PsychicHandler* PsychicHandler::setFilter(PsychicRequestFilterFunction fn) { + _filter = fn; + return this; +} + +bool PsychicHandler::filter(PsychicRequest *request){ + return _filter == NULL || _filter(request); +} + +void PsychicHandler::setSubprotocol(const String& subprotocol) { + this->_subprotocol = subprotocol; +} +const char* PsychicHandler::getSubprotocol() const { + return _subprotocol.c_str(); +} + +PsychicHandler* PsychicHandler::setAuthentication(const char *username, const char *password, HTTPAuthMethod method, const char *realm, const char *authFailMsg) { + _username = String(username); + _password = String(password); + _method = method; + _realm = String(realm); + _authFailMsg = String(authFailMsg); + return this; +}; + +bool PsychicHandler::needsAuthentication(PsychicRequest *request) { + return (_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()); +} + +esp_err_t PsychicHandler::authenticate(PsychicRequest *request) { + return request->requestAuthentication(_method, _realm.c_str(), _authFailMsg.c_str()); +} + +PsychicClient * PsychicHandler::checkForNewClient(PsychicClient *client) +{ + PsychicClient *c = PsychicHandler::getClient(client); + if (c == NULL) + { + c = client; + addClient(c); + c->isNew = true; + } + else + c->isNew = false; + + return c; +} + +void PsychicHandler::checkForClosedClient(PsychicClient *client) +{ + if (hasClient(client)) + { + closeCallback(client); + removeClient(client); + } +} + +void PsychicHandler::addClient(PsychicClient *client) { + _clients.push_back(client); +} + +void PsychicHandler::removeClient(PsychicClient *client) { + _clients.remove(client); +} + +PsychicClient * PsychicHandler::getClient(int socket) +{ + //make sure the server has it too. + if (!_server->hasClient(socket)) + return NULL; + + //what about us? + for (PsychicClient *client : _clients) + if (client->socket() == socket) + return client; + + //nothing found. + return NULL; +} + +PsychicClient * PsychicHandler::getClient(PsychicClient *client) { + return PsychicHandler::getClient(client->socket()); +} + +bool PsychicHandler::hasClient(PsychicClient *socket) { + return PsychicHandler::getClient(socket) != NULL; +} + +const std::list& PsychicHandler::getClientList() { + return _clients; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHandler.h b/lib/PsychicHttp/src/PsychicHandler.h new file mode 100644 index 0000000..bad62bf --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHandler.h @@ -0,0 +1,66 @@ +#ifndef PsychicHandler_h +#define PsychicHandler_h + +#include "PsychicCore.h" +#include "PsychicRequest.h" + +class PsychicEndpoint; +class PsychicHttpServer; + +/* +* HANDLER :: Can be attached to any endpoint or as a generic request handler. +*/ + +class PsychicHandler { + friend PsychicEndpoint; + + protected: + PsychicRequestFilterFunction _filter; + PsychicHttpServer *_server; + + String _username; + String _password; + HTTPAuthMethod _method; + String _realm; + String _authFailMsg; + + String _subprotocol; + + std::list _clients; + + public: + PsychicHandler(); + virtual ~PsychicHandler(); + + PsychicHandler* setFilter(PsychicRequestFilterFunction fn); + bool filter(PsychicRequest *request); + + PsychicHandler* setAuthentication(const char *username, const char *password, HTTPAuthMethod method = BASIC_AUTH, const char *realm = "", const char *authFailMsg = ""); + bool needsAuthentication(PsychicRequest *request); + esp_err_t authenticate(PsychicRequest *request); + + virtual bool isWebSocket() { return false; }; + + void setSubprotocol(const String& subprotocol); + const char* getSubprotocol() const; + + PsychicClient * checkForNewClient(PsychicClient *client); + void checkForClosedClient(PsychicClient *client); + + virtual void addClient(PsychicClient *client); + virtual void removeClient(PsychicClient *client); + virtual PsychicClient * getClient(int socket); + virtual PsychicClient * getClient(PsychicClient *client); + virtual void openCallback(PsychicClient *client) {}; + virtual void closeCallback(PsychicClient *client) {}; + + bool hasClient(PsychicClient *client); + int count() { return _clients.size(); }; + const std::list& getClientList(); + + //derived classes must implement these functions + virtual bool canHandle(PsychicRequest *request) { return true; }; + virtual esp_err_t handleRequest(PsychicRequest *request) = 0; +}; + +#endif \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHttp.h b/lib/PsychicHttp/src/PsychicHttp.h new file mode 100644 index 0000000..3e9da55 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHttp.h @@ -0,0 +1,24 @@ +#ifndef PsychicHttp_h +#define PsychicHttp_h + +//#define ENABLE_ASYNC // This is something added in ESP-IDF 5.1.x where each request can be handled in its own thread + +#include +#include "PsychicHttpServer.h" +#include "PsychicRequest.h" +#include "PsychicResponse.h" +#include "PsychicEndpoint.h" +#include "PsychicHandler.h" +#include "PsychicStaticFileHandler.h" +#include "PsychicFileResponse.h" +#include "PsychicStreamResponse.h" +#include "PsychicUploadHandler.h" +#include "PsychicWebSocket.h" +#include "PsychicEventSource.h" +#include "PsychicJson.h" + +#ifdef ENABLE_ASYNC + #include "async_worker.h" +#endif + +#endif /* PsychicHttp_h */ \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHttpServer.cpp b/lib/PsychicHttp/src/PsychicHttpServer.cpp new file mode 100644 index 0000000..f6cbb7f --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHttpServer.cpp @@ -0,0 +1,374 @@ +#include "PsychicHttpServer.h" +#include "PsychicEndpoint.h" +#include "PsychicHandler.h" +#include "PsychicWebHandler.h" +#include "PsychicStaticFileHandler.h" +#include "PsychicWebSocket.h" +#include "PsychicJson.h" +#include "WiFi.h" + +PsychicHttpServer::PsychicHttpServer() : + _onOpen(NULL), + _onClose(NULL) +{ + maxRequestBodySize = MAX_REQUEST_BODY_SIZE; + maxUploadSize = MAX_UPLOAD_SIZE; + + defaultEndpoint = new PsychicEndpoint(this, HTTP_GET, ""); + onNotFound(PsychicHttpServer::defaultNotFoundHandler); + + //for a regular server + config = HTTPD_DEFAULT_CONFIG(); + config.open_fn = PsychicHttpServer::openCallback; + config.close_fn = PsychicHttpServer::closeCallback; + config.uri_match_fn = httpd_uri_match_wildcard; + config.global_user_ctx = this; + config.global_user_ctx_free_fn = destroy; + config.max_uri_handlers = 20; + + #ifdef ENABLE_ASYNC + // It is advisable that httpd_config_t->max_open_sockets > MAX_ASYNC_REQUESTS + // Why? This leaves at least one socket still available to handle + // quick synchronous requests. Otherwise, all the sockets will + // get taken by the long async handlers, and your server will no + // longer be responsive. + config.max_open_sockets = ASYNC_WORKER_COUNT + 1; + config.lru_purge_enable = true; + #endif +} + +PsychicHttpServer::~PsychicHttpServer() +{ + for (auto *client : _clients) + delete(client); + _clients.clear(); + + for (auto *endpoint : _endpoints) + delete(endpoint); + _endpoints.clear(); + + for (auto *handler : _handlers) + delete(handler); + _handlers.clear(); + + delete defaultEndpoint; +} + +void PsychicHttpServer::destroy(void *ctx) +{ + // do not release any resource for PsychicHttpServer in order to be able to restart it after stopping +} + +esp_err_t PsychicHttpServer::listen(uint16_t port) +{ + this->_use_ssl = false; + this->config.server_port = port; + + return this->_start(); +} + +esp_err_t PsychicHttpServer::_start() +{ + esp_err_t ret; + + #ifdef ENABLE_ASYNC + // start workers + start_async_req_workers(); + #endif + + //fire it up. + ret = _startServer(); + if (ret != ESP_OK) + { + ESP_LOGE(PH_TAG, "Server start failed (%s)", esp_err_to_name(ret)); + return ret; + } + + // Register handler + ret = httpd_register_err_handler(server, HTTPD_404_NOT_FOUND, PsychicHttpServer::notFoundHandler); + if (ret != ESP_OK) + ESP_LOGE(PH_TAG, "Add 404 handler failed (%s)", esp_err_to_name(ret)); + + return ret; +} + +esp_err_t PsychicHttpServer::_startServer() { + return httpd_start(&this->server, &this->config); +} + +void PsychicHttpServer::stop() +{ + httpd_stop(this->server); +} + +PsychicHandler& PsychicHttpServer::addHandler(PsychicHandler* handler){ + _handlers.push_back(handler); + return *handler; +} + +void PsychicHttpServer::removeHandler(PsychicHandler *handler){ + _handlers.remove(handler); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri) { + return on(uri, HTTP_GET); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method) +{ + PsychicWebHandler *handler = new PsychicWebHandler(); + + return on(uri, method, handler); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, PsychicHandler *handler) +{ + return on(uri, HTTP_GET, handler); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method, PsychicHandler *handler) +{ + //make our endpoint + PsychicEndpoint *endpoint = new PsychicEndpoint(this, method, uri); + + //set our handler + endpoint->setHandler(handler); + + // URI handler structure + httpd_uri_t my_uri { + .uri = uri, + .method = method, + .handler = PsychicEndpoint::requestCallback, + .user_ctx = endpoint, + .is_websocket = handler->isWebSocket(), + .supported_subprotocol = handler->getSubprotocol() + }; + + // Register endpoint with ESP-IDF server + esp_err_t ret = httpd_register_uri_handler(this->server, &my_uri); + if (ret != ESP_OK) + ESP_LOGE(PH_TAG, "Add endpoint failed (%s)", esp_err_to_name(ret)); + + //save it for later + _endpoints.push_back(endpoint); + + return endpoint; +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, PsychicHttpRequestCallback fn) +{ + return on(uri, HTTP_GET, fn); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method, PsychicHttpRequestCallback fn) +{ + //these basic requests need a basic web handler + PsychicWebHandler *handler = new PsychicWebHandler(); + handler->onRequest(fn); + + return on(uri, method, handler); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, PsychicJsonRequestCallback fn) +{ + return on(uri, HTTP_GET, fn); +} + +PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method, PsychicJsonRequestCallback fn) +{ + //these basic requests need a basic web handler + PsychicJsonHandler *handler = new PsychicJsonHandler(); + handler->onRequest(fn); + + return on(uri, method, handler); +} + +void PsychicHttpServer::onNotFound(PsychicHttpRequestCallback fn) +{ + PsychicWebHandler *handler = new PsychicWebHandler(); + handler->onRequest(fn == nullptr ? PsychicHttpServer::defaultNotFoundHandler : fn); + + this->defaultEndpoint->setHandler(handler); +} + +esp_err_t PsychicHttpServer::notFoundHandler(httpd_req_t *req, httpd_err_code_t err) +{ + PsychicHttpServer *server = (PsychicHttpServer*)httpd_get_global_user_ctx(req->handle); + PsychicRequest request(server, req); + + //loop through our global handlers and see if anyone wants it + for(auto *handler: server->_handlers) + { + //are we capable of handling this? + if (handler->filter(&request) && handler->canHandle(&request)) + { + //check our credentials + if (handler->needsAuthentication(&request)) + return handler->authenticate(&request); + else + return handler->handleRequest(&request); + } + } + + //nothing found, give it to our defaultEndpoint + PsychicHandler *handler = server->defaultEndpoint->handler(); + if (handler->filter(&request) && handler->canHandle(&request)) + return handler->handleRequest(&request); + + //not sure how we got this far. + return ESP_ERR_HTTPD_INVALID_REQ; +} + +esp_err_t PsychicHttpServer::defaultNotFoundHandler(PsychicRequest *request) +{ + request->reply(404, "text/html", "That URI does not exist."); + + return ESP_OK; +} + +void PsychicHttpServer::onOpen(PsychicClientCallback handler) { + this->_onOpen = handler; +} + +esp_err_t PsychicHttpServer::openCallback(httpd_handle_t hd, int sockfd) +{ + ESP_LOGD(PH_TAG, "New client connected %d", sockfd); + + //get our global server reference + PsychicHttpServer *server = (PsychicHttpServer*)httpd_get_global_user_ctx(hd); + + //lookup our client + PsychicClient *client = server->getClient(sockfd); + if (client == NULL) + { + client = new PsychicClient(hd, sockfd); + server->addClient(client); + } + + //user callback + if (server->_onOpen != NULL) + server->_onOpen(client); + + return ESP_OK; +} + +void PsychicHttpServer::onClose(PsychicClientCallback handler) { + this->_onClose = handler; +} + +void PsychicHttpServer::closeCallback(httpd_handle_t hd, int sockfd) +{ + ESP_LOGD(PH_TAG, "Client disconnected %d", sockfd); + + PsychicHttpServer *server = (PsychicHttpServer*)httpd_get_global_user_ctx(hd); + + //lookup our client + PsychicClient *client = server->getClient(sockfd); + if (client != NULL) + { + //give our handlers a chance to handle a disconnect first + for (PsychicEndpoint * endpoint : server->_endpoints) + { + PsychicHandler *handler = endpoint->handler(); + handler->checkForClosedClient(client); + } + + //do we have a callback attached? + if (server->_onClose != NULL) + server->_onClose(client); + + //remove it from our list + server->removeClient(client); + } + else + ESP_LOGE(PH_TAG, "No client record %d", sockfd); + + //finally close it out. + close(sockfd); +} + +PsychicStaticFileHandler* PsychicHttpServer::serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control) +{ + PsychicStaticFileHandler* handler = new PsychicStaticFileHandler(uri, fs, path, cache_control); + this->addHandler(handler); + + return handler; +} + +void PsychicHttpServer::addClient(PsychicClient *client) { + _clients.push_back(client); +} + +void PsychicHttpServer::removeClient(PsychicClient *client) { + _clients.remove(client); + delete client; +} + +PsychicClient * PsychicHttpServer::getClient(int socket) { + for (PsychicClient * client : _clients) + if (client->socket() == socket) + return client; + + return NULL; +} + +PsychicClient * PsychicHttpServer::getClient(httpd_req_t *req) { + return getClient(httpd_req_to_sockfd(req)); +} + +bool PsychicHttpServer::hasClient(int socket) { + return getClient(socket) != NULL; +} + +const std::list& PsychicHttpServer::getClientList() { + return _clients; +} + +bool ON_STA_FILTER(PsychicRequest *request) { + #ifndef CONFIG_IDF_TARGET_ESP32H2 + return WiFi.localIP() == request->client()->localIP(); + #else + return false; + #endif +} + +bool ON_AP_FILTER(PsychicRequest *request) { + #ifndef CONFIG_IDF_TARGET_ESP32H2 + return WiFi.softAPIP() == request->client()->localIP(); + #else + return false; + #endif +} + +String urlDecode(const char* encoded) +{ + size_t length = strlen(encoded); + char* decoded = (char*)malloc(length + 1); + if (!decoded) { + return ""; + } + + size_t i, j = 0; + for (i = 0; i < length; ++i) { + if (encoded[i] == '%' && isxdigit(encoded[i + 1]) && isxdigit(encoded[i + 2])) { + // Valid percent-encoded sequence + int hex; + sscanf(encoded + i + 1, "%2x", &hex); + decoded[j++] = (char)hex; + i += 2; // Skip the two hexadecimal characters + } else if (encoded[i] == '+') { + // Convert '+' to space + decoded[j++] = ' '; + } else { + // Copy other characters as they are + decoded[j++] = encoded[i]; + } + } + + decoded[j] = '\0'; // Null-terminate the decoded string + + String output(decoded); + free(decoded); + + return output; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHttpServer.h b/lib/PsychicHttp/src/PsychicHttpServer.h new file mode 100644 index 0000000..40e5442 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHttpServer.h @@ -0,0 +1,81 @@ +#ifndef PsychicHttpServer_h +#define PsychicHttpServer_h + +#include "PsychicCore.h" +#include "PsychicClient.h" +#include "PsychicHandler.h" + +class PsychicEndpoint; +class PsychicHandler; +class PsychicStaticFileHandler; + +class PsychicHttpServer +{ + protected: + bool _use_ssl = false; + std::list _endpoints; + std::list _handlers; + std::list _clients; + + PsychicClientCallback _onOpen; + PsychicClientCallback _onClose; + + esp_err_t _start(); + virtual esp_err_t _startServer(); + + public: + PsychicHttpServer(); + virtual ~PsychicHttpServer(); + + //esp-idf specific stuff + httpd_handle_t server; + httpd_config_t config; + + //some limits on what we will accept + unsigned long maxUploadSize; + unsigned long maxRequestBodySize; + + PsychicEndpoint *defaultEndpoint; + + static void destroy(void *ctx); + + esp_err_t listen(uint16_t port); + + virtual void stop(); + + PsychicHandler& addHandler(PsychicHandler* handler); + void removeHandler(PsychicHandler* handler); + + void addClient(PsychicClient *client); + void removeClient(PsychicClient *client); + PsychicClient* getClient(int socket); + PsychicClient* getClient(httpd_req_t *req); + bool hasClient(int socket); + int count() { return _clients.size(); }; + const std::list& getClientList(); + + PsychicEndpoint* on(const char* uri); + PsychicEndpoint* on(const char* uri, http_method method); + PsychicEndpoint* on(const char* uri, PsychicHandler *handler); + PsychicEndpoint* on(const char* uri, http_method method, PsychicHandler *handler); + PsychicEndpoint* on(const char* uri, PsychicHttpRequestCallback onRequest); + PsychicEndpoint* on(const char* uri, http_method method, PsychicHttpRequestCallback onRequest); + PsychicEndpoint* on(const char* uri, PsychicJsonRequestCallback onRequest); + PsychicEndpoint* on(const char* uri, http_method method, PsychicJsonRequestCallback onRequest); + + static esp_err_t notFoundHandler(httpd_req_t *req, httpd_err_code_t err); + static esp_err_t defaultNotFoundHandler(PsychicRequest *request); + void onNotFound(PsychicHttpRequestCallback fn); + + void onOpen(PsychicClientCallback handler); + void onClose(PsychicClientCallback handler); + static esp_err_t openCallback(httpd_handle_t hd, int sockfd); + static void closeCallback(httpd_handle_t hd, int sockfd); + + PsychicStaticFileHandler* serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control = NULL); +}; + +bool ON_STA_FILTER(PsychicRequest *request); +bool ON_AP_FILTER(PsychicRequest *request); + +#endif // PsychicHttpServer_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHttpsServer.cpp b/lib/PsychicHttp/src/PsychicHttpsServer.cpp new file mode 100644 index 0000000..5df225e --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHttpsServer.cpp @@ -0,0 +1,61 @@ +#include "PsychicHttpsServer.h" + +#ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE + +PsychicHttpsServer::PsychicHttpsServer() : PsychicHttpServer() +{ + //for a SSL server + ssl_config = HTTPD_SSL_CONFIG_DEFAULT(); + ssl_config.httpd.open_fn = PsychicHttpServer::openCallback; + ssl_config.httpd.close_fn = PsychicHttpServer::closeCallback; + ssl_config.httpd.uri_match_fn = httpd_uri_match_wildcard; + ssl_config.httpd.global_user_ctx = this; + ssl_config.httpd.global_user_ctx_free_fn = destroy; + ssl_config.httpd.max_uri_handlers = 20; + + // each SSL connection takes about 45kb of heap + // a barebones sketch with PsychicHttp has ~150kb of heap available + // if we set it higher than 2 and use all the connections, we get lots of memory errors. + // not to mention there is no heap left over for the program itself. + ssl_config.httpd.max_open_sockets = 2; +} + +PsychicHttpsServer::~PsychicHttpsServer() {} + +esp_err_t PsychicHttpsServer::listen(uint16_t port, const char *cert, const char *private_key) +{ + this->_use_ssl = true; + + this->ssl_config.port_secure = port; + +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 2) + this->ssl_config.servercert = (uint8_t *)cert; + this->ssl_config.servercert_len = strlen(cert)+1; +#else + this->ssl_config.cacert_pem = (uint8_t *)cert; + this->ssl_config.cacert_len = strlen(cert)+1; +#endif + + this->ssl_config.prvtkey_pem = (uint8_t *)private_key; + this->ssl_config.prvtkey_len = strlen(private_key)+1; + + return this->_start(); +} + +esp_err_t PsychicHttpsServer::_startServer() +{ + if (this->_use_ssl) + return httpd_ssl_start(&this->server, &this->ssl_config); + else + return httpd_start(&this->server, &this->config); +} + +void PsychicHttpsServer::stop() +{ + if (this->_use_ssl) + httpd_ssl_stop(this->server); + else + httpd_stop(this->server); +} + +#endif // CONFIG_ESP_HTTPS_SERVER_ENABLE \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicHttpsServer.h b/lib/PsychicHttp/src/PsychicHttpsServer.h new file mode 100644 index 0000000..c60b25b --- /dev/null +++ b/lib/PsychicHttp/src/PsychicHttpsServer.h @@ -0,0 +1,38 @@ +#ifndef PsychicHttpsServer_h +#define PsychicHttpsServer_h + +#include + +#ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE + +#include "PsychicCore.h" +#include "PsychicHttpServer.h" +#include +#if !CONFIG_HTTPD_WS_SUPPORT + #error PsychicHttpsServer cannot be used unless HTTPD_WS_SUPPORT is enabled in esp-http-server component configuration +#endif + +#define PSY_ENABLE_SSL //you can use this define in your code to enable/disable these features + +class PsychicHttpsServer : public PsychicHttpServer +{ + protected: + bool _use_ssl = false; + + public: + PsychicHttpsServer(); + ~PsychicHttpsServer(); + + httpd_ssl_config_t ssl_config; + + using PsychicHttpServer::listen; //keep the regular version + esp_err_t listen(uint16_t port, const char *cert, const char *private_key); + + virtual esp_err_t _startServer() override final; + virtual void stop() override final; +}; +#else + #warning ESP-IDF https server support not enabled. +#endif // CONFIG_ESP_HTTPS_SERVER_ENABLE + +#endif // PsychicHttpsServer_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicJson.cpp b/lib/PsychicHttp/src/PsychicJson.cpp new file mode 100644 index 0000000..ca0f0a5 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicJson.cpp @@ -0,0 +1,133 @@ +#include "PsychicJson.h" + +#ifdef ARDUINOJSON_6_COMPATIBILITY + PsychicJsonResponse::PsychicJsonResponse(PsychicRequest *request, bool isArray, size_t maxJsonBufferSize) : + PsychicResponse(request), + _jsonBuffer(maxJsonBufferSize) + { + setContentType(JSON_MIMETYPE); + if (isArray) + _root = _jsonBuffer.createNestedArray(); + else + _root = _jsonBuffer.createNestedObject(); + } +#else + PsychicJsonResponse::PsychicJsonResponse(PsychicRequest *request, bool isArray) : PsychicResponse(request) + { + setContentType(JSON_MIMETYPE); + if (isArray) + _root = _jsonBuffer.add(); + else + _root = _jsonBuffer.add(); + } +#endif + +JsonVariant &PsychicJsonResponse::getRoot() { return _root; } + +size_t PsychicJsonResponse::getLength() +{ + return measureJson(_root); +} + +esp_err_t PsychicJsonResponse::send() +{ + esp_err_t err = ESP_OK; + size_t length = getLength(); + size_t buffer_size; + char *buffer; + + //how big of a buffer do we want? + if (length < JSON_BUFFER_SIZE) + buffer_size = length+1; + else + buffer_size = JSON_BUFFER_SIZE; + + buffer = (char *)malloc(buffer_size); + if (buffer == NULL) { + httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); + return ESP_FAIL; + } + + //send it in one shot or no? + if (length < JSON_BUFFER_SIZE) + { + serializeJson(_root, buffer, buffer_size); + + this->setContent((uint8_t *)buffer, length); + this->setContentType(JSON_MIMETYPE); + + err = PsychicResponse::send(); + } + else + { + //helper class that acts as a stream to print chunked responses + ChunkPrinter dest(this, (uint8_t *)buffer, buffer_size); + + //keep our headers + this->sendHeaders(); + + serializeJson(_root, dest); + + //send the last bits + dest.flush(); + + //done with our chunked response too + err = this->finishChunking(); + } + + //let the buffer go + free(buffer); + + return err; +} + +#ifdef ARDUINOJSON_6_COMPATIBILITY + PsychicJsonHandler::PsychicJsonHandler(size_t maxJsonBufferSize) : + _onRequest(NULL), + _maxJsonBufferSize(maxJsonBufferSize) + {}; + + PsychicJsonHandler::PsychicJsonHandler(PsychicJsonRequestCallback onRequest, size_t maxJsonBufferSize) : + _onRequest(onRequest), + _maxJsonBufferSize(maxJsonBufferSize) + {} +#else + PsychicJsonHandler::PsychicJsonHandler() : + _onRequest(NULL) + {}; + + PsychicJsonHandler::PsychicJsonHandler(PsychicJsonRequestCallback onRequest) : + _onRequest(onRequest) + {} +#endif + +void PsychicJsonHandler::onRequest(PsychicJsonRequestCallback fn) { _onRequest = fn; } + +esp_err_t PsychicJsonHandler::handleRequest(PsychicRequest *request) +{ + //process basic stuff + PsychicWebHandler::handleRequest(request); + + if (_onRequest) + { + #ifdef ARDUINOJSON_6_COMPATIBILITY + DynamicJsonDocument jsonBuffer(this->_maxJsonBufferSize); + DeserializationError error = deserializeJson(jsonBuffer, request->body()); + if (error) + return request->reply(400); + + JsonVariant json = jsonBuffer.as(); + #else + JsonDocument jsonBuffer; + DeserializationError error = deserializeJson(jsonBuffer, request->body()); + if (error) + return request->reply(400); + + JsonVariant json = jsonBuffer.as(); + #endif + + return _onRequest(request, json); + } + else + return request->reply(500); +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicJson.h b/lib/PsychicHttp/src/PsychicJson.h new file mode 100644 index 0000000..95ca894 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicJson.h @@ -0,0 +1,89 @@ +// PsychicJson.h +/* + Async Response to use with ArduinoJson and AsyncWebServer + Written by Andrew Melvin (SticilFace) with help from me-no-dev and BBlanchon. + Ported to PsychicHttp by Zach Hoeken + +*/ +#ifndef PSYCHIC_JSON_H_ +#define PSYCHIC_JSON_H_ + +#include "PsychicRequest.h" +#include "PsychicWebHandler.h" +#include "ChunkPrinter.h" +#include + +#if ARDUINOJSON_VERSION_MAJOR == 6 + #define ARDUINOJSON_6_COMPATIBILITY + #ifndef DYNAMIC_JSON_DOCUMENT_SIZE + #define DYNAMIC_JSON_DOCUMENT_SIZE 4096 + #endif +#endif + + +#ifndef JSON_BUFFER_SIZE + #define JSON_BUFFER_SIZE 4*1024 +#endif + +constexpr const char *JSON_MIMETYPE = "application/json"; + +/* + * Json Response + * */ + +class PsychicJsonResponse : public PsychicResponse +{ + protected: + #ifdef ARDUINOJSON_5_COMPATIBILITY + DynamicJsonBuffer _jsonBuffer; + #elif ARDUINOJSON_VERSION_MAJOR == 6 + DynamicJsonDocument _jsonBuffer; + #else + JsonDocument _jsonBuffer; + #endif + + JsonVariant _root; + size_t _contentLength; + + public: + #ifdef ARDUINOJSON_5_COMPATIBILITY + PsychicJsonResponse(PsychicRequest *request, bool isArray = false); + #elif ARDUINOJSON_VERSION_MAJOR == 6 + PsychicJsonResponse(PsychicRequest *request, bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); + #else + PsychicJsonResponse(PsychicRequest *request, bool isArray = false); + #endif + + ~PsychicJsonResponse() {} + + JsonVariant &getRoot(); + size_t getLength(); + + virtual esp_err_t send() override; +}; + +class PsychicJsonHandler : public PsychicWebHandler +{ + protected: + PsychicJsonRequestCallback _onRequest; + #if ARDUINOJSON_VERSION_MAJOR == 6 + const size_t _maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE; + #endif + + public: + #ifdef ARDUINOJSON_5_COMPATIBILITY + PsychicJsonHandler(); + PsychicJsonHandler(PsychicJsonRequestCallback onRequest); + #elif ARDUINOJSON_VERSION_MAJOR == 6 + PsychicJsonHandler(size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); + PsychicJsonHandler(PsychicJsonRequestCallback onRequest, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); + #else + PsychicJsonHandler(); + PsychicJsonHandler(PsychicJsonRequestCallback onRequest); + #endif + + void onRequest(PsychicJsonRequestCallback fn); + virtual esp_err_t handleRequest(PsychicRequest *request) override; +}; + +#endif \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicRequest.cpp b/lib/PsychicHttp/src/PsychicRequest.cpp new file mode 100644 index 0000000..2005d91 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicRequest.cpp @@ -0,0 +1,559 @@ +#include "PsychicRequest.h" +#include "http_status.h" +#include "PsychicHttpServer.h" + + +PsychicRequest::PsychicRequest(PsychicHttpServer *server, httpd_req_t *req) : + _server(server), + _req(req), + _method(HTTP_GET), + _query(""), + _body(""), + _tempObject(NULL) +{ + //load up our client. + this->_client = server->getClient(req); + + //handle our session data + if (req->sess_ctx != NULL) + this->_session = (SessionData *)req->sess_ctx; + else + { + this->_session = new SessionData(); + req->sess_ctx = this->_session; + } + + //callback for freeing the session later + req->free_ctx = this->freeSession; + + //load up some data + this->_uri = String(this->_req->uri); +} + +PsychicRequest::~PsychicRequest() +{ + //temorary user object + if (_tempObject != NULL) + free(_tempObject); + + //our web parameters + for (auto *param : _params) + delete(param); + _params.clear(); +} + +void PsychicRequest::freeSession(void *ctx) +{ + if (ctx != NULL) + { + SessionData *session = (SessionData*)ctx; + delete session; + } +} + +PsychicHttpServer * PsychicRequest::server() { + return _server; +} + +httpd_req_t * PsychicRequest::request() { + return _req; +} + +PsychicClient * PsychicRequest::client() { + return _client; +} + +const String PsychicRequest::getFilename() +{ + //parse the content-disposition header + if (this->hasHeader("Content-Disposition")) + { + ContentDisposition cd = this->getContentDisposition(); + if (cd.filename != "") + return cd.filename; + } + + //fall back to passed in query string + PsychicWebParameter *param = getParam("_filename"); + if (param != NULL) + return param->name(); + + //fall back to parsing it from url (useful for wildcard uploads) + String uri = this->uri(); + int filenameStart = uri.lastIndexOf('/') + 1; + String filename = uri.substring(filenameStart); + if (filename != "") + return filename; + + //finally, unknown. + ESP_LOGE(PH_TAG, "Did not get a valid filename from the upload."); + return "unknown.txt"; +} + +const ContentDisposition PsychicRequest::getContentDisposition() +{ + ContentDisposition cd; + String header = this->header("Content-Disposition"); + int start; + int end; + + if (header.indexOf("form-data") == 0) + cd.disposition = FORM_DATA; + else if (header.indexOf("attachment") == 0) + cd.disposition = ATTACHMENT; + else if (header.indexOf("inline") == 0) + cd.disposition = INLINE; + else + cd.disposition = NONE; + + start = header.indexOf("filename="); + if (start) + { + end = header.indexOf('"', start+10); + cd.filename = header.substring(start+10, end-1); + } + + start = header.indexOf("name="); + if (start) + { + end = header.indexOf('"', start+6); + cd.name = header.substring(start+6, end-1); + } + + return cd; +} + +esp_err_t PsychicRequest::loadBody() +{ + esp_err_t err = ESP_OK; + + this->_body = String(); + + size_t remaining = this->_req->content_len; + size_t actuallyReceived = 0; + char *buf = (char *)malloc(remaining + 1); + if (buf == NULL) { + ESP_LOGE(PH_TAG, "Failed to allocate memory for body"); + return ESP_FAIL; + } + + while (remaining > 0) { + int received = httpd_req_recv(this->_req, buf + actuallyReceived, remaining); + + if (received == HTTPD_SOCK_ERR_TIMEOUT) { + continue; + } + else if (received == HTTPD_SOCK_ERR_FAIL) { + ESP_LOGE(PH_TAG, "Failed to receive data."); + err = ESP_FAIL; + break; + } + + remaining -= received; + actuallyReceived += received; + } + + buf[actuallyReceived] = '\0'; + this->_body = String(buf); + free(buf); + return err; +} + +http_method PsychicRequest::method() { + return (http_method)this->_req->method; +} + +const String PsychicRequest::methodStr() { + return String(http_method_str((http_method)this->_req->method)); +} + +const String PsychicRequest::path() { + int index = _uri.indexOf("?"); + if(index == -1) + return _uri; + else + return _uri.substring(0, index); +} + +const String& PsychicRequest::uri() { + return this->_uri; +} + +const String& PsychicRequest::query() { + return this->_query; +} + +// no way to get list of headers yet.... +// int PsychicRequest::headers() +// { +// } + +const String PsychicRequest::header(const char *name) +{ + size_t header_len = httpd_req_get_hdr_value_len(this->_req, name); + + //if we've got one, allocated it and load it + if (header_len) + { + char header[header_len+1]; + httpd_req_get_hdr_value_str(this->_req, name, header, sizeof(header)); + return String(header); + } + else + return ""; +} + +bool PsychicRequest::hasHeader(const char *name) +{ + return httpd_req_get_hdr_value_len(this->_req, name) > 0; +} + +const String PsychicRequest::host() { + return this->header("Host"); +} + +const String PsychicRequest::contentType() { + return header("Content-Type"); +} + +size_t PsychicRequest::contentLength() { + return this->_req->content_len; +} + +const String& PsychicRequest::body() +{ + return this->_body; +} + +bool PsychicRequest::isMultipart() +{ + const String& type = this->contentType(); + + return (this->contentType().indexOf("multipart/form-data") >= 0); +} + +esp_err_t PsychicRequest::redirect(const char *url) +{ + PsychicResponse response(this); + response.setCode(301); + response.addHeader("Location", url); + + return response.send(); +} + +bool PsychicRequest::hasCookie(const char *key) +{ + char cookie[MAX_COOKIE_SIZE]; + size_t cookieSize = MAX_COOKIE_SIZE; + esp_err_t err = httpd_req_get_cookie_val(this->_req, key, cookie, &cookieSize); + + //did we get anything? + if (err == ESP_OK) + return true; + else if (err == ESP_ERR_HTTPD_RESULT_TRUNC) + ESP_LOGE(PH_TAG, "cookie too large (%d bytes).\n", cookieSize); + + return false; +} + +const String PsychicRequest::getCookie(const char *key) +{ + char cookie[MAX_COOKIE_SIZE]; + size_t cookieSize = MAX_COOKIE_SIZE; + esp_err_t err = httpd_req_get_cookie_val(this->_req, key, cookie, &cookieSize); + + //did we get anything? + if (err == ESP_OK) + return String(cookie); + else + return ""; +} + +void PsychicRequest::loadParams() +{ + //did we get a query string? + size_t query_len = httpd_req_get_url_query_len(_req); + if (query_len) + { + char query[query_len+1]; + httpd_req_get_url_query_str(_req, query, sizeof(query)); + _query.concat(query); + + //parse them. + _addParams(_query, false); + } + + //did we get form data as body? + if (this->method() == HTTP_POST && this->contentType().startsWith("application/x-www-form-urlencoded")) + { + _addParams(_body, true); + } +} + +void PsychicRequest::_addParams(const String& params, bool post){ + 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(); + addParam(name, value, true, post); + start = end + 1; + } +} + +PsychicWebParameter * PsychicRequest::addParam(const String &name, const String &value, bool decode, bool post) +{ + if (decode) + return addParam(new PsychicWebParameter(urlDecode(name.c_str()), urlDecode(value.c_str()), post)); + else + return addParam(new PsychicWebParameter(name, value, post)); +} + +PsychicWebParameter * PsychicRequest::addParam(PsychicWebParameter *param) { + // ESP_LOGD(PH_TAG, "Adding param: '%s' = '%s'", param->name().c_str(), param->value().c_str()); + _params.push_back(param); + return param; +} + +int PsychicRequest::params() +{ + return _params.size(); +} + +bool PsychicRequest::hasParam(const char *key) +{ + return getParam(key) != NULL; +} + +PsychicWebParameter * PsychicRequest::getParam(const char *key) +{ + for (auto *param : _params) + if (param->name().equals(key)) + return param; + + return NULL; +} + +PsychicWebParameter * PsychicRequest::getParam(int index) +{ + if (_params.size() > index){ + std::list::iterator it = _params.begin(); + for(int i=0; i_session->find(key) != this->_session->end(); +} + +const String PsychicRequest::getSessionKey(const String& key) +{ + auto it = this->_session->find(key); + if (it != this->_session->end()) + return it->second; + else + return ""; +} + +void PsychicRequest::setSessionKey(const String& key, const String& value) +{ + this->_session->insert(std::pair(key, value)); +} + +static const String md5str(const String &in){ + MD5Builder md5 = MD5Builder(); + md5.begin(); + md5.add(in); + md5.calculate(); + return md5.toString(); +} + +bool PsychicRequest::authenticate(const char * username, const char * password) +{ + if(hasHeader("Authorization")) + { + String authReq = header("Authorization"); + if(authReq.startsWith("Basic")){ + authReq = authReq.substring(6); + authReq.trim(); + char toencodeLen = strlen(username)+strlen(password)+1; + char *toencode = new char[toencodeLen + 1]; + if(toencode == NULL){ + authReq = ""; + return false; + } + char *encoded = new char[base64_encode_expected_len(toencodeLen)+1]; + if(encoded == NULL){ + authReq = ""; + delete[] toencode; + return false; + } + sprintf(toencode, "%s:%s", username, password); + if(base64_encode_chars(toencode, toencodeLen, encoded) > 0 && authReq.equalsConstantTime(encoded)) { + authReq = ""; + delete[] toencode; + delete[] encoded; + return true; + } + delete[] toencode; + delete[] encoded; + } + else if(authReq.startsWith(F("Digest"))) + { + authReq = authReq.substring(7); + String _username = _extractParam(authReq,F("username=\""),'\"'); + if(!_username.length() || _username != String(username)) { + authReq = ""; + return false; + } + // extracting required parameters for RFC 2069 simpler Digest + String _realm = _extractParam(authReq, F("realm=\""),'\"'); + String _nonce = _extractParam(authReq, F("nonce=\""),'\"'); + String _uri = _extractParam(authReq, F("uri=\""),'\"'); + String _resp = _extractParam(authReq, F("response=\""),'\"'); + String _opaque = _extractParam(authReq, F("opaque=\""),'\"'); + + if((!_realm.length()) || (!_nonce.length()) || (!_uri.length()) || (!_resp.length()) || (!_opaque.length())) { + authReq = ""; + return false; + } + if((_opaque != this->getSessionKey("opaque")) || (_nonce != this->getSessionKey("nonce")) || (_realm != this->getSessionKey("realm"))) + { + authReq = ""; + return false; + } + // parameters for the RFC 2617 newer Digest + String _nc,_cnonce; + if(authReq.indexOf("qop=auth") != -1 || authReq.indexOf("qop=\"auth\"") != -1) { + _nc = _extractParam(authReq, F("nc="), ','); + _cnonce = _extractParam(authReq, F("cnonce=\""),'\"'); + } + + String _H1 = md5str(String(username) + ':' + _realm + ':' + String(password)); + //ESP_LOGD(PH_TAG, "Hash of user:realm:pass=%s", _H1.c_str()); + + String _H2 = ""; + if(_method == HTTP_GET){ + _H2 = md5str(String(F("GET:")) + _uri); + }else if(_method == HTTP_POST){ + _H2 = md5str(String(F("POST:")) + _uri); + }else if(_method == HTTP_PUT){ + _H2 = md5str(String(F("PUT:")) + _uri); + }else if(_method == HTTP_DELETE){ + _H2 = md5str(String(F("DELETE:")) + _uri); + }else{ + _H2 = md5str(String(F("GET:")) + _uri); + } + //ESP_LOGD(PH_TAG, "Hash of GET:uri=%s", _H2.c_str()); + + String _responsecheck = ""; + if(authReq.indexOf("qop=auth") != -1 || authReq.indexOf("qop=\"auth\"") != -1) { + _responsecheck = md5str(_H1 + ':' + _nonce + ':' + _nc + ':' + _cnonce + F(":auth:") + _H2); + } else { + _responsecheck = md5str(_H1 + ':' + _nonce + ':' + _H2); + } + + //ESP_LOGD(PH_TAG, "The Proper response=%s", _responsecheck.c_str()); + if(_resp == _responsecheck){ + authReq = ""; + return true; + } + } + authReq = ""; + } + return false; +} + +const String PsychicRequest::_extractParam(const String& authReq, const String& param, const char delimit) +{ + int _begin = authReq.indexOf(param); + if (_begin == -1) + return ""; + return authReq.substring(_begin+param.length(),authReq.indexOf(delimit,_begin+param.length())); +} + +const String PsychicRequest::_getRandomHexString() +{ + char buffer[33]; // buffer to hold 32 Hex Digit + /0 + int i; + for(i = 0; i < 4; i++) { + sprintf (buffer + (i*8), "%08lx", (unsigned long int)esp_random()); + } + return String(buffer); +} + +esp_err_t PsychicRequest::requestAuthentication(HTTPAuthMethod mode, const char* realm, const char* authFailMsg) +{ + //what is thy realm, sire? + if(!strcmp(realm, "")) + this->setSessionKey("realm", "Login Required"); + else + this->setSessionKey("realm", realm); + + PsychicResponse response(this); + String authStr; + + //what kind of auth? + if(mode == BASIC_AUTH) + { + authStr = "Basic realm=\"" + this->getSessionKey("realm") + "\""; + response.addHeader("WWW-Authenticate", authStr.c_str()); + } + else + { + //only make new ones if we havent sent them yet + if (this->getSessionKey("nonce").isEmpty()) + this->setSessionKey("nonce", _getRandomHexString()); + if (this->getSessionKey("opaque").isEmpty()) + this->setSessionKey("opaque", _getRandomHexString()); + + authStr = "Digest realm=\"" + this->getSessionKey("realm") + "\", qop=\"auth\", nonce=\"" + this->getSessionKey("nonce") + "\", opaque=\"" + this->getSessionKey("opaque") + "\""; + response.addHeader("WWW-Authenticate", authStr.c_str()); + } + + response.setCode(401); + response.setContentType("text/html"); + response.setContent(authStr.c_str()); + return response.send(); +} + +esp_err_t PsychicRequest::reply(int code) +{ + PsychicResponse response(this); + + response.setCode(code); + response.setContentType("text/plain"); + response.setContent(http_status_reason(code)); + + return response.send(); +} + +esp_err_t PsychicRequest::reply(const char *content) +{ + PsychicResponse response(this); + + response.setCode(200); + response.setContentType("text/html"); + response.setContent(content); + + return response.send(); +} + +esp_err_t PsychicRequest::reply(int code, const char *contentType, const char *content) +{ + PsychicResponse response(this); + + response.setCode(code); + response.setContentType(contentType); + response.setContent(content); + + return response.send(); +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicRequest.h b/lib/PsychicHttp/src/PsychicRequest.h new file mode 100644 index 0000000..5b54d6e --- /dev/null +++ b/lib/PsychicHttp/src/PsychicRequest.h @@ -0,0 +1,100 @@ +#ifndef PsychicRequest_h +#define PsychicRequest_h + +#include "PsychicCore.h" +#include "PsychicHttpServer.h" +#include "PsychicClient.h" +#include "PsychicWebParameter.h" +#include "PsychicResponse.h" + +typedef std::map SessionData; + +enum Disposition { NONE, INLINE, ATTACHMENT, FORM_DATA}; + +struct ContentDisposition { + Disposition disposition; + String filename; + String name; +}; + +class PsychicRequest { + friend PsychicHttpServer; + + protected: + PsychicHttpServer *_server; + httpd_req_t *_req; + SessionData *_session; + PsychicClient *_client; + + http_method _method; + String _uri; + String _query; + String _body; + + std::list _params; + + void _addParams(const String& params, bool post); + void _parseGETParams(); + void _parsePOSTParams(); + + const String _extractParam(const String& authReq, const String& param, const char delimit); + const String _getRandomHexString(); + + public: + PsychicRequest(PsychicHttpServer *server, httpd_req_t *req); + virtual ~PsychicRequest(); + + void *_tempObject; + + PsychicHttpServer * server(); + httpd_req_t * request(); + virtual PsychicClient * client(); + + bool isMultipart(); + esp_err_t loadBody(); + + const String header(const char *name); + bool hasHeader(const char *name); + + static void freeSession(void *ctx); + bool hasSessionKey(const String& key); + const String getSessionKey(const String& key); + void setSessionKey(const String& key, const String& value); + + bool hasCookie(const char * key); + const String getCookie(const char * key); + + http_method method(); // returns the HTTP method used as enum value (eg. HTTP_GET) + const String methodStr(); // returns the HTTP method used as a string (eg. "GET") + const String path(); // returns the request path (eg /page?foo=bar returns "/page") + const String& uri(); // returns the full request uri (eg /page?foo=bar) + const String& query(); // returns the request query data (eg /page?foo=bar returns "foo=bar") + const String host(); // returns the requested host (request to http://psychic.local/foo will return "psychic.local") + const String contentType(); // returns the Content-Type header value + size_t contentLength(); // returns the Content-Length header value + const String& body(); // returns the body of the request + const ContentDisposition getContentDisposition(); + + const String& queryString() { return query(); } //compatability function. same as query() + const String& url() { return uri(); } //compatability function. same as uri() + + void loadParams(); + PsychicWebParameter * addParam(PsychicWebParameter *param); + PsychicWebParameter * addParam(const String &name, const String &value, bool decode = true, bool post = false); + int params(); + bool hasParam(const char *key); + PsychicWebParameter * getParam(const char *name); + PsychicWebParameter * getParam(int index); + + const String getFilename(); + + bool authenticate(const char * username, const char * password); + esp_err_t requestAuthentication(HTTPAuthMethod mode, const char* realm, const char* authFailMsg); + + esp_err_t redirect(const char *url); + esp_err_t reply(int code); + esp_err_t reply(const char *content); + esp_err_t reply(int code, const char *contentType, const char *content); +}; + +#endif // PsychicRequest_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicResponse.cpp b/lib/PsychicHttp/src/PsychicResponse.cpp new file mode 100644 index 0000000..5046441 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicResponse.cpp @@ -0,0 +1,162 @@ +#include "PsychicResponse.h" +#include "PsychicRequest.h" +#include + +PsychicResponse::PsychicResponse(PsychicRequest *request) : + _request(request), + _code(200), + _status(""), + _contentLength(0), + _body("") +{ +} + +PsychicResponse::~PsychicResponse() +{ + //clean up our header variables. we have to do this on desctruct since httpd_resp_send doesn't store copies + for (HTTPHeader header : _headers) + { + free(header.field); + free(header.value); + } + _headers.clear(); +} + +void PsychicResponse::addHeader(const char *field, const char *value) +{ + //these get freed after send by the destructor + HTTPHeader header; + header.field =(char *)malloc(strlen(field)+1); + header.value = (char *)malloc(strlen(value)+1); + + strlcpy(header.field, field, strlen(field)+1); + strlcpy(header.value, value, strlen(value)+1); + + _headers.push_back(header); +} + +void PsychicResponse::setCookie(const char *name, const char *value, unsigned long secondsFromNow, const char *extras) +{ + time_t now = time(nullptr); + + String output; + output = urlEncode(name) + "=" + urlEncode(value); + + //if current time isn't modern, default to using max age + if (now < 1700000000) + output += "; Max-Age=" + String(secondsFromNow); + //otherwise, set an expiration date + else + { + time_t expirationTimestamp = now + secondsFromNow; + + // Convert the expiration timestamp to a formatted string for the "expires" attribute + struct tm* tmInfo = gmtime(&expirationTimestamp); + char expires[30]; + strftime(expires, sizeof(expires), "%a, %d %b %Y %H:%M:%S GMT", tmInfo); + output += "; Expires=" + String(expires); + } + + //did we get any extras? + if (strlen(extras)) + output += "; " + String(extras); + + //okay, add it in. + addHeader("Set-Cookie", output.c_str()); +} + +void PsychicResponse::setCode(int code) +{ + _code = code; +} + +void PsychicResponse::setContentType(const char *contentType) +{ + httpd_resp_set_type(_request->request(), contentType); +} + +void PsychicResponse::setContent(const char *content) +{ + _body = content; + setContentLength(strlen(content)); +} + +void PsychicResponse::setContent(const uint8_t *content, size_t len) +{ + _body = (char *)content; + setContentLength(len); +} + +const char * PsychicResponse::getContent() +{ + return _body; +} + +size_t PsychicResponse::getContentLength() +{ + return _contentLength; +} + +esp_err_t PsychicResponse::send() +{ + //esp-idf makes you set the whole status. + sprintf(_status, "%u %s", _code, http_status_reason(_code)); + httpd_resp_set_status(_request->request(), _status); + + //our headers too + this->sendHeaders(); + + //now send it off + esp_err_t err = httpd_resp_send(_request->request(), getContent(), getContentLength()); + + //did something happen? + if (err != ESP_OK) + ESP_LOGE(PH_TAG, "Send response failed (%s)", esp_err_to_name(err)); + + return err; +} + +void PsychicResponse::sendHeaders() +{ + //get our global headers out of the way first + for (HTTPHeader header : DefaultHeaders::Instance().getHeaders()) + httpd_resp_set_hdr(_request->request(), header.field, header.value); + + //now do our individual headers + for (HTTPHeader header : _headers) + httpd_resp_set_hdr(this->_request->request(), header.field, header.value); + + // DO NOT RELEASE HEADERS HERE... released in the PsychicResponse destructor after they have been sent. + // httpd_resp_set_hdr just passes on the pointer, but its needed after this call. + // clean up our header variables after send + // for (HTTPHeader header : _headers) + // { + // free(header.field); + // free(header.value); + // } + // _headers.clear(); +} + +esp_err_t PsychicResponse::sendChunk(uint8_t *chunk, size_t chunksize) +{ + /* Send the buffer contents as HTTP response chunk */ + esp_err_t err = httpd_resp_send_chunk(this->_request->request(), (char *)chunk, chunksize); + if (err != ESP_OK) + { + ESP_LOGE(PH_TAG, "File sending failed (%s)", esp_err_to_name(err)); + + /* Abort sending file */ + httpd_resp_sendstr_chunk(this->_request->request(), NULL); + + /* Respond with 500 Internal Server Error */ + httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file"); + } + + return err; +} + +esp_err_t PsychicResponse::finishChunking() +{ + /* Respond with an empty chunk to signal HTTP response completion */ + return httpd_resp_send_chunk(this->_request->request(), NULL, 0); +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicResponse.h b/lib/PsychicHttp/src/PsychicResponse.h new file mode 100644 index 0000000..a36de65 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicResponse.h @@ -0,0 +1,46 @@ +#ifndef PsychicResponse_h +#define PsychicResponse_h + +#include "PsychicCore.h" +#include "time.h" + +class PsychicRequest; + +class PsychicResponse +{ + protected: + PsychicRequest *_request; + + int _code; + char _status[60]; + std::list _headers; + int64_t _contentLength; + const char * _body; + + public: + PsychicResponse(PsychicRequest *request); + virtual ~PsychicResponse(); + + void setCode(int code); + + void setContentType(const char *contentType); + void setContentLength(int64_t contentLength) { _contentLength = contentLength; } + int64_t getContentLength(int64_t contentLength) { return _contentLength; } + + void addHeader(const char *field, const char *value); + + void setCookie(const char *key, const char *value, unsigned long max_age = 60*60*24*30, const char *extras = ""); + + void setContent(const char *content); + void setContent(const uint8_t *content, size_t len); + + const char * getContent(); + size_t getContentLength(); + + virtual esp_err_t send(); + void sendHeaders(); + esp_err_t sendChunk(uint8_t *chunk, size_t chunksize); + esp_err_t finishChunking(); +}; + +#endif // PsychicResponse_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicStaticFileHander.cpp b/lib/PsychicHttp/src/PsychicStaticFileHander.cpp new file mode 100644 index 0000000..54fafc4 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicStaticFileHander.cpp @@ -0,0 +1,181 @@ +#include "PsychicStaticFileHandler.h" + +/*************************************/ +/* PsychicStaticFileHandler */ +/*************************************/ + +PsychicStaticFileHandler::PsychicStaticFileHandler(const char* uri, FS& fs, const char* path, const char* cache_control) + : _fs(fs), _uri(uri), _path(path), _default_file("index.html"), _cache_control(cache_control), _last_modified("") +{ + // Ensure leading '/' + if (_uri.length() == 0 || _uri[0] != '/') _uri = "/" + _uri; + if (_path.length() == 0 || _path[0] != '/') _path = "/" + _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; +} + +PsychicStaticFileHandler& PsychicStaticFileHandler::setIsDir(bool isDir){ + _isDir = isDir; + return *this; +} + +PsychicStaticFileHandler& PsychicStaticFileHandler::setDefaultFile(const char* filename){ + _default_file = String(filename); + return *this; +} + +PsychicStaticFileHandler& PsychicStaticFileHandler::setCacheControl(const char* cache_control){ + _cache_control = String(cache_control); + return *this; +} + +PsychicStaticFileHandler& PsychicStaticFileHandler::setLastModified(const char* last_modified){ + _last_modified = String(last_modified); + return *this; +} + +PsychicStaticFileHandler& PsychicStaticFileHandler::setLastModified(struct tm* last_modified){ + char result[30]; + strftime (result,30,"%a, %d %b %Y %H:%M:%S %Z", last_modified); + return setLastModified((const char *)result); +} + +bool PsychicStaticFileHandler::canHandle(PsychicRequest *request) +{ + if(request->method() != HTTP_GET || !request->uri().startsWith(_uri) ) + return false; + + if (_getFile(request)) + return true; + + return false; +} + +bool PsychicStaticFileHandler::_getFile(PsychicRequest *request) +{ + // Remove the found uri + String path = request->uri().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(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 += "/"; + path += _default_file; + + return _fileExists(path); +} + +#define FILE_IS_REAL(f) (f == true && !f.isDirectory()) + +bool PsychicStaticFileHandler::_fileExists(const String& path) +{ + bool fileFound = false; + bool gzipFound = false; + + String gzip = path + ".gz"; + + if (_gzipFirst) { + _file = _fs.open(gzip, "r"); + gzipFound = FILE_IS_REAL(_file); + if (!gzipFound){ + _file = _fs.open(path, "r"); + fileFound = FILE_IS_REAL(_file); + } + } else { + _file = _fs.open(path, "r"); + fileFound = FILE_IS_REAL(_file); + if (!fileFound){ + _file = _fs.open(gzip, "r"); + gzipFound = FILE_IS_REAL(_file); + } + } + + bool found = fileFound || gzipFound; + + if (found) + { + _filename = path; + + // 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 PsychicStaticFileHandler::_countBits(const uint8_t value) const +{ + uint8_t w = value; + uint8_t n; + for (n=0; w!=0; n++) w&=w-1; + return n; +} + +esp_err_t PsychicStaticFileHandler::handleRequest(PsychicRequest *request) +{ + if (_file == true) + { + //is it not modified? + String etag = String(_file.size()); + if (_last_modified.length() && _last_modified == request->header("If-Modified-Since")) + { + _file.close(); + request->reply(304); // Not modified + } + //does our Etag match? + else if (_cache_control.length() && request->hasHeader("If-None-Match") && request->header("If-None-Match").equals(etag)) + { + _file.close(); + + PsychicResponse response(request); + response.addHeader("Cache-Control", _cache_control.c_str()); + response.addHeader("ETag", etag.c_str()); + response.setCode(304); + response.send(); + } + //nope, send them the full file. + else + { + PsychicFileResponse response(request, _fs, _filename); + + if (_last_modified.length()) + response.addHeader("Last-Modified", _last_modified.c_str()); + if (_cache_control.length()) { + response.addHeader("Cache-Control", _cache_control.c_str()); + response.addHeader("ETag", etag.c_str()); + } + + return response.send(); + } + } else { + return request->reply(404); + } + + return ESP_OK; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicStaticFileHandler.h b/lib/PsychicHttp/src/PsychicStaticFileHandler.h new file mode 100644 index 0000000..f757111 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicStaticFileHandler.h @@ -0,0 +1,41 @@ +#ifndef PsychicStaticFileHandler_h +#define PsychicStaticFileHandler_h + +#include "PsychicCore.h" +#include "PsychicWebHandler.h" +#include "PsychicRequest.h" +#include "PsychicResponse.h" +#include "PsychicFileResponse.h" + +class PsychicStaticFileHandler : public PsychicWebHandler { + using File = fs::File; + using FS = fs::FS; + private: + bool _getFile(PsychicRequest *request); + bool _fileExists(const String& path); + uint8_t _countBits(const uint8_t value) const; + protected: + FS _fs; + File _file; + String _filename; + String _uri; + String _path; + String _default_file; + String _cache_control; + String _last_modified; + bool _isDir; + bool _gzipFirst; + uint8_t _gzipStats; + public: + PsychicStaticFileHandler(const char* uri, FS& fs, const char* path, const char* cache_control); + bool canHandle(PsychicRequest *request) override; + esp_err_t handleRequest(PsychicRequest *request) override; + PsychicStaticFileHandler& setIsDir(bool isDir); + PsychicStaticFileHandler& setDefaultFile(const char* filename); + PsychicStaticFileHandler& setCacheControl(const char* cache_control); + PsychicStaticFileHandler& setLastModified(const char* last_modified); + PsychicStaticFileHandler& setLastModified(struct tm* last_modified); + //PsychicStaticFileHandler& setTemplateProcessor(AwsTemplateProcessor newCallback) {_callback = newCallback; return *this;} +}; + +#endif /* PsychicHttp_h */ \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicStreamResponse.cpp b/lib/PsychicHttp/src/PsychicStreamResponse.cpp new file mode 100644 index 0000000..5132104 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicStreamResponse.cpp @@ -0,0 +1,94 @@ +#include "PsychicStreamResponse.h" +#include "PsychicResponse.h" +#include "PsychicRequest.h" + +PsychicStreamResponse::PsychicStreamResponse(PsychicRequest *request, const String& contentType) + : PsychicResponse(request), _buffer(NULL) { + + setContentType(contentType.c_str()); + addHeader("Content-Disposition", "inline"); +} + + +PsychicStreamResponse::PsychicStreamResponse(PsychicRequest *request, const String& contentType, const String& name) + : PsychicResponse(request), _buffer(NULL) { + + setContentType(contentType.c_str()); + + char buf[26+name.length()]; + snprintf(buf, sizeof (buf), "attachment; filename=\"%s\"", name.c_str()); + addHeader("Content-Disposition", buf); +} + + +PsychicStreamResponse::~PsychicStreamResponse() +{ + endSend(); +} + + +esp_err_t PsychicStreamResponse::beginSend() +{ + if(_buffer) + return ESP_OK; + + //Buffer to hold ChunkPrinter and stream buffer. Using placement new will keep us at a single allocation. + _buffer = (uint8_t*)malloc(STREAM_CHUNK_SIZE + sizeof(ChunkPrinter)); + + if(!_buffer) + { + /* Respond with 500 Internal Server Error */ + httpd_resp_send_err(_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); + return ESP_FAIL; + } + + _printer = new (_buffer) ChunkPrinter(this, _buffer + sizeof(ChunkPrinter), STREAM_CHUNK_SIZE); + + sendHeaders(); + return ESP_OK; +} + + +esp_err_t PsychicStreamResponse::endSend() +{ + esp_err_t err = ESP_OK; + + if(!_buffer) + err = ESP_FAIL; + else + { + _printer->~ChunkPrinter(); //flushed on destruct + err = finishChunking(); + free(_buffer); + _buffer = NULL; + } + return err; +} + + +void PsychicStreamResponse::flush() +{ + if(_buffer) + _printer->flush(); +} + + +size_t PsychicStreamResponse::write(uint8_t data) +{ + return _buffer ? _printer->write(data) : 0; +} + + +size_t PsychicStreamResponse::write(const uint8_t *buffer, size_t size) +{ + return _buffer ? _printer->write(buffer, size) : 0; +} + + +size_t PsychicStreamResponse::copyFrom(Stream &stream) +{ + if(_buffer) + return _printer->copyFrom(stream); + + return 0; +} diff --git a/lib/PsychicHttp/src/PsychicStreamResponse.h b/lib/PsychicHttp/src/PsychicStreamResponse.h new file mode 100644 index 0000000..888ec9c --- /dev/null +++ b/lib/PsychicHttp/src/PsychicStreamResponse.h @@ -0,0 +1,35 @@ +#ifndef PsychicStreamResponse_h +#define PsychicStreamResponse_h + +#include "PsychicCore.h" +#include "PsychicResponse.h" +#include "ChunkPrinter.h" + +class PsychicRequest; + +class PsychicStreamResponse : public PsychicResponse, public Print +{ + private: + ChunkPrinter *_printer; + uint8_t *_buffer; + public: + + PsychicStreamResponse(PsychicRequest *request, const String& contentType); + PsychicStreamResponse(PsychicRequest *request, const String& contentType, const String& name); //Download + + ~PsychicStreamResponse(); + + esp_err_t beginSend(); + esp_err_t endSend(); + + void flush() override; + + size_t write(uint8_t data) override; + size_t write(const uint8_t *buffer, size_t size) override; + + size_t copyFrom(Stream &stream); + + using Print::write; +}; + +#endif // PsychicStreamResponse_h diff --git a/lib/PsychicHttp/src/PsychicUploadHandler.cpp b/lib/PsychicHttp/src/PsychicUploadHandler.cpp new file mode 100644 index 0000000..d8a55e3 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicUploadHandler.cpp @@ -0,0 +1,395 @@ +#include "PsychicUploadHandler.h" + +PsychicUploadHandler::PsychicUploadHandler() : + PsychicWebHandler() + , _temp() + , _parsedLength(0) + , _multiParseState(EXPECT_BOUNDARY) + , _boundaryPosition(0) + , _itemStartIndex(0) + , _itemSize(0) + , _itemName() + , _itemFilename() + , _itemType() + , _itemValue() + , _itemBuffer(0) + , _itemBufferIndex(0) + , _itemIsFile(false) + {} +PsychicUploadHandler::~PsychicUploadHandler() {} + +bool PsychicUploadHandler::canHandle(PsychicRequest *request) { + return true; +} + +esp_err_t PsychicUploadHandler::handleRequest(PsychicRequest *request) +{ + esp_err_t err = ESP_OK; + + //save it for later (multipart) + _request = request; + _parsedLength = 0; + /* File cannot be larger than a limit */ + if (request->contentLength() > request->server()->maxUploadSize) + { + ESP_LOGE(PH_TAG, "File too large : %d bytes", request->contentLength()); + + /* Respond with 400 Bad Request */ + char error[50]; + sprintf(error, "File size must be less than %lu bytes!", request->server()->maxUploadSize); + httpd_resp_send_err(request->request(), HTTPD_400_BAD_REQUEST, error); + + /* Return failure to close underlying connection else the incoming file content will keep the socket busy */ + return ESP_FAIL; + } + + //we might want to access some of these params + request->loadParams(); + + //TODO: support for the 100 header. not sure if we can do it. + // if (request->header("Expect").equals("100-continue")) + // { + // char response[] = "100 Continue"; + // httpd_socket_send(self->server, httpd_req_to_sockfd(req), response, strlen(response), 0); + // } + + //2 types of upload requests + if (request->isMultipart()) + err = _multipartUploadHandler(request); + else + err = _basicUploadHandler(request); + + //we can also call onRequest for some final processing and response + if (err == ESP_OK) + { + if (_requestCallback != NULL) + err = _requestCallback(request); + else + err = request->reply("Upload Successful."); + } + else + request->reply(500, "text/html", "Error processing upload."); + + return err; +} + +esp_err_t PsychicUploadHandler::_basicUploadHandler(PsychicRequest *request) +{ + esp_err_t err = ESP_OK; + + String filename = request->getFilename(); + + /* Retrieve the pointer to scratch buffer for temporary storage */ + char *buf = (char *)malloc(FILE_CHUNK_SIZE); + int received; + unsigned long index = 0; + + /* Content length of the request gives the size of the file being uploaded */ + int remaining = request->contentLength(); + + while (remaining > 0) + { + #ifdef ENABLE_ASYNC + httpd_sess_update_lru_counter(request->server()->server, request->client()->socket()); + #endif + + //ESP_LOGD(PH_TAG, "Remaining size : %d", remaining); + + /* Receive the file part by part into a buffer */ + if ((received = httpd_req_recv(request->request(), buf, min(remaining, FILE_CHUNK_SIZE))) <= 0) + { + /* Retry if timeout occurred */ + if (received == HTTPD_SOCK_ERR_TIMEOUT) + continue; + //bail if we got an error + else if (received == HTTPD_SOCK_ERR_FAIL) + { + ESP_LOGE(PH_TAG, "Socket error"); + err = ESP_FAIL; + break; + } + } + + //call our upload callback here. + if (_uploadCallback != NULL) + { + err = _uploadCallback(request, filename, index, (uint8_t *)buf, received, (remaining - received == 0)); + if (err != ESP_OK) + break; + } + else + { + ESP_LOGE(PH_TAG, "No upload callback specified!"); + err = ESP_FAIL; + break; + } + + /* Keep track of remaining size of the file left to be uploaded */ + remaining -= received; + index += received; + } + + //dont forget to free our buffer + free(buf); + + return err; +} + +esp_err_t PsychicUploadHandler::_multipartUploadHandler(PsychicRequest *request) +{ + esp_err_t err = ESP_OK; + + String value = request->header("Content-Type"); + if (value.startsWith("multipart/")){ + _boundary = value.substring(value.indexOf('=')+1); + _boundary.replace("\"",""); + } else { + ESP_LOGE(PH_TAG, "No multipart boundary found."); + return request->reply(400, "text/html", "No multipart boundary found."); + } + + char *buf = (char *)malloc(FILE_CHUNK_SIZE); + int received; + unsigned long index = 0; + + /* Content length of the request gives the size of the file being uploaded */ + int remaining = request->contentLength(); + + while (remaining > 0) + { + #ifdef ENABLE_ASYNC + httpd_sess_update_lru_counter(request->server()->server, request->client()->socket()); + #endif + + //ESP_LOGD(PH_TAG, "Remaining size : %d", remaining); + + /* Receive the file part by part into a buffer */ + if ((received = httpd_req_recv(request->request(), buf, min(remaining, FILE_CHUNK_SIZE))) <= 0) + { + /* Retry if timeout occurred */ + if (received == HTTPD_SOCK_ERR_TIMEOUT) + continue; + //bail if we got an error + else if (received == HTTPD_SOCK_ERR_FAIL) + { + ESP_LOGE(PH_TAG, "Socket error"); + err = ESP_FAIL; + break; + } + } + + //parse it 1 byte at a time. + for (int i=0; i 12 && _temp.substring(0, 12).equalsIgnoreCase("Content-Type")){ + _itemType = _temp.substring(14); + _itemIsFile = true; + } else if(_temp.length() > 19 && _temp.substring(0, 19).equalsIgnoreCase("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 == "name"){ + _itemName = nameVal; + } else if(name == "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 == "name"){ + _itemName = nameVal; + } else if(name == "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(FILE_CHUNK_SIZE); + if(_itemBuffer == NULL){ + ESP_LOGE(PH_TAG, "Multipart: Failed to allocate buffer"); + _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){ + _request->addParam(_itemName, _itemValue); + //_addParam(new AsyncWebParameter(_itemName, _itemValue, true)); + } else { + if(_itemSize){ + if(_uploadCallback) + _uploadCallback(_request, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, true); + _itemBufferIndex = 0; + _request->addParam(new PsychicWebParameter(_itemName, _itemFilename, true, true, _itemSize)); + } + free(_itemBuffer); + _itemBuffer = NULL; + } + + } else { + _boundaryPosition++; + } + } else if(_multiParseState == DASH3_OR_RETURN2){ + if(data == '-' && (_request->contentLength() - _parsedLength - 4) != 0){ + ESP_LOGE(PH_TAG, "ERROR: The parser got to the end of the POST but is expecting more bytes!"); + _multiParseState = PARSE_ERROR; + return; + } + if(data == '\r'){ + _multiParseState = EXPECT_FEED2; + } else if(data == '-' && _request->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); + } + } +} diff --git a/lib/PsychicHttp/src/PsychicUploadHandler.h b/lib/PsychicHttp/src/PsychicUploadHandler.h new file mode 100644 index 0000000..59e62b6 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicUploadHandler.h @@ -0,0 +1,68 @@ +#ifndef PsychicUploadHandler_h +#define PsychicUploadHandler_h + +#include "PsychicCore.h" +#include "PsychicHttpServer.h" +#include "PsychicRequest.h" +#include "PsychicWebHandler.h" +#include "PsychicWebParameter.h" + +//callback definitions +typedef std::function PsychicUploadCallback; + +/* +* HANDLER :: Can be attached to any endpoint or as a generic request handler. +*/ + +class PsychicUploadHandler : public PsychicWebHandler { + protected: + PsychicUploadCallback _uploadCallback; + + PsychicRequest *_request; + + String _temp; + size_t _parsedLength; + uint8_t _multiParseState; + String _boundary; + 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; + + esp_err_t _basicUploadHandler(PsychicRequest *request); + esp_err_t _multipartUploadHandler(PsychicRequest *request); + + void _handleUploadByte(uint8_t data, bool last); + void _parseMultipartPostByte(uint8_t data, bool last); + + public: + PsychicUploadHandler(); + ~PsychicUploadHandler(); + + bool canHandle(PsychicRequest *request) override; + esp_err_t handleRequest(PsychicRequest *request) override; + + PsychicUploadHandler * onUpload(PsychicUploadCallback fn); +}; + +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 +}; + +#endif // PsychicUploadHandler_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicWebHandler.cpp b/lib/PsychicHttp/src/PsychicWebHandler.cpp new file mode 100644 index 0000000..1e4997e --- /dev/null +++ b/lib/PsychicHttp/src/PsychicWebHandler.cpp @@ -0,0 +1,74 @@ +#include "PsychicWebHandler.h" + +PsychicWebHandler::PsychicWebHandler() : + PsychicHandler(), + _requestCallback(NULL), + _onOpen(NULL), + _onClose(NULL) + {} +PsychicWebHandler::~PsychicWebHandler() {} + +bool PsychicWebHandler::canHandle(PsychicRequest *request) { + return true; +} + +esp_err_t PsychicWebHandler::handleRequest(PsychicRequest *request) +{ + //lookup our client + PsychicClient *client = checkForNewClient(request->client()); + if (client->isNew) + openCallback(client); + + /* Request body cannot be larger than a limit */ + if (request->contentLength() > request->server()->maxRequestBodySize) + { + ESP_LOGE(PH_TAG, "Request body too large : %d bytes", request->contentLength()); + + /* Respond with 400 Bad Request */ + char error[60]; + sprintf(error, "Request body must be less than %lu bytes!", request->server()->maxRequestBodySize); + httpd_resp_send_err(request->request(), HTTPD_400_BAD_REQUEST, error); + + /* Return failure to close underlying connection else the incoming file content will keep the socket busy */ + return ESP_FAIL; + } + + //get our body loaded up. + esp_err_t err = request->loadBody(); + if (err != ESP_OK) + return err; + + //load our params in. + request->loadParams(); + + //okay, pass on to our callback. + if (this->_requestCallback != NULL) + err = this->_requestCallback(request); + + return err; +} + +PsychicWebHandler * PsychicWebHandler::onRequest(PsychicHttpRequestCallback fn) { + _requestCallback = fn; + return this; +} + +void PsychicWebHandler::openCallback(PsychicClient *client) { + if (_onOpen != NULL) + _onOpen(client); +} + +void PsychicWebHandler::closeCallback(PsychicClient *client) { + if (_onClose != NULL) + _onClose(getClient(client)); +} + +PsychicWebHandler * PsychicWebHandler::onOpen(PsychicClientCallback fn) { + _onOpen = fn; + return this; +} + +PsychicWebHandler * PsychicWebHandler::onClose(PsychicClientCallback fn) { + _onClose = fn; + return this; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicWebHandler.h b/lib/PsychicHttp/src/PsychicWebHandler.h new file mode 100644 index 0000000..07a6780 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicWebHandler.h @@ -0,0 +1,34 @@ +#ifndef PsychicWebHandler_h +#define PsychicWebHandler_h + +// #include "PsychicCore.h" +// #include "PsychicHttpServer.h" +// #include "PsychicRequest.h" +#include "PsychicHandler.h" + +/* +* HANDLER :: Can be attached to any endpoint or as a generic request handler. +*/ + +class PsychicWebHandler : public PsychicHandler { + protected: + PsychicHttpRequestCallback _requestCallback; + PsychicClientCallback _onOpen; + PsychicClientCallback _onClose; + + public: + PsychicWebHandler(); + ~PsychicWebHandler(); + + virtual bool canHandle(PsychicRequest *request) override; + virtual esp_err_t handleRequest(PsychicRequest *request) override; + PsychicWebHandler * onRequest(PsychicHttpRequestCallback fn); + + virtual void openCallback(PsychicClient *client); + virtual void closeCallback(PsychicClient *client); + + PsychicWebHandler *onOpen(PsychicClientCallback fn); + PsychicWebHandler *onClose(PsychicClientCallback fn); +}; + +#endif \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicWebParameter.h b/lib/PsychicHttp/src/PsychicWebParameter.h new file mode 100644 index 0000000..e09136b --- /dev/null +++ b/lib/PsychicHttp/src/PsychicWebParameter.h @@ -0,0 +1,25 @@ +#ifndef PsychicWebParameter_h +#define PsychicWebParameter_h + +/* + * PARAMETER :: Chainable object to hold GET/POST and FILE parameters + * */ + +class PsychicWebParameter { + private: + String _name; + String _value; + size_t _size; + bool _isForm; + bool _isFile; + + public: + PsychicWebParameter(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; } +}; + +#endif //PsychicWebParameter_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/PsychicWebSocket.cpp b/lib/PsychicHttp/src/PsychicWebSocket.cpp new file mode 100644 index 0000000..7a3c6b1 --- /dev/null +++ b/lib/PsychicHttp/src/PsychicWebSocket.cpp @@ -0,0 +1,258 @@ +#include "PsychicWebSocket.h" + +/*************************************/ +/* PsychicWebSocketRequest */ +/*************************************/ + +PsychicWebSocketRequest::PsychicWebSocketRequest(PsychicRequest *req) : + PsychicRequest(req->server(), req->request()), + _client(req->client()) +{ +} + +PsychicWebSocketRequest::~PsychicWebSocketRequest() +{ +} + +PsychicWebSocketClient * PsychicWebSocketRequest::client() { + return &_client; +} + +esp_err_t PsychicWebSocketRequest::reply(httpd_ws_frame_t * ws_pkt) +{ + return httpd_ws_send_frame(this->_req, ws_pkt); +} + +esp_err_t PsychicWebSocketRequest::reply(httpd_ws_type_t op, const void *data, size_t len) +{ + httpd_ws_frame_t ws_pkt; + memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); + + ws_pkt.payload = (uint8_t*)data; + ws_pkt.len = len; + ws_pkt.type = op; + + return this->reply(&ws_pkt); +} + +esp_err_t PsychicWebSocketRequest::reply(const char *buf) +{ + return this->reply(HTTPD_WS_TYPE_TEXT, buf, strlen(buf)); +} + +/*************************************/ +/* PsychicWebSocketClient */ +/*************************************/ + +PsychicWebSocketClient::PsychicWebSocketClient(PsychicClient *client) + : PsychicClient(client->server(), client->socket()) +{ +} + +PsychicWebSocketClient::~PsychicWebSocketClient() { +} + +esp_err_t PsychicWebSocketClient::sendMessage(httpd_ws_frame_t * ws_pkt) +{ + return httpd_ws_send_frame_async(this->server(), this->socket(), ws_pkt); +} + +esp_err_t PsychicWebSocketClient::sendMessage(httpd_ws_type_t op, const void *data, size_t len) +{ + httpd_ws_frame_t ws_pkt; + memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); + + ws_pkt.payload = (uint8_t*)data; + ws_pkt.len = len; + ws_pkt.type = op; + + return this->sendMessage(&ws_pkt); +} + +esp_err_t PsychicWebSocketClient::sendMessage(const char *buf) +{ + return this->sendMessage(HTTPD_WS_TYPE_TEXT, buf, strlen(buf)); +} + +PsychicWebSocketHandler::PsychicWebSocketHandler() : + PsychicHandler(), + _onOpen(NULL), + _onFrame(NULL), + _onClose(NULL) + { + } + +PsychicWebSocketHandler::~PsychicWebSocketHandler() { +} + +PsychicWebSocketClient * PsychicWebSocketHandler::getClient(int socket) +{ + PsychicClient *client = PsychicHandler::getClient(socket); + if (client == NULL) + return NULL; + + if (client->_friend == NULL) + { + return NULL; + } + + return (PsychicWebSocketClient *)client->_friend; +} + +PsychicWebSocketClient * PsychicWebSocketHandler::getClient(PsychicClient *client) { + return getClient(client->socket()); +} + +void PsychicWebSocketHandler::addClient(PsychicClient *client) { + client->_friend = new PsychicWebSocketClient(client); + PsychicHandler::addClient(client); +} + +void PsychicWebSocketHandler::removeClient(PsychicClient *client) { + PsychicHandler::removeClient(client); + delete (PsychicWebSocketClient*)client->_friend; + client->_friend = NULL; +} + +void PsychicWebSocketHandler::openCallback(PsychicClient *client) { + PsychicWebSocketClient *buddy = getClient(client); + if (buddy == NULL) + { + return; + } + + if (_onOpen != NULL) + _onOpen(getClient(buddy)); +} + +void PsychicWebSocketHandler::closeCallback(PsychicClient *client) { + PsychicWebSocketClient *buddy = getClient(client); + if (buddy == NULL) + { + return; + } + + if (_onClose != NULL) + _onClose(getClient(buddy)); +} + +bool PsychicWebSocketHandler::isWebSocket() { return true; } + +esp_err_t PsychicWebSocketHandler::handleRequest(PsychicRequest *request) +{ + //lookup our client + PsychicClient *client = checkForNewClient(request->client()); + + // beginning of the ws URI handler and our onConnect hook + if (request->method() == HTTP_GET) + { + if (client->isNew) + openCallback(client); + + return ESP_OK; + } + + //prep our request + PsychicWebSocketRequest wsRequest(request); + + //init our memory for storing the packet + httpd_ws_frame_t ws_pkt; + memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); + ws_pkt.type = HTTPD_WS_TYPE_TEXT; + uint8_t *buf = NULL; + + /* Set max_len = 0 to get the frame len */ + esp_err_t ret = httpd_ws_recv_frame(wsRequest.request(), &ws_pkt, 0); + if (ret != ESP_OK) { + ESP_LOGE(PH_TAG, "httpd_ws_recv_frame failed to get frame len with %s", esp_err_to_name(ret)); + return ret; + } + + //okay, now try to load the packet + //ESP_LOGD(PH_TAG, "frame len is %d", ws_pkt.len); + if (ws_pkt.len) { + /* ws_pkt.len + 1 is for NULL termination as we are expecting a string */ + buf = (uint8_t*) calloc(1, ws_pkt.len + 1); + if (buf == NULL) { + ESP_LOGE(PH_TAG, "Failed to calloc memory for buf"); + return ESP_ERR_NO_MEM; + } + ws_pkt.payload = buf; + /* Set max_len = ws_pkt.len to get the frame payload */ + ret = httpd_ws_recv_frame(wsRequest.request(), &ws_pkt, ws_pkt.len); + if (ret != ESP_OK) { + ESP_LOGE(PH_TAG, "httpd_ws_recv_frame failed with %s", esp_err_to_name(ret)); + free(buf); + return ret; + } + //ESP_LOGD(PH_TAG, "Got packet with message: %s", ws_pkt.payload); + } + + // Text messages are our payload. + if (ws_pkt.type == HTTPD_WS_TYPE_TEXT || ws_pkt.type == HTTPD_WS_TYPE_BINARY) + { + if (this->_onFrame != NULL) + ret = this->_onFrame(&wsRequest, &ws_pkt); + } + + //logging housekeeping + if (ret != ESP_OK) + ESP_LOGE(PH_TAG, "httpd_ws_send_frame failed with %s", esp_err_to_name(ret)); + // ESP_LOGD(PH_TAG, "ws_handler: httpd_handle_t=%p, sockfd=%d, client_info:%d", + // request->server(), + // httpd_req_to_sockfd(request->request()), + // httpd_ws_get_fd_info(request->server()->server, httpd_req_to_sockfd(request->request()))); + + //dont forget to release our buffer memory + free(buf); + + return ret; +} + +PsychicWebSocketHandler * PsychicWebSocketHandler::onOpen(PsychicWebSocketClientCallback fn) { + _onOpen = fn; + return this; +} + +PsychicWebSocketHandler * PsychicWebSocketHandler::onFrame(PsychicWebSocketFrameCallback fn) { + _onFrame = fn; + return this; +} + +PsychicWebSocketHandler * PsychicWebSocketHandler::onClose(PsychicWebSocketClientCallback fn) { + _onClose = fn; + return this; +} + +void PsychicWebSocketHandler::sendAll(httpd_ws_frame_t * ws_pkt) +{ + for (PsychicClient *client : _clients) + { + //ESP_LOGD(PH_TAG, "Active client (fd=%d) -> sending async message", client->socket()); + + if (client->_friend == NULL) + { + return; + } + + if (((PsychicWebSocketClient*)client->_friend)->sendMessage(ws_pkt) != ESP_OK) + break; + } +} + +void PsychicWebSocketHandler::sendAll(httpd_ws_type_t op, const void *data, size_t len) +{ + httpd_ws_frame_t ws_pkt; + memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); + + ws_pkt.payload = (uint8_t*)data; + ws_pkt.len = len; + ws_pkt.type = op; + + this->sendAll(&ws_pkt); +} + +void PsychicWebSocketHandler::sendAll(const char *buf) +{ + this->sendAll(HTTPD_WS_TYPE_TEXT, buf, strlen(buf)); +} diff --git a/lib/PsychicHttp/src/PsychicWebSocket.h b/lib/PsychicHttp/src/PsychicWebSocket.h new file mode 100644 index 0000000..01917de --- /dev/null +++ b/lib/PsychicHttp/src/PsychicWebSocket.h @@ -0,0 +1,70 @@ +#ifndef PsychicWebSocket_h +#define PsychicWebSocket_h + +#include "PsychicCore.h" +#include "PsychicRequest.h" + +class PsychicWebSocketRequest; +class PsychicWebSocketClient; + +//callback function definitions +typedef std::function PsychicWebSocketClientCallback; +typedef std::function PsychicWebSocketFrameCallback; + +class PsychicWebSocketClient : public PsychicClient +{ + public: + PsychicWebSocketClient(PsychicClient *client); + ~PsychicWebSocketClient(); + + esp_err_t sendMessage(httpd_ws_frame_t * ws_pkt); + esp_err_t sendMessage(httpd_ws_type_t op, const void *data, size_t len); + esp_err_t sendMessage(const char *buf); +}; + +class PsychicWebSocketRequest : public PsychicRequest +{ + private: + PsychicWebSocketClient _client; + + public: + PsychicWebSocketRequest(PsychicRequest *req); + virtual ~PsychicWebSocketRequest(); + + PsychicWebSocketClient * client() override; + + esp_err_t reply(httpd_ws_frame_t * ws_pkt); + esp_err_t reply(httpd_ws_type_t op, const void *data, size_t len); + esp_err_t reply(const char *buf); +}; + +class PsychicWebSocketHandler : public PsychicHandler { + protected: + PsychicWebSocketClientCallback _onOpen; + PsychicWebSocketFrameCallback _onFrame; + PsychicWebSocketClientCallback _onClose; + + public: + PsychicWebSocketHandler(); + ~PsychicWebSocketHandler(); + + PsychicWebSocketClient * getClient(int socket) override; + PsychicWebSocketClient * getClient(PsychicClient *client) override; + void addClient(PsychicClient *client) override; + void removeClient(PsychicClient *client) override; + void openCallback(PsychicClient *client) override; + void closeCallback(PsychicClient *client) override; + + bool isWebSocket() override final; + esp_err_t handleRequest(PsychicRequest *request) override; + + PsychicWebSocketHandler *onOpen(PsychicWebSocketClientCallback fn); + PsychicWebSocketHandler *onFrame(PsychicWebSocketFrameCallback fn); + PsychicWebSocketHandler *onClose(PsychicWebSocketClientCallback fn); + + void sendAll(httpd_ws_frame_t * ws_pkt); + void sendAll(httpd_ws_type_t op, const void *data, size_t len); + void sendAll(const char *buf); +}; + +#endif // PsychicWebSocket_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/TemplatePrinter.cpp b/lib/PsychicHttp/src/TemplatePrinter.cpp new file mode 100644 index 0000000..5c05904 --- /dev/null +++ b/lib/PsychicHttp/src/TemplatePrinter.cpp @@ -0,0 +1,90 @@ + /************************************************************ + + TemplatePrinter Class + + A basic templating engine for a stream of text. + This wraps the Arduino Print interface and writes to any + Print interface. + + Written by Christopher Andrews (https://github.com/Chris--A) + + ************************************************************/ + +#include "TemplatePrinter.h" + +void TemplatePrinter::resetParam(bool flush){ + if(flush && _inParam){ + _stream.write(_delimiter); + + if(_paramPos) + _stream.print(_paramBuffer); + } + + memset(_paramBuffer, 0, sizeof(_paramBuffer)); + _paramPos = 0; + _inParam = false; +} + + +void TemplatePrinter::flush(){ + resetParam(true); + _stream.flush(); +} + +size_t TemplatePrinter::write(uint8_t data){ + + if(data == _delimiter){ + + // End of parameter, send to callback + if(_inParam){ + + // On false, return the parameter place holder as is: not a parameter + // Bug fix: ignore parameters that are zero length. + if(!_paramPos || !_cb(_stream, _paramBuffer)){ + resetParam(true); + _stream.write(data); + }else{ + resetParam(false); + } + + // Start collecting parameter + }else{ + _inParam = true; + } + }else{ + + // Are we collecting + if(_inParam){ + + // Is param still valid + if(isalnum(data) || data == '_'){ + + // Total param len must be 63, 1 for null. + if(_paramPos < sizeof(_paramBuffer) - 1){ + _paramBuffer[_paramPos++] = data; + + // Not a valid param + }else{ + resetParam(true); + } + }else{ + resetParam(true); + _stream.write(data); + } + + // Just output + }else{ + _stream.write(data); + } + } + return 1; +} + +size_t TemplatePrinter::copyFrom(Stream &stream){ + size_t count = 0; + + while(stream.available()) + count += this->write(stream.read()); + + return count; +} diff --git a/lib/PsychicHttp/src/TemplatePrinter.h b/lib/PsychicHttp/src/TemplatePrinter.h new file mode 100644 index 0000000..6adf14a --- /dev/null +++ b/lib/PsychicHttp/src/TemplatePrinter.h @@ -0,0 +1,51 @@ +#ifndef TemplatePrinter_h + #define TemplatePrinter_h + + #include "PsychicCore.h" + #include + + /************************************************************ + + TemplatePrinter Class + + A basic templating engine for a stream of text. + This wraps the Arduino Print interface and writes to any + Print interface. + + Written by Christopher Andrews (https://github.com/Chris--A) + + ************************************************************/ + + class TemplatePrinter; + + typedef std::function TemplateCallback; + typedef std::function TemplateSourceCallback; + + class TemplatePrinter : public Print{ + private: + bool _inParam; + char _paramBuffer[64]; + uint8_t _paramPos; + Print &_stream; + TemplateCallback _cb; + char _delimiter; + + void resetParam(bool flush); + + public: + using Print::write; + + static void start(Print &stream, TemplateCallback cb, TemplateSourceCallback entry){ + TemplatePrinter printer(stream, cb); + entry(printer); + } + + TemplatePrinter(Print &stream, TemplateCallback cb, const char delimeter = '%') : _stream(stream), _cb(cb), _delimiter(delimeter) { resetParam(false); } + ~TemplatePrinter(){ flush(); } + + void flush() override; + size_t write(uint8_t data) override; + size_t copyFrom(Stream &stream); + }; + +#endif diff --git a/lib/PsychicHttp/src/async_worker.cpp b/lib/PsychicHttp/src/async_worker.cpp new file mode 100644 index 0000000..d7310cb --- /dev/null +++ b/lib/PsychicHttp/src/async_worker.cpp @@ -0,0 +1,203 @@ +#include "async_worker.h" + +bool is_on_async_worker_thread(void) +{ + // is our handle one of the known async handles? + TaskHandle_t handle = xTaskGetCurrentTaskHandle(); + for (int i = 0; i < ASYNC_WORKER_COUNT; i++) { + if (worker_handles[i] == handle) { + return true; + } + } + return false; +} + +// Submit an HTTP req to the async worker queue +esp_err_t submit_async_req(httpd_req_t *req, httpd_req_handler_t handler) +{ + // must create a copy of the request that we own + httpd_req_t* copy = NULL; + esp_err_t err = httpd_req_async_handler_begin(req, ©); + if (err != ESP_OK) { + return err; + } + + httpd_async_req_t async_req = { + .req = copy, + .handler = handler, + }; + + // How should we handle resource exhaustion? + // In this example, we immediately respond with an + // http error if no workers are available. + int ticks = 0; + + // counting semaphore: if success, we know 1 or + // more asyncReqTaskWorkers are available. + if (xSemaphoreTake(worker_ready_count, ticks) == false) { + ESP_LOGE(PH_TAG, "No workers are available"); + httpd_req_async_handler_complete(copy); // cleanup + return ESP_FAIL; + } + + // Since worker_ready_count > 0 the queue should already have space. + // But lets wait up to 100ms just to be safe. + if (xQueueSend(async_req_queue, &async_req, pdMS_TO_TICKS(100)) == false) { + ESP_LOGE(PH_TAG, "worker queue is full"); + httpd_req_async_handler_complete(copy); // cleanup + return ESP_FAIL; + } + + return ESP_OK; +} + +void async_req_worker_task(void *p) +{ + ESP_LOGI(PH_TAG, "starting async req task worker"); + + while (true) { + + // counting semaphore - this signals that a worker + // is ready to accept work + xSemaphoreGive(worker_ready_count); + + // wait for a request + httpd_async_req_t async_req; + if (xQueueReceive(async_req_queue, &async_req, portMAX_DELAY)) { + + ESP_LOGI(PH_TAG, "invoking %s", async_req.req->uri); + + // call the handler + async_req.handler(async_req.req); + + // Inform the server that it can purge the socket used for + // this request, if needed. + if (httpd_req_async_handler_complete(async_req.req) != ESP_OK) { + ESP_LOGE(PH_TAG, "failed to complete async req"); + } + } + } + + ESP_LOGW(PH_TAG, "worker stopped"); + vTaskDelete(NULL); +} + +void start_async_req_workers(void) +{ + + // counting semaphore keeps track of available workers + worker_ready_count = xSemaphoreCreateCounting( + ASYNC_WORKER_COUNT, // Max Count + 0); // Initial Count + if (worker_ready_count == NULL) { + ESP_LOGE(PH_TAG, "Failed to create workers counting Semaphore"); + return; + } + + // create queue + async_req_queue = xQueueCreate(1, sizeof(httpd_async_req_t)); + if (async_req_queue == NULL){ + ESP_LOGE(PH_TAG, "Failed to create async_req_queue"); + vSemaphoreDelete(worker_ready_count); + return; + } + + // start worker tasks + for (int i = 0; i < ASYNC_WORKER_COUNT; i++) { + + bool success = xTaskCreate(async_req_worker_task, "async_req_worker", + ASYNC_WORKER_TASK_STACK_SIZE, // stack size + (void *)0, // argument + ASYNC_WORKER_TASK_PRIORITY, // priority + &worker_handles[i]); + + if (!success) { + ESP_LOGE(PH_TAG, "Failed to start asyncReqWorker"); + continue; + } + } +} + +/**** + * + * This code is backported from the 5.1.x branch + * +****/ + +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) + +/* Calculate the maximum size needed for the scratch buffer */ +#define HTTPD_SCRATCH_BUF MAX(HTTPD_MAX_REQ_HDR_LEN, HTTPD_MAX_URI_LEN) + +/** + * @brief Auxiliary data structure for use during reception and processing + * of requests and temporarily keeping responses + */ +struct httpd_req_aux { + struct sock_db *sd; /*!< Pointer to socket database */ + char scratch[HTTPD_SCRATCH_BUF + 1]; /*!< Temporary buffer for our operations (1 byte extra for null termination) */ + size_t remaining_len; /*!< Amount of data remaining to be fetched */ + char *status; /*!< HTTP response's status code */ + char *content_type; /*!< HTTP response's content type */ + bool first_chunk_sent; /*!< Used to indicate if first chunk sent */ + unsigned req_hdrs_count; /*!< Count of total headers in request packet */ + unsigned resp_hdrs_count; /*!< Count of additional headers in response packet */ + struct resp_hdr { + const char *field; + const char *value; + } *resp_hdrs; /*!< Additional headers in response packet */ + struct http_parser_url url_parse_res; /*!< URL parsing result, used for retrieving URL elements */ +#ifdef CONFIG_HTTPD_WS_SUPPORT + bool ws_handshake_detect; /*!< WebSocket handshake detection flag */ + httpd_ws_type_t ws_type; /*!< WebSocket frame type */ + bool ws_final; /*!< WebSocket FIN bit (final frame or not) */ + uint8_t mask_key[4]; /*!< WebSocket mask key for this payload */ +#endif +}; + +esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out) +{ + if (r == NULL || out == NULL) { + return ESP_ERR_INVALID_ARG; + } + + // alloc async req + httpd_req_t *async = (httpd_req_t *)malloc(sizeof(httpd_req_t)); + if (async == NULL) { + return ESP_ERR_NO_MEM; + } + memcpy((void *)async, (void *)r, sizeof(httpd_req_t)); + + // alloc async aux + async->aux = (httpd_req_aux *)malloc(sizeof(struct httpd_req_aux)); + if (async->aux == NULL) { + free(async); + return ESP_ERR_NO_MEM; + } + memcpy(async->aux, r->aux, sizeof(struct httpd_req_aux)); + + // not available in 4.4.x + // mark socket as "in use" + // struct httpd_req_aux *ra = r->aux; + //ra->sd->for_async_req = true; + + *out = async; + + return ESP_OK; +} + +esp_err_t httpd_req_async_handler_complete(httpd_req_t *r) +{ + if (r == NULL) { + return ESP_ERR_INVALID_ARG; + } + + // not available in 4.4.x + // struct httpd_req_aux *ra = (httpd_req_aux *)r->aux; + // ra->sd->for_async_req = false; + + free(r->aux); + free(r); + + return ESP_OK; +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/async_worker.h b/lib/PsychicHttp/src/async_worker.h new file mode 100644 index 0000000..e77c4a6 --- /dev/null +++ b/lib/PsychicHttp/src/async_worker.h @@ -0,0 +1,36 @@ +#ifndef async_worker_h +#define async_worker_h + +#include "PsychicCore.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +#define ASYNC_WORKER_TASK_PRIORITY 5 +#define ASYNC_WORKER_TASK_STACK_SIZE (4*1024) +#define ASYNC_WORKER_COUNT 8 + +// Async requests are queued here while they wait to be processed by the workers +static QueueHandle_t async_req_queue; + +// Track the number of free workers at any given time +static SemaphoreHandle_t worker_ready_count; + +// Each worker has its own thread +static TaskHandle_t worker_handles[ASYNC_WORKER_COUNT]; + +typedef esp_err_t (*httpd_req_handler_t)(httpd_req_t *req); + +typedef struct { + httpd_req_t* req; + httpd_req_handler_t handler; +} httpd_async_req_t; + +bool is_on_async_worker_thread(void); +esp_err_t submit_async_req(httpd_req_t *req, httpd_req_handler_t handler); +void async_req_worker_task(void *p); +void start_async_req_workers(void); + +esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out); +esp_err_t httpd_req_async_handler_complete(httpd_req_t *r); + +#endif //async_worker_h \ No newline at end of file diff --git a/lib/PsychicHttp/src/http_status.cpp b/lib/PsychicHttp/src/http_status.cpp new file mode 100644 index 0000000..64e0c07 --- /dev/null +++ b/lib/PsychicHttp/src/http_status.cpp @@ -0,0 +1,194 @@ +#include "http_status.h" + +bool http_informational(int code) +{ + return code >= 100 && code < 200; +} + +bool http_success(int code) +{ + return code >= 200 && code < 300; +} + +bool http_redirection(int code) +{ + return code >= 300 && code < 400; +} + +bool http_client_error(int code) +{ + return code >= 400 && code < 500; +} + +bool http_server_error(int code) +{ + return code >= 500 && code < 600; +} + +bool http_failure(int code) +{ + return code >= 400 && code < 600; +} + +const char *http_status_group(int code) +{ + if (http_informational(code)) + return "Informational"; + + if (http_success(code)) + return "Success"; + + if (http_redirection(code)) + return "Redirection"; + + if (http_client_error(code)) + return "Client Error"; + + if (http_server_error(code)) + return "Server Error"; + + return "Unknown"; +} + +const char *http_status_reason(int code) +{ + switch (code) + { + /*####### 1xx - Informational #######*/ + case 100: + return "Continue"; + case 101: + return "Switching Protocols"; + case 102: + return "Processing"; + case 103: + return "Early Hints"; + + /*####### 2xx - Successful #######*/ + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 203: + return "Non-Authoritative Information"; + case 204: + return "No Content"; + case 205: + return "Reset Content"; + case 206: + return "Partial Content"; + case 207: + return "Multi-Status"; + case 208: + return "Already Reported"; + case 226: + return "IM Used"; + + /*####### 3xx - Redirection #######*/ + case 300: + return "Multiple Choices"; + case 301: + return "Moved Permanently"; + case 302: + return "Found"; + case 303: + return "See Other"; + case 304: + return "Not Modified"; + case 305: + return "Use Proxy"; + case 307: + return "Temporary Redirect"; + case 308: + return "Permanent Redirect"; + + /*####### 4xx - Client Error #######*/ + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 402: + return "Payment Required"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 406: + return "Not Acceptable"; + case 407: + return "Proxy Authentication Required"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 410: + return "Gone"; + case 411: + return "Length Required"; + case 412: + return "Precondition Failed"; + case 413: + return "Content Too Large"; + case 414: + return "URI Too Long"; + case 415: + return "Unsupported Media Type"; + case 416: + return "Range Not Satisfiable"; + case 417: + return "Expectation Failed"; + case 418: + return "I'm a teapot"; + case 421: + return "Misdirected Request"; + case 422: + return "Unprocessable Content"; + case 423: + return "Locked"; + case 424: + return "Failed Dependency"; + case 425: + return "Too Early"; + case 426: + return "Upgrade Required"; + case 428: + return "Precondition Required"; + case 429: + return "Too Many Requests"; + case 431: + return "Request Header Fields Too Large"; + case 451: + return "Unavailable For Legal Reasons"; + + /*####### 5xx - Server Error #######*/ + case 500: + return "Internal Server Error"; + case 501: + return "Not Implemented"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + case 504: + return "Gateway Timeout"; + case 505: + return "HTTP Version Not Supported"; + case 506: + return "Variant Also Negotiates"; + case 507: + return "Insufficient Storage"; + case 508: + return "Loop Detected"; + case 510: + return "Not Extended"; + case 511: + return "Network Authentication Required"; + + default: + return "Unknown"; + } +} \ No newline at end of file diff --git a/lib/PsychicHttp/src/http_status.h b/lib/PsychicHttp/src/http_status.h new file mode 100644 index 0000000..e03b735 --- /dev/null +++ b/lib/PsychicHttp/src/http_status.h @@ -0,0 +1,15 @@ +#ifndef MICRO_HTTP_STATUS_H +#define MICRO_HTTP_STATUS_H + +#include + +bool http_informational(int code); +bool http_success(int code); +bool http_redirection(int code); +bool http_client_error(int code); +bool http_server_error(int code); +bool http_failure(int code); +const char *http_status_group(int code); +const char *http_status_reason(int code); + +#endif // MICRO_HTTP_STATUS_H \ No newline at end of file diff --git a/lib/WiFiManager/CMakeLists.txt b/lib/WiFiManager/CMakeLists.txt deleted file mode 100644 index c87bb20..0000000 --- a/lib/WiFiManager/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -cmake_minimum_required(VERSION 3.5) - -idf_component_register( - SRCS "WiFiManager.cpp" - INCLUDE_DIRS "." - PRIV_REQUIRES arduino -) - -project(WiFiManager) diff --git a/lib/WiFiManager/LICENSE b/lib/WiFiManager/LICENSE deleted file mode 100644 index 1dabff5..0000000 --- a/lib/WiFiManager/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 tzapu - -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/WiFiManager/README.md b/lib/WiFiManager/README.md deleted file mode 100644 index 29976c6..0000000 --- a/lib/WiFiManager/README.md +++ /dev/null @@ -1,576 +0,0 @@ - -# WiFiManager - -Espressif ESPx WiFi Connection manager with fallback web configuration portal - -:warning: This Documentation is out of date, see notes below - - -[![Release](https://img.shields.io/github/v/release/tzapu/WiFiManager?include_prereleases)](#release) - -[![Build CI Status](https://github.com/tzapu/WiFiManager/actions/workflows/compile_library.yml/badge.svg)](https://github.com/tzapu/WiFiManager/actions/workflows/compile_library.yml) - -[![Build CI Status Examples](https://github.com/tzapu/WiFiManager/actions/workflows/compile_examples.yaml/badge.svg)](https://github.com/tzapu/WiFiManager/actions/workflows/compile_examples.yaml) - -[![arduino-library-badge](https://www.ardu-badge.com/badge/WiFiManager.svg?)](https://www.ardu-badge.com/WiFiManager) - -[![Build with PlatformIO](https://img.shields.io/badge/PlatformIO-Library-orange?)](https://platformio.org/lib/show/567/WiFiManager/installation) - -[![ESP8266](https://img.shields.io/badge/ESP-8266-000000.svg?longCache=true&style=flat&colorA=CC101F)](https://www.espressif.com/en/products/socs/esp8266) - -[![ESP32](https://img.shields.io/badge/ESP-32-000000.svg?longCache=true&style=flat&colorA=CC101F)](https://www.espressif.com/en/products/socs/esp32) -[![ESP32](https://img.shields.io/badge/ESP-32S2-000000.svg?longCache=true&style=flat&colorA=CC101F)](https://www.espressif.com/en/products/socs/esp32-s2) -[![ESP32](https://img.shields.io/badge/ESP-32C3-000000.svg?longCache=true&style=flat&colorA=CC101F)](https://www.espressif.com/en/products/socs/esp32-c3) -[![ESP32](https://img.shields.io/badge/ESP-32S3-000000.svg?longCache=true&style=flat&colorA=CC101F)](https://www.espressif.com/en/products/socs/esp32-S3) - -Member to Member Support / Chat - - [![Join the chat at https://gitter.im/tablatronix/WiFiManager](https://badges.gitter.im/tablatronix/WiFiManager.svg)](https://gitter.im/tablatronix/WiFiManager?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -[![Discord](https://img.shields.io/badge/Discord-WiFiManager-%237289da.svg?logo=discord)](https://discord.gg/nS5WGkaQH5) -The configuration portal is of the captive variety, so on various devices it will present the configuration dialogue as soon as you connect to the created access point. - -Works with the [ESP8266 Arduino](https://github.com/esp8266/Arduino) and [ESP32 Arduino](https://github.com/espressif/arduino-esp32) platforms. - -### Known Issues - -* Documentation needs to be updated, see [https://github.com/tzapu/WiFiManager/issues/500](https://github.com/tzapu/WiFiManager/issues/500) -------- - -## Contents - - [How it works](#how-it-works) - - [Wishlist](#wishlist) - - [Quick start](#quick-start) - - Installing - - [Arduino - Through Library Manager](#install-through-library-manager) - - [Arduino - From Github](#checkout-from-github) - - [PlatformIO](#install-using-platformio) - - [Using](#using) - - [Documentation](#documentation) - - [Access Point Password](#password-protect-the-configuration-access-point) - - [Callbacks](#callbacks) - - [Configuration Portal Timeout](#configuration-portal-timeout) - - [On Demand Configuration](#on-demand-configuration-portal) - - [Custom Parameters](#custom-parameters) - - [Custom IP Configuration](#custom-ip-configuration) - - [Filter Low Quality Networks](#filter-networks) - - [Debug Output](#debug) - - [Troubleshooting](#troubleshooting) - - [Releases](#releases) - - [Contributors](#contributions-and-thanks) - - -## How It Works -- When your ESP starts up, it sets it up in Station mode and tries to connect to a previously saved Access Point -- if this is unsuccessful (or no previous network saved) it moves the ESP into Access Point mode and spins up a DNS and WebServer (default ip 192.168.4.1) -- using any wifi enabled device with a browser (computer, phone, tablet) connect to the newly created Access Point -- because of the Captive Portal and the DNS server you will either get a 'Join to network' type of popup or get any domain you try to access redirected to the configuration portal -- choose one of the access points scanned, enter password, click save -- ESP will try to connect. If successful, it relinquishes control back to your app. If not, reconnect to AP and reconfigure. -- There are options to change this behavior or manually start the configportal and webportal independantly as well as run them in non blocking mode. - -## How It Looks -![ESP8266 WiFi Captive Portal Homepage](http://i.imgur.com/YPvW9eql.png) ![ESP8266 WiFi Captive Portal Configuration](http://i.imgur.com/oicWJ4gl.png) - -## Wishlist -- [x] remove dependency on EEPROM library -- [x] move HTML Strings to PROGMEM -- [x] cleanup and streamline code (although this is ongoing) -- [x] if timeout is set, extend it when a page is fetched in AP mode -- [x] add ability to configure more parameters than ssid/password -- [x] maybe allow setting ip of ESP after reboot -- [x] add to Arduino Library Manager -- [x] add to PlatformIO -- [ ] add multiple sets of network credentials -- [x] allow users to customize CSS -- [ ] rewrite documentation for simplicity, based on scenarios/goals - -### Development -- [x] ESP32 support -- [x] rely on the SDK's built in auto connect more than forcing a connect -- [x] add non blocking mode -- [x] easy customization of strings -- [x] hostname support -- [x] fix various bugs and workarounds for esp SDK issues -- [x] additional info page items -- [x] last status display / faiilure reason -- [x] customizeable menu -- [x] seperate custom params page -- [x] ondemand webportal -- [x] complete refactor of code to segment functions -- [x] wiif scan icons or percentage display -- [x] invert class for dark mode -- [x] more template tokens -- [x] progmem for all strings -- [ ] new callbacks -- [ ] new callouts / filters -- [ ] shared web server instance -- [x] latest esp idf/sdk support -- [x] wm is now non persistent, will not erase or change stored esp config on esp8266 -- [x] tons of debugging output / levels -- [ ] disable captiveportal -- [ ] preload wiifscans, faster page loads -- [ ] softap stability fixes when sta is not connected - - -## Quick Start - -### Installing -You can either install through the Arduino Library Manager or checkout the latest changes or a release from github - -#### Install through Library Manager -__Currently version 0.8+ works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - - in Arduino IDE got to Sketch/Include Library/Manage Libraries - ![Manage Libraries](http://i.imgur.com/9BkEBkR.png) - - - search for WiFiManager - ![WiFiManager package](http://i.imgur.com/18yIai8.png) - - - click Install and start [using it](#using) - -#### Checkout from github -__Github version works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ -- Checkout library to your Arduino libraries folder - -### Using -- Include in your sketch -```cpp -#include //https://github.com/tzapu/WiFiManager WiFi Configuration Magic -``` - -- Initialize library, in your setup function add, NOTEif you are using non blocking you will make sure you create this in global scope or handle appropriatly , it will not work if in setup and using non blocking mode. -```cpp -WiFiManager wifiManager; -``` - -- Also in the setup function add -```cpp -//first parameter is name of access point, second is the password -wifiManager.autoConnect("AP-NAME", "AP-PASSWORD"); -``` -if you just want an unsecured access point -```cpp -wifiManager.autoConnect("AP-NAME"); -``` -or if you want to use and auto generated name from 'ESP' and the esp's Chip ID use -```cpp -wifiManager.autoConnect(); -``` - -After you write your sketch and start the ESP, it will try to connect to WiFi. If it fails it starts in Access Point mode. -While in AP mode, connect to it then open a browser to the gateway IP, default 192.168.4.1, configure wifi, save and it should reboot and connect. - -Also see [examples](https://github.com/tzapu/WiFiManager/tree/master/examples). - -#### Install Using PlatformIO - -[PlatformIO](https://platformio.org/) is an emerging ecosystem for IoT development, and -is an alternative to using the Arduino IDE. Install `WiFiManager` -using the platformio [library manager](https://docs.platformio.org/en/latest/librarymanager/index.html#librarymanager) in your editor, -or using the [PlatformIO Core CLI](https://docs.platformio.org/en/latest/core/index.html), -or by adding it to your `platformio.ini` as shown below (recommended approach). - -The simplest way is to open the `platformio.ini` file at the root of your project, and `WifiManager` to the common top-level env -`lib_deps` key like so: - -``` -[env] -lib_deps = - WiFiManager -``` - - -``` -[env] -lib_deps = - https://github.com/tzapu/WiFiManager.git -``` - -## Documentation - -#### Password protect the configuration Access Point -You can and should password protect the configuration access point. Simply add the password as a second parameter to `autoConnect`. -A short password seems to have unpredictable results so use one that's around 8 characters or more in length. -The guidelines are that a wifi password must consist of 8 to 63 ASCII-encoded characters in the range of 32 to 126 (decimal) -```cpp -wifiManager.autoConnect("AutoConnectAP", "password") -``` - -#### Callbacks -##### Enter Config mode -Use this if you need to do something when your device enters configuration mode on failed WiFi connection attempt. -Before `autoConnect()` -```cpp -wifiManager.setAPCallback(configModeCallback); -``` -`configModeCallback` declaration and example -```cpp -void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("Entered config mode"); - Serial.println(WiFi.softAPIP()); - - Serial.println(myWiFiManager->getConfigPortalSSID()); -} -``` - -##### Save settings -This gets called when custom parameters have been set **AND** a connection has been established. Use it to set a flag, so when all the configuration finishes, you can save the extra parameters somewhere. - - -IF YOU NEED TO SAVE PARAMETERS EVEN ON WIFI FAIL OR EMPTY, you must set `setBreakAfterConfig` to true, or else saveConfigCallback will not be called. - -```C++ -//if this is set, it will exit after config, even if connection is unsuccessful. - void setBreakAfterConfig(boolean shouldBreak); -``` - -See [AutoConnectWithFSParameters Example](https://github.com/tzapu/WiFiManager/tree/master/examples/Parameters/SPIFFS/AutoConnectWithFSParameters). -```cpp -wifiManager.setSaveConfigCallback(saveConfigCallback); -``` -`saveConfigCallback` declaration and example -```cpp -//flag for saving data -bool shouldSaveConfig = false; - -//callback notifying us of the need to save config -void saveConfigCallback () { - Serial.println("Should save config"); - shouldSaveConfig = true; -} -``` - -#### Configuration Portal Timeout -If you need to set a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure, you can add -```cpp -wifiManager.setConfigPortalTimeout(180); -``` -which will wait 3 minutes (180 seconds). When the time passes, the autoConnect function will return, no matter the outcome. -Check for connection and if it's still not established do whatever is needed (on some modules I restart them to retry, on others I enter deep sleep) - -#### On Demand Configuration Portal -If you would rather start the configuration portal on demand rather than automatically on a failed connection attempt, then this is for you. - -Instead of calling `autoConnect()` which does all the connecting and failover configuration portal setup for you, you need to use `startConfigPortal()`. __Do not use BOTH.__ - -Example usage -```cpp -void loop() { - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW ) { - WiFiManager wifiManager; - wifiManager.startConfigPortal("OnDemandAP"); - Serial.println("connected...yeey :)"); - } -} -``` -See example for a more complex version. [OnDemandConfigPortal](https://github.com/tzapu/WiFiManager/tree/master/examples/OnDemand/OnDemandConfigPortal) - -#### Exiting from the Configuration Portal -Normally, once entered, the configuration portal will continue to loop until WiFi credentials have been successfully entered or a timeout is reached. -If you'd prefer to exit without joining a WiFi network, say becuase you're going to put the ESP into AP mode, then press the "Exit" button -on the main webpage. -If started via `autoConnect` or `startConfigPortal` then it will return `false (portalAbortResult)` - -#### Custom Parameters -You can use WiFiManager to collect more parameters than just SSID and password. -This could be helpful for configuring stuff like MQTT host and port, [blynk](http://www.blynk.cc) or [emoncms](http://emoncms.org) tokens, just to name a few. -**You are responsible for saving and loading these custom values.** The library just collects and displays the data for you as a convenience. -Usage scenario would be: -- load values from somewhere (EEPROM/FS) or generate some defaults -- add the custom parameters to WiFiManager using -```cpp - // id/name, placeholder/prompt, default, length - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - wifiManager.addParameter(&custom_mqtt_server); - -``` -- if connection to AP fails, configuration portal starts and you can set /change the values (or use on demand configuration portal) -- once configuration is done and connection is established save config callback() is called -- once WiFiManager returns control to your application, read and save the new values using the `WiFiManagerParameter` object. -```cpp - mqtt_server = custom_mqtt_server.getValue(); -``` -This feature is a lot more involved than all the others, so here are some examples to fully show how it is done. -You should also take a look at adding custom HTML to your form. - -- Save and load custom parameters to file system in json form [AutoConnectWithFSParameters](https://github.com/tzapu/WiFiManager/tree/master/examples/Parameters/SPIFFS/AutoConnectWithFSParameters) -- *Save and load custom parameters to EEPROM* (not done yet) - -#### Custom IP Configuration -You can set a custom IP for both AP (access point, config mode) and STA (station mode, client mode, normal project state) - -##### Custom Access Point IP Configuration -This will set your captive portal to a specific IP should you need/want such a feature. Add the following snippet before `autoConnect()` -```cpp -//set custom ip for portal -wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); -``` - -##### Custom Station (client) Static IP Configuration -This will make use the specified IP configuration instead of using DHCP in station mode. -```cpp -wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); // optional DNS 4th argument -``` -There are a couple of examples in the examples folder that show you how to set a static IP and even how to configure it through the web configuration portal. - -NOTE: You should fill DNS server if you have HTTP requests with hostnames or syncronize time (NTP). It's the same as gateway ip or a popular (Google DNS: 8.8.8.8). - -#### Custom HTML, CSS, Javascript -There are various ways in which you can inject custom HTML, CSS or Javascript into the configuration portal. -The options are: -- inject custom head element -You can use this to any html bit to the head of the configuration portal. If you add a `"); -``` -- inject a custom bit of html in the configuration/param form -```cpp -WiFiManagerParameter custom_text("

This is just a text paragraph

"); -wifiManager.addParameter(&custom_text); -``` -- inject a custom bit of html in a configuration form element -Just add the bit you want added as the last parameter to the custom parameter constructor. -```cpp -WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "iot.eclipse", 40, " readonly"); -wifiManager.addParameter(&custom_mqtt_server); -``` - -#### Theming -You can customize certain elements of the default template with some builtin classes -```CPP -wifiManager.setClass("invert"); // dark theme -wifiManager.setScanDispPerc(true); // display percentages instead of graphs for RSSI -``` -There are additional classes in the css you can use in your custom html , see the example template. - -#### Filter Networks -You can filter networks based on signal quality and show/hide duplicate networks. - -- If you would like to filter low signal quality networks you can tell WiFiManager to not show networks below an arbitrary quality %; -```cpp -wifiManager.setMinimumSignalQuality(10); -``` -will not show networks under 10% signal quality. If you omit the parameter it defaults to 8%; - -- You can also remove or show duplicate networks (default is remove). -Use this function to show (or hide) all networks. -```cpp -wifiManager.setRemoveDuplicateAPs(false); -``` - -#### Debug -Debug is enabled by default on `Serial` in non-stable releases. To disable add before autoConnect/startConfigPortal -```cpp -wifiManager.setDebugOutput(false); -``` - -You can pass in a custom stream via constructor -```CPP -WiFiManager wifiManager(Serial1); -``` - -You can customize the debug level by changing `_debugLevel` in source -options are: -* DEBUG_ERROR -* DEBUG_NOTIFY -* DEBUG_VERBOSE -* DEBUG_DEV -* DEBUG_MAX - -## Troubleshooting -If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. - -Changes added on 0.8 should make the latest trunk work without compilation errors. Tested down to ESP8266 core 2.0.0. **Please update to version 0.8** - -I am trying to keep releases working with release versions of the core, so they can be installed through boards manager, but if you checkout the latest version directly from github, sometimes, the library will only work if you update the ESP8266 core to the latest version because I am using some newly added function. - -If you connect to the created configuration Access Point but the configuration portal does not show up, just open a browser and type in the IP of the web portal, by default `192.168.4.1`. - -If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. - -I get stuck in ap mode when the power goes out or modem resets, try a setConfigPortalTimeout(seconds). This will cause the configportal to close after no activity, and you can reboot or attempt reconnection in your code. - -## Releases -### 1.0.1 - -### Development Overview - -#### Added Public Methods -`setConfigPortalBlocking` - -`setShowStaticFields` - -`setCaptivePortalEnable` - -`setRestorePersistent` - -`setCaptivePortalClientCheck` - -`setWebPortalClientCheck` - -`startWebPortal` - -`stopWebPortal` - -`process` - -`disconnect` - -`erase` - -` debugSoftAPConfig` - -` debugPlatformInfo` - -`setScanDispPerc` - -`setHostname` - -`setMenu(menu_page_t[])` - -`setWiFiAutoReconnect` - -` setSTAStaticIPConfig(..,dns)` - -`setShowDnsFields` - -`getLastConxResult` - -`getWLStatusString` - -`getModeString` - -`getWiFiIsSaved` - -`setShowInfoErase` - -`setEnableConfigPortal` - -`setCountry` - -`setClass` - -`htmleEtities` - - -#### WiFiManagerParameter -`WiFiManagerParameter(id,label)` - -`WiFiManagerParameter.setValue(value,length)` - -`getParameters` - -`getParametersCount` - - -#### Constructors -`WiFiManager(Stream& consolePort)` - -#### define flags -❗️ **Defines cannot be set in user sketches** -`#define WM_MDNS // use MDNS` - -`#define WM_FIXERASECONFIG // use erase flash fix, esp8266 2.4.0` - -`#define WM_ERASE_NVS // esp32 erase(true) will erase NVS` - -`#include // esp32 info page will show last reset reasons if this file is included` - -#### Changes Overview -- ESP32 support ( fairly stable ) -- complete refactor of strings `strings_en.h` -- adds new tokens for wifiscan, and some classes (left , invert icons, MSG color) -- adds status callout panel default, primary, special colors -- adds tons of info on info page, and erase capability -- adds signal icons, replaces percentage ( has hover titles ) -- adds labels to all inputs (replaces placeholders) -- all html ( and eventually all strings except debug) moved to `strings_en.h` -- added additional debugging, compressed debug lines, debuglevels -- persistent disabled, and restored via de/con-stuctor (uses `setRestorePersistent`) -- should retain all user modes including AP, should not overwrite or persist user modes or configs,even STA (`storeSTAmode`) (BUGGY) -- ⚠️ return values may have changed depending on portal abort, or timeout ( `portalTimeoutResult`,`portalAbortResult`) -- params memory is auto allocated by increment of `WIFI_MANAGER_MAX_PARAMS(5)` when exceeded, user no longer needs to specify this at all. -- addparameter now returns bool, and it returns false if param ID is not alphanum [0-9,A-Z,a-z,_] -- param field ids allow {I} token to use param_n instead of string in case someones wants to change this due to i18n or character issues -- provides `#DEFINE FIXERASECONFIG` to help deal with https://github.com/esp8266/Arduino/pull/3635 -- failure reason reporting on portal -- set esp8266 sta hostname, esp32 sta+ap hostname ( DHCP client id) -- pass in debug stream in constructor WiFiManager(Stream& consolePort) -- you can force ip fields off with showxfields(false) if you set _disableIpFields=true -- param menu/page (setup) added to separate params from wifi page, handled automatically by setMenu -- set custom root menu -- disable configportal on autoconnect -- wm parameters init is now protected, allowing child classes, example included -- wifiscans are precached and async for faster page loads, refresh forces rescan -- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) - -#### 0.12 -- removed 204 header response -- fixed incompatibility with other libs using isnan and other std:: functions without namespace - -##### 0.11 -- a lot more reliable reconnecting to networks -- custom html in custom parameters (for read only params) -- custom html in custom parameter form (like labels) -- custom head element (like custom css) -- sort networks based on signal quality -- remove duplicate networks - -##### 0.10 -- some css changes -- bug fixes and speed improvements -- added an alternative to waitForConnectResult() for debugging -- changed `setTimeout(seconds)` to `setConfigPortalTimeout(seconds)` - -### Contributions and thanks -The support and help I got from the community has been nothing short of phenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. - -__THANK YOU__ - -The esp8266 and esp32 arduino and idf maintainers! - -[Shawn A aka tablatronix](https://github.com/tablatronix) - -[liebman](https://github.com/liebman) - -[Evgeny Dontsov](https://github.com/dontsovcmc) - -[Chris Marrin](https://github.com/cmarrin) - -[bbx10](https://github.com/bbx10) - -[kentaylor](https://github.com/kentaylor) - -[Maximiliano Duarte](https://github.com/domonetic) - -[alltheblinkythings](https://github.com/alltheblinkythings) - -[Niklas Wall](https://github.com/niklaswall) - -[Jakub Piasecki](https://github.com/zaporylie) - -[Peter Allan](https://github.com/alwynallan) - -[John Little](https://github.com/j0hnlittle) - -[markaswift](https://github.com/markaswift) - -[franklinvv](https://github.com/franklinvv) - -[Alberto Ricci Bitti](https://github.com/riccibitti) - -[SebiPanther](https://github.com/SebiPanther) - -[jonathanendersby](https://github.com/jonathanendersby) - -[walthercarsten](https://github.com/walthercarsten) - -And countless others - -#### Inspiration - * http://www.esp8266.com/viewtopic.php?f=29&t=2520 - * https://github.com/chriscook8/esp-arduino-apboot - * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced - * Built by AlexT https://github.com/tzapu - diff --git a/lib/WiFiManager/WiFiManager.cpp b/lib/WiFiManager/WiFiManager.cpp deleted file mode 100644 index d7aa82c..0000000 --- a/lib/WiFiManager/WiFiManager.cpp +++ /dev/null @@ -1,4160 +0,0 @@ -/** - * WiFiManager.cpp - * - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - -#include "WiFiManager.h" - -#if defined(ESP8266) || defined(ESP32) - -#ifdef ESP32 -uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; -#endif - -/** - * -------------------------------------------------------------------------------- - * WiFiManagerParameter - * -------------------------------------------------------------------------------- -**/ - -WiFiManagerParameter::WiFiManagerParameter() { - WiFiManagerParameter(""); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *custom) { - _id = NULL; - _label = NULL; - _length = 0; - _value = nullptr; - _labelPlacement = WFM_LABEL_DEFAULT; - _customHTML = custom; -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { - init(id, label, "", 0, "", WFM_LABEL_DEFAULT); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) { - init(id, label, defaultValue, length, "", WFM_LABEL_DEFAULT); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) { - init(id, label, defaultValue, length, custom, WFM_LABEL_DEFAULT); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { - init(id, label, defaultValue, length, custom, labelPlacement); -} - -void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { - _id = id; - _label = label; - _labelPlacement = labelPlacement; - _customHTML = custom; - _length = 0; - _value = nullptr; - setValue(defaultValue,length); -} - -WiFiManagerParameter::~WiFiManagerParameter() { - if (_value != NULL) { - delete[] _value; - } - _length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows -} - -// WiFiManagerParameter& WiFiManagerParameter::operator=(const WiFiManagerParameter& rhs){ -// Serial.println("copy assignment op called"); -// (*this->_value) = (*rhs._value); -// return *this; -// } - -// @note debug is not available in wmparameter class -void WiFiManagerParameter::setValue(const char *defaultValue, int length) { - if(!_id){ - // Serial.println("cannot set value of this parameter"); - return; - } - - // if(strlen(defaultValue) > length){ - // // Serial.println("defaultValue length mismatch"); - // // return false; //@todo bail - // } - - if(_length != length || _value == nullptr){ - _length = length; - if( _value != nullptr){ - delete[] _value; - } - _value = new char[_length + 1]; - } - - memset(_value, 0, _length + 1); // explicit null - - if (defaultValue != NULL) { - strncpy(_value, defaultValue, _length); - } -} -const char* WiFiManagerParameter::getValue() const { - // Serial.println(printf("Address of _value is %p\n", (void *)_value)); - return _value; -} -const char* WiFiManagerParameter::getID() const { - return _id; -} -const char* WiFiManagerParameter::getPlaceholder() const { - return _label; -} -const char* WiFiManagerParameter::getLabel() const { - return _label; -} -int WiFiManagerParameter::getValueLength() const { - return _length; -} -int WiFiManagerParameter::getLabelPlacement() const { - return _labelPlacement; -} -const char* WiFiManagerParameter::getCustomHTML() const { - return _customHTML; -} - -/** - * [addParameter description] - * @access public - * @param {[type]} WiFiManagerParameter *p [description] - */ -bool WiFiManager::addParameter(WiFiManagerParameter *p) { - - // check param id is valid, unless null - if(p->getID()){ - for (size_t i = 0; i < strlen(p->getID()); i++){ - if(!(isAlphaNumeric(p->getID()[i])) && !(p->getID()[i]=='_')){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] parameter IDs can only contain alpha numeric chars")); - #endif - return false; - } - } - } - - // init params if never malloc - if(_params == NULL){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*)); - #endif - _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); - } - - // resize the params array by increment of WIFI_MANAGER_MAX_PARAMS - if(_paramsCount == _max_params){ - _max_params += WIFI_MANAGER_MAX_PARAMS; - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Updated _max_params:"),_max_params); - DEBUG_WM(WM_DEBUG_DEV,F("re-allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*)); - #endif - WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*)); - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WIFI_MANAGER_MAX_PARAMS); - // DEBUG_WM(_paramsCount); - // DEBUG_WM(_max_params); - #endif - if (new_params != NULL) { - _params = new_params; - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] failed to realloc params, size not increased!")); - #endif - return false; - } - } - - _params[_paramsCount] = p; - _paramsCount++; - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Added Parameter:"),p->getID()); - #endif - return true; -} - -/** - * [getParameters description] - * @access public - */ -WiFiManagerParameter** WiFiManager::getParameters() { - return _params; -} - -/** - * [getParametersCount description] - * @access public - */ -int WiFiManager::getParametersCount() { - return _paramsCount; -} - -/** - * -------------------------------------------------------------------------------- - * WiFiManager - * -------------------------------------------------------------------------------- -**/ - -// constructors -WiFiManager::WiFiManager(Print& consolePort):_debugPort(consolePort){ - WiFiManagerInit(); -} - -WiFiManager::WiFiManager(const char* user, const char* password) { - WiFiManagerInit(); - - if(strlen(user) > 0) - { - strcpy(_credUser, user); - strcpy(_credPassword, password); - _hasCredentials = true; - } -} - -WiFiManager::WiFiManager() { - WiFiManagerInit(); -} - -void WiFiManager::WiFiManagerInit(){ - setMenu(_menuIdsDefault); - if(_debug && _debugLevel >= WM_DEBUG_DEV) debugPlatformInfo(); - _max_params = WIFI_MANAGER_MAX_PARAMS; -} - -// destructor -WiFiManager::~WiFiManager() { - _end(); - // parameters - // @todo below belongs to wifimanagerparameter - if (_params != NULL){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("freeing allocated params!")); - #endif - free(_params); - _params = NULL; - } - - // remove event - // WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); - #ifdef ESP32 - WiFi.removeEvent(wm_event_id); - #endif - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("unloading")); - #endif -} - -void WiFiManager::_begin(){ - if(_hasBegun) return; - _hasBegun = true; - // _usermode = WiFi.getMode(); - - #ifndef ESP32 - WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites - #endif -} - -void WiFiManager::_end(){ - _hasBegun = false; - if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent - // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); -} - -// AUTOCONNECT - -boolean WiFiManager::autoConnect() { - String ssid = getDefaultAPName(); - return autoConnect(ssid.c_str(), NULL); -} - -/** - * [autoConnect description] - * @access public - * @param {[type]} char const *apName [description] - * @param {[type]} char const *apPassword [description] - * @return {[type]} [description] - */ -boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("AutoConnect")); - #endif - - // no getter for autoreconnectpolicy before this - // https://github.com/esp8266/Arduino/pull/4359 - // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop - WiFi_autoReconnect(); - - // bool wifiIsSaved = getWiFiIsSaved(); - bool wifiIsSaved = true; // workaround until I can check esp32 wifiisinit and has nvs - - #ifdef ESP32 - setupHostname(true); - - if(_hostname != ""){ - // disable wifi if already on - if(WiFi.getMode() & WIFI_STA){ - WiFi.mode(WIFI_OFF); - int timeout = millis()+1200; - // async loop for mode change - while(WiFi.getMode()!= WIFI_OFF && millis()0){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting AP on channel:"),channel); - #endif - } - - // start soft AP with password or anonymous - // default channel is 1 here and in esplib, @todo just change to default remove conditionals - if (_apPassword != "") { - if(channel>0){ - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),channel,_apHidden); - } - else{ - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),1,_apHidden);//password option - } - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("AP has anonymous access!")); - #endif - if(channel>0){ - ret = WiFi.softAP(_apName.c_str(),"",channel,_apHidden); - } - else{ - ret = WiFi.softAP(_apName.c_str(),"",1,_apHidden); - } - } - - if(_debugLevel >= WM_DEBUG_DEV) debugSoftAPConfig(); - - // @todo add softAP retry here to dela with unknown failures - - delay(500); // slight delay to make sure we get an AP IP - #ifdef WM_DEBUG_LEVEL - if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] There was a problem starting the AP")); - DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); - #endif - - // set ap hostname - #ifdef ESP32 - if(ret && _hostname != ""){ - bool res = WiFi.softAPsetHostname(_hostname.c_str()); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("setting softAP Hostname:"),_hostname); - if(!res)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); - DEBUG_WM(WM_DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname()); - #endif - } - #endif - - return ret; -} - -/** - * [startWebPortal description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::startWebPortal() { - if(configPortalActive || webPortalActive) return; - connect = abort = false; - setupConfigPortal(); - webPortalActive = true; -} - -/** - * [stopWebPortal description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::stopWebPortal() { - if(!configPortalActive && !webPortalActive) return; - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Stopping Web Portal")); - #endif - webPortalActive = false; - shutdownConfigPortal(); -} - -boolean WiFiManager::configPortalHasTimeout(){ - if(!configPortalActive) return false; - uint16_t logintvl = 30000; // how often to emit timeing out counter logging - - // handle timeout portal client check - if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){ - // debug num clients every 30s - if(millis() - timer > logintvl){ - timer = millis(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("NUM CLIENTS: "),(String)WiFi_softap_num_stations()); - #endif - } - _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts - return false; - } - - // handle timeout webclient check - if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed; - - // handle timed out - if(millis() > _configPortalStart + _configPortalTimeout){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("config portal has timed out")); - #endif - return true; // timeout bail, else do debug logging - } - else if(_debug && _debugLevel > 0) { - // log timeout time remaining every 30s - if((millis() - timer) > logintvl){ - timer = millis(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds")); - #endif - } - } - - return false; -} - -void WiFiManager::setupHTTPServer(){ - - server.reset(new WM_WebServer(_httpPort)); - - /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ - server->on(String(FPSTR(R_wifi)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleWifi, this,std::placeholders::_1,true)); - server->on(String(FPSTR(R_wifinoscan)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleWifi, this,std::placeholders::_1,false)); - server->on(String(FPSTR(R_erase)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleErase, this,std::placeholders::_1,false)); - { - using namespace std::placeholders; - server->on(String(FPSTR(R_root)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleRoot, this,_1)); - server->on(String(FPSTR(R_wifisave)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleWifiSave, this,_1)); - server->on(String(FPSTR(R_info)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleInfo, this,_1)); - server->on(String(FPSTR(R_param)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleParam, this,_1)); - server->on(String(FPSTR(R_paramsave)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleParamSave, this,_1)); - server->on(String(FPSTR(R_restart)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleReset, this,_1)); - server->on(String(FPSTR(R_exit)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleExit, this,_1)); - server->on(String(FPSTR(R_close)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleClose, this,_1)); - server->on(String(FPSTR(R_status)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleWiFiStatus, this,_1)); - server->onNotFound (std::bind(&WiFiManager::handleNotFound, this, _1)); - - server->on(String(FPSTR(R_update)).c_str(), HTTP_ANY, std::bind(&WiFiManager::handleUpdate, this, _1)); - server->on(String(FPSTR(R_updatedone)).c_str(), HTTP_POST,std::bind(&WiFiManager::handleUpdateDone, this, _1), std::bind(&WiFiManager::handleUpdating, this, _1,_2,_3,_4,_5,_6)); - } - server->begin(); // Web server start -} - -void WiFiManager::teardownHTTPServer(){ - -} - -void WiFiManager::setupDNSD(){ - dnsServer.reset(new DNSServer()); - - if(_httpPort != 80) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("http server starting with custom port: "),_httpPort); // @todo not showing ip - #endif - } - - setupHTTPServer(); - - /* Setup the DNS server redirecting all the domains to the apIP */ - dnsServer->setErrorReplyCode(DNSReplyCode::NoError); - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM("dns server started port: ",DNS_PORT); - DEBUG_WM(WM_DEBUG_DEV,F("dns server started with ip: "),WiFi.softAPIP()); // @todo not showing ip - #endif - dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); -} - -void WiFiManager::setupConfigPortal() { - setupHTTPServer(); - _lastscan = 0; // reset network scan cache - if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async -} - -boolean WiFiManager::startConfigPortal() { - String ssid = getDefaultAPName(); - return startConfigPortal(ssid.c_str(), NULL); -} - -/** - * [startConfigPortal description] - * @access public - * @param {[type]} char const *apName [description] - * @param {[type]} char const *apPassword [description] - * @return {[type]} [description] - */ -boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { - _begin(); - - if(configPortalActive){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting Config Portal FAILED, is already running")); - #endif - return false; - } - - //setup AP - _apName = apName; // @todo check valid apname ? - _apPassword = apPassword; - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting Config Portal")); - #endif - - if(_apName == "") _apName = getDefaultAPName(); - - if(!validApPassword()) return false; - - // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond - if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ - // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` - #ifdef WM_DISCONWORKAROUND - WiFi.mode(WIFI_AP_STA); - #endif - WiFi_Disconnect(); - WiFi_enableSTA(false); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Disabling STA")); - #endif - } - else { - // WiFi_enableSTA(true); - } - - // init configportal globals to known states - configPortalActive = true; - bool result = connect = abort = false; // loop flags, connect true success, abort true break - uint8_t state; - - _configPortalStart = millis(); - - // start access point - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Enabling AP")); - #endif - startAP(); - WiFiSetCountry(); - - // do AP callback if set - if ( _apcallback != NULL) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _apcallback calling")); - #endif - _apcallback(this); - } - - // init configportal - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("setupConfigPortal")); - #endif - setupConfigPortal(); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("setupDNSD")); - #endif - setupDNSD(); - - - if(!_configPortalIsBlocking){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Config Portal Running, non blocking (processing)")); - if(_configPortalTimeout > 0) DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds")); - #endif - return result; // skip blocking loop - } - - // enter blocking loop, waiting for config - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); - if(_configPortalTimeout > 0) DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds")); - #endif - - while(1){ - - // if timed out or abort, break - if(configPortalHasTimeout() || abort){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("configportal loop abort")); - #endif - shutdownConfigPortal(); - result = abort ? portalAbortResult : portalTimeoutResult; // false, false - if (_configportaltimeoutcallback != NULL) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] config portal timeout callback")); - #endif - _configportaltimeoutcallback(); // @CALLBACK - } - break; - } - - state = processConfigPortal(); - - // status change, break - // @todo what is this for, should be moved inside the processor - // I think.. this is to detect autoconnect by esp in background, there are also many open issues about autoreconnect not working - if(state != WL_IDLE_STATUS){ - result = (state == WL_CONNECTED); // true if connected - DEBUG_WM(WM_DEBUG_DEV,F("configportal loop break")); - break; - } - - if(!configPortalActive) break; - - vTaskDelay( 50 / portTICK_PERIOD_MS); - } - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_NOTIFY,F("config portal exiting")); - #endif - return result; -} - -/** - * [process description] - * @access public - * @return bool connected - */ -boolean WiFiManager::process(){ - // process mdns, esp32 not required - #if defined(WM_MDNS) && defined(ESP8266) - MDNS.update(); - #endif - - if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ - // if timed out or abort, break - if(_allowExit && (configPortalHasTimeout() || abort)){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("process loop abort")); - #endif - webPortalActive = false; - shutdownConfigPortal(); - if (_configportaltimeoutcallback != NULL) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] config portal timeout callback")); - #endif - _configportaltimeoutcallback(); // @CALLBACK - } - return false; - } - - uint8_t state = processConfigPortal(); // state is WL_IDLE or WL_CONNECTED/FAILED - return state == WL_CONNECTED; - } - return false; -} - -/** - * [processConfigPortal description] - * using esp wl_status enums as returns for now, should be fine - * returns WL_IDLE_STATUS or WL_CONNECTED/WL_CONNECT_FAILED upon connect/save flag - * - * @return {[type]} [description] - */ -uint8_t WiFiManager::processConfigPortal(){ - if(configPortalActive){ - //DNS handler - dnsServer->processNextRequest(); - } - - //HTTP handler - #ifndef WM_ASYNCWEBSERVER - server->handleClient(); - #endif - - if(_rebootNeeded) reboot(); - - // Waiting for save... - if(connect) { - connect = false; - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("processing save")); - #endif - if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. - - // skip wifi if no ssid - if(_ssid == ""){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("No ssid, skipping wifi save")); - #endif - } - else{ - // attempt sta connection to submitted _ssid, _pass - uint8_t res = connectWifi(_ssid, _pass, _connectonsave) == WL_CONNECTED; - if (res || (!_connectonsave)) { - #ifdef WM_DEBUG_LEVEL - if(!_connectonsave){ - DEBUG_WM(F("SAVED with no connect to new AP")); - } else { - DEBUG_WM(F("Connect to new AP [SUCCESS]")); - DEBUG_WM(F("Got IP Address:")); - DEBUG_WM(WiFi.localIP()); - } - #endif - - if ( _savewificallback != NULL) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _savewificallback calling")); - #endif - _savewificallback(); // @CALLBACK - } - if(!_connectonsave) return WL_IDLE_STATUS; - if(_disableConfigPortal) shutdownConfigPortal(); - return WL_CONNECTED; // CONNECT SUCCESS - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); - #endif - } - - if (_shouldBreakAfterConfig) { - - // do save callback - // @todo this is more of an exiting callback than a save, clarify when this should actually occur - // confirm or verify data was saved to make this more accurate callback - if ( _savewificallback != NULL) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] WiFi/Param save callback")); - #endif - _savewificallback(); // @CALLBACK - } - if(_disableConfigPortal) shutdownConfigPortal(); - return WL_CONNECT_FAILED; // CONNECT FAIL - } - else if(_configPortalIsBlocking){ - // clear save strings - _ssid = ""; - _pass = ""; - // if connect fails, turn sta off to stabilize AP - WiFi_Disconnect(); - WiFi_enableSTA(false); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Processing - Disabling STA")); - #endif - } - else{ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal is non blocking - remaining open")); - #endif - } - } - - return WL_IDLE_STATUS; -} - -/** - * [shutdownConfigPortal description] - * @access public - * @return bool success (softapdisconnect) - */ -bool WiFiManager::shutdownConfigPortal(){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("shutdownConfigPortal")); - #endif - - if(webPortalActive) return false; - - if(configPortalActive){ - //DNS handler - dnsServer->processNextRequest(); - } - - #ifndef WM_ASYNCWEBSERVER - //HTTP handler - server->handleClient(); - #endif - - // @todo what is the proper way to shutdown and free the server up - // debug - many open issues aobut port not clearing for use with other servers - #ifdef WM_ASYNCWEBSERVER - server->end(); - #else - server->stop(); - #endif - server.reset(); - - dnsServer->stop(); // free heap ? - dnsServer.reset(); - - WiFi.scanDelete(); // free wifi scan results - - if(!configPortalActive) return false; - - // turn off AP - // @todo bug workaround - // https://github.com/esp8266/Arduino/issues/3793 - // [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed - // still no way to reproduce reliably - - bool ret = false; - ret = WiFi.softAPdisconnect(false); - - #ifdef WM_DEBUG_LEVEL - if(!ret)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); - DEBUG_WM(WM_DEBUG_VERBOSE,F("restoring usermode"),getModeString(_usermode)); - #endif - delay(1000); - WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 - if(WiFi.status()==WL_IDLE_STATUS){ - WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Reconnect, was idle")); - #endif - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("wifi status:"),getWLStatusString(WiFi.status())); - DEBUG_WM(WM_DEBUG_VERBOSE,F("wifi mode:"),getModeString(WiFi.getMode())); - #endif - configPortalActive = false; - DEBUG_WM(WM_DEBUG_VERBOSE,F("configportal closed")); - _end(); - return ret; -} - -// @todo refactor this up into seperate functions -// one for connecting to flash , one for new client -// clean up, flow is convoluted, and causes bugs -uint8_t WiFiManager::connectWifi(String ssid, String pass, bool connect) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Connecting as wifi client...")); - #endif - uint8_t retry = 1; - uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL; - - setSTAConfig(); - //@todo catch failures in set_config - - // make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !) - // WiFi.setAutoReconnect(false); - if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect - // @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status to avoid these - - // if retry without delay (via begin()), the IDF is still busy even after returning status - // E (5130) wifi:sta is connecting, return error - // [E][WiFiSTA.cpp:221] begin(): connect failed! - - while(retry <= _connectRetries && (connRes!=WL_CONNECTED)){ - if(_connectRetries > 1){ - if(_aggresiveReconn) delay(1000); // add idle time before recon - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Connect Wifi, ATTEMPT #"),(String)retry+" of "+(String)_connectRetries); - #endif - } - // if ssid argument provided connect to that - // NOTE: this also catches preload() _defaultssid @todo rework - if (ssid != "") { - wifiConnectNew(ssid,pass,connect); - // @todo connect=false seems to disconnect sta in begin() so not sure if _connectonsave is useful at all - // skip wait if not connecting - // if(connect){ - if(_saveTimeout > 0){ - connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop - } - else { - connRes = waitForConnectResult(); - } - // } - } - else { - // connect using saved ssid if there is one - if (WiFi_hasAutoConnect()) { - wifiConnectDefault(); - connRes = waitForConnectResult(); - } - else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("No wifi saved, skipping")); - #endif - } - } - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); - #endif - retry++; -} - -// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 -#ifdef NO_EXTRA_4K_HEAP - // do WPS, if WPS options enabled and not connected and no password was supplied - // @todo this seems like wrong place for this, is it a fallback or option? - if (_tryWPS && connRes != WL_CONNECTED && pass == "") { - startWPS(); - // should be connected at the end of WPS - connRes = waitForConnectResult(); - } -#endif - - if(connRes != WL_SCAN_COMPLETED){ - updateConxResult(connRes); - } - - return connRes; -} - -/** - * connect to a new wifi ap - * @since $dev - * @param String ssid - * @param String pass - * @return bool success - * @return connect only save if false - */ -bool WiFiManager::wifiConnectNew(String ssid, String pass,bool connect){ - bool ret = false; - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_DEV,F("CONNECTED: "),WiFi.status() == WL_CONNECTED ? "Y" : "NO"); - DEBUG_WM(F("Connecting to NEW AP:"),ssid); - DEBUG_WM(WM_DEBUG_DEV,F("Using Password:"),pass); - #endif - WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) - WiFi.persistent(true); - - if (_findBestRSSI) { - WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); - WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("find best RSSI: TRUE")); - #endif - if (!_numNetworks) - WiFi_scanNetworks(false, false); // scan in case this gets called before any scans - - int n = _numNetworks; - if (n == 0) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("No networks found")); - #endif - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(n, F("networks found")); - #endif - int bestConnection = -1; - // Find best RSSI AP for given SSID - for (int i = 0; i < n; i++) { - if (ssid == WiFi.SSID(i)) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(String(F("SSID ")) + ssid + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(i)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + - String(F(" and channel: ")) + String(WiFi.channel(i))); - #endif - if (bestConnection == -1) { - bestConnection = i; - } else { - if (WiFi.RSSI(i) > WiFi.RSSI(bestConnection)) { - bestConnection = i; - } - } - } - } - if (bestConnection == -1) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("No network found with SSID: "), ssid); - #endif - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(String(F("Trying to connect to SSID ")) + ssid + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(bestConnection)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(bestConnection)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(bestConnection) + - String(F(" and channel: ")) + String(WiFi.channel(bestConnection))); - #endif - ret = WiFi.begin(ssid.c_str(), pass.c_str(), 0, WiFi.BSSID(bestConnection), connect); - } - } - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("find best RSSI: FALSE")); - #endif - ret = WiFi.begin(ssid.c_str(), pass.c_str(), 0, NULL, connect); - } - - WiFi.persistent(false); - #ifdef WM_DEBUG_LEVEL - if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi begin failed")); - #endif - return ret; -} - -/** - * connect to stored wifi - * @since dev - * @return bool success - */ -bool WiFiManager::wifiConnectDefault(){ - bool ret = false; - - String ssid = WiFi_SSID(true); - String pass = WiFi_psk(true); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Connecting to SAVED AP:"),ssid); - DEBUG_WM(WM_DEBUG_DEV,F("Using Password:"),pass); - #endif - - ret = WiFi_enableSTA(true,storeSTAmode); - delay(500); // THIS DELAY ? - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Mode after delay: "),getModeString(WiFi.getMode())); - if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi enableSta failed")); - #endif - - if (_findBestRSSI) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("find best RSSI: TRUE")); - #endif - if (!_numNetworks) - WiFi_scanNetworks(false, false); // scan in case this gets called before any scans - - int n = _numNetworks; - if (n == 0) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("No networks found")); - #endif - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(n, F("networks found")); - #endif - int bestConnection = -1; - // Find best RSSI AP for given SSID - for (int i = 0; i < n; i++) { - if (ssid == WiFi.SSID(i)) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(String(F("SSID ")) + ssid + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(i)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + - String(F(" and channel: ")) + String(WiFi.channel(i))); - #endif - if (bestConnection == -1) { - bestConnection = i; - } else { - if (WiFi.RSSI(i) > WiFi.RSSI(bestConnection)) { - bestConnection = i; - } - } - } - } - if (bestConnection == -1) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("No network found with SSID: "), ssid); - #endif - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(String(F("Trying to connect to SSID ")) + ssid + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(bestConnection)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(bestConnection)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(bestConnection) + - String(F(" and channel: ")) + String(WiFi.channel(bestConnection))); - #endif - ret = WiFi.begin(ssid.c_str(), pass.c_str(), 0, WiFi.BSSID(bestConnection), true); - } - } - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("find best RSSI: FALSE")); - #endif - ret = WiFi.begin(); - } - - #ifdef WM_DEBUG_LEVEL - if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi begin failed")); - #endif - - return ret; -} - - -/** - * set sta config if set - * @since $dev - * @return bool success - */ -bool WiFiManager::setSTAConfig(){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("STA static IP:"),_sta_static_ip); - #endif - bool ret = true; - if (_sta_static_ip) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Custom static IP/GW/Subnet/DNS")); - #endif - if(_sta_static_dns) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Custom static DNS")); - #endif - ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns); - } - else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet")); - #endif - ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn); - } - - #ifdef WM_DEBUG_LEVEL - if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi config failed")); - else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); - #endif - } - else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("setSTAConfig static ip not set, skipping")); - #endif - } - return ret; -} - -// @todo change to getLastFailureReason and do not touch conxresult -void WiFiManager::updateConxResult(uint8_t status){ - // hack in wrong password detection - _lastconxresult = status; - #ifdef ESP8266 - if(_lastconxresult == WL_CONNECT_FAILED){ - if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD){ - _lastconxresult = WL_STATION_WRONG_PASSWORD; - } - } - #elif defined(ESP32) - // if(_lastconxresult == WL_CONNECT_FAILED){ - if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("lastconxresulttmp:"),getWLStatusString(_lastconxresulttmp)); - #endif - if(_lastconxresulttmp != WL_IDLE_STATUS){ - _lastconxresult = _lastconxresulttmp; - // _lastconxresulttmp = WL_IDLE_STATUS; - } - } - DEBUG_WM(WM_DEBUG_DEV,F("lastconxresult:"),getWLStatusString(_lastconxresult)); - #endif -} - - -uint8_t WiFiManager::waitForConnectResult() { - #ifdef WM_DEBUG_LEVEL - if(_connectTimeout > 0) DEBUG_WM(WM_DEBUG_DEV,_connectTimeout,F("ms connectTimeout set")); - #endif - return waitForConnectResult(_connectTimeout); -} - -/** - * waitForConnectResult - * @param uint16_t timeout in seconds - * @return uint8_t WL Status - */ -uint8_t WiFiManager::waitForConnectResult(uint32_t timeout) { - if (timeout == 0){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult...")); - #endif - return WiFi.waitForConnectResult(); - } - - unsigned long timeoutmillis = millis() + timeout; - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); - #endif - uint8_t status = WiFi.status(); - - while(millis() < timeoutmillis) { - status = WiFi.status(); - // @todo detect additional states, connect happens, then dhcp then get ip, there is some delay here, make sure not to timeout if waiting on IP - if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { - return status; - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM (WM_DEBUG_VERBOSE,F(".")); - #endif - delay(100); - } - return status; -} - -// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 -#ifdef NO_EXTRA_4K_HEAP -void WiFiManager::startWPS() { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("START WPS")); - #endif - #ifdef ESP8266 - WiFi.beginWPSConfig(); - #else - // @todo - #endif - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("END WPS")); - #endif -} -#endif - -String WiFiManager::getHTTPHead(String title){ - String page; - page += FPSTR(HTTP_HEAD_START); - page.replace(FPSTR(T_v), title); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - - if(_bodyClass != ""){ - String p = FPSTR(HTTP_HEAD_END); - p.replace(FPSTR(T_c), _bodyClass); // add class str - page += p; - } - else { - page += FPSTR(HTTP_HEAD_END); - } - - return page; -} - -void WiFiManager::HTTPSend(AsyncWebServerRequest *request, String page){ - AsyncWebServerResponse *response = request->beginResponse(200,FPSTR(HTTP_HEAD_CT), page); - response->addHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - request->send(response); -} - -/** - * HTTPD handler for page requests - */ -void WiFiManager::handleRequest() { - _webPortalAccessed = millis(); - - // TESTING HTTPD AUTH RFC 2617 - // BASIC_AUTH will hold onto creds, hard to "logout", but convienent - // DIGEST_AUTH will require new auth often, and nonce is random - // bool authenticate(const char * username, const char * password); - // bool authenticateDigest(const String& username, const String& H1); - // void requestAuthentication(HTTPAuthMethod mode = BASIC_AUTH, const char* realm = NULL, const String& authFailMsg = String("") ); -} - -/** - * HTTPD CALLBACK root or redirect to captive portal - */ -void WiFiManager::handleRoot(AsyncWebServerRequest *request) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Root")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - if (captivePortal(request)) return; // If captive portal redirect instead of displaying the page - handleRequest(); - String page = getHTTPHead(_title); // @token options @todo replace options with title - String str = FPSTR(HTTP_ROOT_MAIN); // @todo custom title - str.replace(FPSTR(T_t),_title); - str.replace(FPSTR(T_v),configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading @todo use hostname? - page += str; - page += FPSTR(HTTP_PORTAL_OPTIONS); - page += getMenuOut(); - reportStatus(page); - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - if(_preloadwifiscan) WiFi_scanNetworks(_scancachetime,true); // preload wifiscan throttled, async - // @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load - // I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone - // if we can detect these and ignore them that would be great, since they come from the captive portal redirect maybe there is a refferer -} - -/** - * HTTPD CALLBACK Wifi config page handler - */ -void WiFiManager::handleWifi(AsyncWebServerRequest *request,bool scan = true) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Wifi")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi - if (scan) { - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_DEV,"refresh flag:",request->hasArg(F("refresh"))); - #endif - WiFi_scanNetworks(request->hasArg(F("refresh")),true); //wifiscan, force if arg refresh - page += getScanItemOut(); - } - String pitem = ""; - - pitem = FPSTR(HTTP_FORM_START); - pitem.replace(FPSTR(T_v), F("wifisave")); // set form action - page += pitem; - - pitem = FPSTR(HTTP_FORM_WIFI); - pitem.replace(FPSTR(T_v), WiFi_SSID()); - - if(_showPassword){ - pitem.replace(FPSTR(T_p), WiFi_psk()); - } - else if(WiFi_psk() != ""){ - pitem.replace(FPSTR(T_p),FPSTR(S_passph)); - } - else { - pitem.replace(FPSTR(T_p),""); - } - - page += pitem; - - page += getStaticOut(); - page += FPSTR(HTTP_FORM_WIFI_END); - if(_paramsInWifi && _paramsCount>0){ - page += FPSTR(HTTP_FORM_PARAM_HEAD); - page += getParamOut(); - } - page += FPSTR(HTTP_FORM_END); - page += FPSTR(HTTP_SCAN_LINK); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - reportStatus(page); - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Sent config page")); - #endif -} - -/** - * HTTPD CALLBACK Wifi param page handler - */ -void WiFiManager::handleParam(AsyncWebServerRequest *request){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Param")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi - - String pitem = ""; - - pitem = FPSTR(HTTP_FORM_START); - pitem.replace(FPSTR(T_v), F("paramsave")); - page += pitem; - - page += getParamOut(); - page += FPSTR(HTTP_FORM_END); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - reportStatus(page); - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Sent param page")); - #endif -} - - -String WiFiManager::getMenuOut(){ - String page; - - for(auto menuId :_menuIds ){ - if((String)_menutokens[menuId] == "param" && _paramsCount == 0) continue; // no params set, omit params from menu, @todo this may be undesired by someone, use only menu to force? - if((String)_menutokens[menuId] == "custom" && _customMenuHTML!=NULL){ - page += _customMenuHTML; - continue; - } - page += HTTP_PORTAL_MENU[menuId]; - delay(0); - } - - return page; -} - -// // is it possible in softap mode to detect aps without scanning -// bool WiFiManager::WiFi_scanNetworksForAP(bool force){ -// WiFi_scanNetworks(force); -// } - -void WiFiManager::WiFi_scanComplete(int networksFound){ - _lastscan = millis(); - _numNetworks = networksFound; - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); - #endif -} - -bool WiFiManager::WiFi_scanNetworks(){ - return WiFi_scanNetworks(false,true); -} - -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); -} -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime,true); -} -bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_DEV,"scanNetworks async:",async == true); - // DEBUG_WM(WM_DEBUG_DEV,_numNetworks,(millis()-_lastscan )); - // DEBUG_WM(WM_DEBUG_DEV,"scanNetworks force:",force == true); - #endif - - if(_numNetworks == 0 && _autoforcerescan){ - DEBUG_WM(WM_DEBUG_DEV,"NO APs found forcing new scan"); - force = true; - } - - // if scan is empty or stale (last scantime > _scancachetime), this avoids fast reloading wifi page and constant scan delayed page loads appearing to freeze. - if(!_lastscan || _lastscan == 0 || (_lastscan>0 && (millis()-_lastscan > _scancachetime))){ - force = true; - } - //force = _lastscan == 0; - - if(force){ - int8_t res; - _startscan = millis(); - if(async && _asyncScan){ - #ifdef ESP8266 - #ifndef WM_NOASYNC // no async available < 2.4.0 - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); - #endif - using namespace std::placeholders; // for `_1` - WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); - #else - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan SYNC started")); - res = WiFi.scanNetworks(); - #endif - #else - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); - #endif - res = WiFi.scanNetworks(true); - #endif - return false; - } - else{ - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan SYNC started")); - res = WiFi.scanNetworks(); - } - if(res == WIFI_SCAN_FAILED){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] scan failed")); - #endif - } - else if(res == WIFI_SCAN_RUNNING){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] scan waiting")); - #endif - while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,"."); - #endif - delay(100); - } - _numNetworks = WiFi.scanComplete(); - } - else if(res >=0 ) _numNetworks = res; - _lastscan = millis(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - #endif - return true; - } - else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Scan is cached"),(String)(millis()-_lastscan )+" ms ago"); - #endif - } - return false; -} - -void WiFiManager::resetScan(){ - _numNetworks = 0; -} - -String WiFiManager::WiFiManager::getScanItemOut(){ - String page; - - if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans - - int n = _numNetworks; - if (n == 0) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("No networks found")); - #endif - page += FPSTR(S_nonetworks); // @token nonetworks - page += F("

"); - } - else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(n,F("networks found")); - #endif - //sort networks - int indices[n]; - for (int i = 0; i < n; i++) { - indices[i] = i; - } - - // RSSI SORT - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { - std::swap(indices[i], indices[j]); - } - } - } - - /* test std:sort - std::sort(indices, indices + n, [](const int & a, const int & b) -> bool - { - return WiFi.RSSI(a) > WiFi.RSSI(b); - }); - */ - - // remove duplicates ( must be RSSI sorted ) - if (_removeDuplicateAPs) { - String cssid; - for (int i = 0; i < n; i++) { - if (indices[i] == -1) continue; - cssid = WiFi.SSID(indices[i]); - for (int j = i + 1; j < n; j++) { - if (cssid == WiFi.SSID(indices[j])) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); - #endif - indices[j] = -1; // set dup aps to index -1 - } - } - } - } - - // token precheck, to speed up replacements on large ap lists - String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); - - // toggle icons with percentage - HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); - HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); - HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); - HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); - - // set token precheck flags - bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; - bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; - bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; - bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; - bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; - - //display networks in page - for (int i = 0; i < n; i++) { - if (indices[i] == -1) continue; // skip dups - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); - #endif - - int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); - uint8_t enc_type = WiFi.encryptionType(indices[i]); - - if (_minimumQuality == -1 || _minimumQuality < rssiperc) { - String item = HTTP_ITEM_STR; - if(WiFi.SSID(indices[i]) == ""){ - // Serial.println(WiFi.BSSIDstr(indices[i])); - continue; // No idea why I am seeing these, lets just skip them for now - } - item.replace(FPSTR(T_V), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding - item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]),true)); // ssid no encoding - if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); - if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 - if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db - if(tok_q) item.replace(FPSTR(T_q), (String)int(round(map(rssiperc,0,100,1,4)))); //quality icon 1-4 - if(tok_i){ - if (enc_type != WM_WIFIOPEN) { - item.replace(FPSTR(T_i), F("l")); - } else { - item.replace(FPSTR(T_i), ""); - } - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,item); - #endif - page += item; - delay(0); - } else { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); - #endif - } - - } - page += FPSTR(HTTP_BR); - } - - return page; -} - -String WiFiManager::getIpForm(String id, String title, String value){ - String item = FPSTR(HTTP_FORM_LABEL); - item += FPSTR(HTTP_FORM_PARAM); - item.replace(FPSTR(T_i), id); - item.replace(FPSTR(T_n), id); - item.replace(FPSTR(T_p), FPSTR(T_t)); - // item.replace(FPSTR(T_p), default); - item.replace(FPSTR(T_t), title); - item.replace(FPSTR(T_l), F("15")); - item.replace(FPSTR(T_v), value); - item.replace(FPSTR(T_c), ""); - return item; -} - -String WiFiManager::getStaticOut(){ - String page; - if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("_staShowStaticFields")); - #endif - page += FPSTR(HTTP_FORM_STATIC_HEAD); - // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not - page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip - // WiFi.localIP().toString(); - page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw - // WiFi.gatewayIP().toString(); - page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet - // WiFi.subnetMask().toString(); - } - - if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ - page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns - } - - if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css - - return page; -} - -String WiFiManager::getParamOut(){ - String page; - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("getParamOut"),_paramsCount); - #endif - - if(_paramsCount > 0){ - - String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); - HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); - bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_I)) > 0; - bool tok_i = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; - bool tok_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; - bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; - bool tok_t = HTTP_PARAM_temp.indexOf(FPSTR(T_t)) > 0; - bool tok_l = HTTP_PARAM_temp.indexOf(FPSTR(T_l)) > 0; - bool tok_v = HTTP_PARAM_temp.indexOf(FPSTR(T_v)) > 0; - bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; - - char valLength[5]; - - for (int i = 0; i < _paramsCount; i++) { - //Serial.println((String)_params[i]->_length); - if (_params[i] == NULL || _params[i]->_length > 99999) { - // try to detect param scope issues, doesnt always catch but works ok - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); - #endif - return ""; - } - } - - // add the extra parameters to the form - for (int i = 0; i < _paramsCount; i++) { - // label before or after, @todo this could be done via floats or CSS and eliminated - String pitem; - switch (_params[i]->getLabelPlacement()) { - case WFM_LABEL_BEFORE: - pitem = FPSTR(HTTP_FORM_LABEL); - pitem += FPSTR(HTTP_FORM_PARAM); - break; - case WFM_LABEL_AFTER: - pitem = FPSTR(HTTP_FORM_PARAM); - pitem += FPSTR(HTTP_FORM_LABEL); - break; - default: - // WFM_NO_LABEL - pitem = FPSTR(HTTP_FORM_PARAM); - break; - } - - // Input templating - // "
"; - // if no ID use customhtml for item, else generate from param string - if (_params[i]->getID() != NULL) { - if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number - if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name - if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias - if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token - if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label - snprintf(valLength, 5, "%d", _params[i]->getValueLength()); - if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length - if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value - if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff - } else { - pitem = _params[i]->getCustomHTML(); - } - - page += pitem; - } - } - - return page; -} - -void WiFiManager::handleWiFiStatus(AsyncWebServerRequest *request){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP WiFi status ")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - String page; - // String page = "{\"result\":true,\"count\":1}"; - #ifdef WM_JSTEST - page = FPSTR(HTTP_JS); - #endif - HTTPSend(request,page); -} - -/** - * HTTPD CALLBACK save form and redirect to WLAN config page again - */ -void WiFiManager::handleWifiSave(AsyncWebServerRequest *request) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP WiFi save ")); - DEBUG_WM(WM_DEBUG_DEV,F("Method:"),request->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - - //SAVE/connect here - _ssid = request->arg(F("s")).c_str(); - _pass = request->arg(F("p")).c_str(); - - if(_ssid == "" && _pass != ""){ - _ssid = WiFi_SSID(true); // password change, placeholder ssid, @todo compare pass to old?, confirm ssid is clean - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Detected WiFi password change")); - #endif - } - - #ifdef WM_DEBUG_LEVEL - String requestinfo = "SERVER_REQUEST\n----------------\n"; - requestinfo += "URI: "; - requestinfo += request->url(); - requestinfo += "\nMethod: "; - requestinfo += (request->method() == HTTP_GET) ? "GET" : "POST"; - requestinfo += "\nArguments: "; - requestinfo += request->args(); - requestinfo += "\n"; - for (uint8_t i = 0; i < request->args(); i++) { - requestinfo += " " + request->argName(i) + ": " + request->arg(i) + "\n"; - } - - DEBUG_WM(WM_DEBUG_MAX,requestinfo); - #endif - - // set static ips from server args - if (request->arg(FPSTR(S_ip)) != "") { - //_sta_static_ip.fromString(request->arg(FPSTR(S_ip)); - String ip = request->arg(FPSTR(S_ip)); - optionalIPFromString(&_sta_static_ip, ip.c_str()); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("static ip:"),ip); - #endif - } - if (request->arg(FPSTR(S_gw)) != "") { - String gw = request->arg(FPSTR(S_gw)); - optionalIPFromString(&_sta_static_gw, gw.c_str()); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("static gateway:"),gw); - #endif - } - if (request->arg(FPSTR(S_sn)) != "") { - String sn = request->arg(FPSTR(S_sn)); - optionalIPFromString(&_sta_static_sn, sn.c_str()); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("static netmask:"),sn); - #endif - } - if (request->arg(FPSTR(S_dns)) != "") { - String dns = request->arg(FPSTR(S_dns)); - optionalIPFromString(&_sta_static_dns, dns.c_str()); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("static DNS:"),dns); - #endif - } - - if (_presavewificallback != NULL) { - _presavewificallback(); // @CALLBACK - } - - if(_paramsInWifi) doParamSave(request); - - String page; - - if(_ssid == ""){ - page = getHTTPHead(FPSTR(S_titlewifisettings)); // @token titleparamsaved - page += FPSTR(HTTP_PARAMSAVED); - } - else { - page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved - page += FPSTR(HTTP_SAVED); - } - - if(_showBack) page += FPSTR(HTTP_BACKBTN); - page += FPSTR(HTTP_END); - - //server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); // @HTTPHEAD send cors - HTTPSend(request,page); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Sent wifi save page")); - #endif - - connect = true; //signal ready to connect/reset process in processConfigPortal -} - -void WiFiManager::handleParamSave(AsyncWebServerRequest *request) { - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Param save ")); - #endif - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Method:"),request->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - - doParamSave(request); - - String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved - page += FPSTR(HTTP_PARAMSAVED); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Sent param save page")); - #endif -} - -void WiFiManager::doParamSave(AsyncWebServerRequest *request){ - // @todo use new callback for before paramsaves, is this really needed? - if ( _presaveparamscallback != NULL) { - _presaveparamscallback(); // @CALLBACK - } - - //parameters - if(_paramsCount > 0){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Parameters")); - DEBUG_WM(WM_DEBUG_VERBOSE,FPSTR(D_HR)); - #endif - - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL || _params[i]->_length > 99999) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); - #endif - break; // @todo might not be needed anymore - } - //read parameter from server - String name = (String)FPSTR(S_parampre)+(String)i; - String value; - if(request->hasArg(name.c_str())) { - value = request->arg(name); - } else { - value = request->arg(_params[i]->getID()); - } - - //store it in params array - value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); - #endif - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,FPSTR(D_HR)); - #endif - } - - if ( _saveparamscallback != NULL) { - _saveparamscallback(); // @CALLBACK - } - -} - -/** - * HTTPD CALLBACK info page - */ -void WiFiManager::handleInfo(AsyncWebServerRequest *request) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Info")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - //handleRequest(); - String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo - reportStatus(page); - - uint16_t infos = 0; - - //@todo convert to enum or refactor to strings - //@todo wrap in build flag to remove all info code for memory saving - #ifdef ESP8266 - infos = 28; - String infoids[] = { - F("esphead"), - F("uptime"), - F("chipid"), - F("fchipid"), - F("idesize"), - F("flashsize"), - F("corever"), - F("bootver"), - F("cpufreq"), - F("freeheap"), - F("memsketch"), - F("memsmeter"), - F("lastreset"), - F("wifihead"), - F("conx"), - F("stassid"), - F("staip"), - F("stagw"), - F("stasub"), - F("dnss"), - F("host"), - F("stamac"), - F("autoconx"), - F("wifiaphead"), - F("apssid"), - F("apip"), - F("apbssid"), - F("apmac") - }; - - #elif defined(ESP32) - // add esp_chip_info ? - infos = 27; - String infoids[] = { - F("esphead"), - F("uptime"), - F("chipid"), - F("chiprev"), - F("idesize"), - F("flashsize"), - F("cpufreq"), - F("freeheap"), - F("memsketch"), - F("memsmeter"), - F("lastreset"), - F("temp"), - // F("hall"), - F("wifihead"), - F("conx"), - F("stassid"), - F("staip"), - F("stagw"), - F("stasub"), - F("dnss"), - F("host"), - F("stamac"), - F("apssid"), - F("wifiaphead"), - F("apip"), - F("apmac"), - F("aphost"), - F("apbssid") - }; - #endif - - for(size_t i=0; i"); - - page += F("

About


"); - page += getInfoData("aboutver"); - page += getInfoData("aboutarduinover"); - page += getInfoData("aboutidfver"); - page += getInfoData("aboutdate"); - page += F("
"); - - if(_showInfoUpdate){ - page += HTTP_PORTAL_MENU[8]; - page += HTTP_PORTAL_MENU[9]; - } - if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - page += FPSTR(HTTP_HELP); - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("Sent info page")); - #endif -} - -String WiFiManager::getInfoData(String id){ - - String p; - if(id==F("esphead")){ - p = FPSTR(HTTP_INFO_esphead); - #ifdef ESP32 - p.replace(FPSTR(T_1), (String)ESP.getChipModel()); - #endif - } - else if(id==F("wifihead")){ - p = FPSTR(HTTP_INFO_wifihead); - p.replace(FPSTR(T_1),getModeString(WiFi.getMode())); - } - else if(id==F("uptime")){ - // subject to rollover! - p = FPSTR(HTTP_INFO_uptime); - p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); - p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); - } - else if(id==F("chipid")){ - p = FPSTR(HTTP_INFO_chipid); - p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); - } - #ifdef ESP32 - else if(id==F("chiprev")){ - p = FPSTR(HTTP_INFO_chiprev); - String rev = (String)ESP.getChipRevision(); - #ifdef _SOC_EFUSE_REG_H_ - String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); - p.replace(FPSTR(T_1),rev+"
"+revb); - #else - p.replace(FPSTR(T_1),rev); - #endif - } - #endif - #ifdef ESP8266 - else if(id==F("fchipid")){ - p = FPSTR(HTTP_INFO_fchipid); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); - } - #endif - else if(id==F("idesize")){ - p = FPSTR(HTTP_INFO_idesize); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); - } - else if(id==F("flashsize")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_flashsize); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); - #elif defined ESP32 - p = FPSTR(HTTP_INFO_psrsize); - p.replace(FPSTR(T_1),(String)ESP.getPsramSize()); - #endif - } - else if(id==F("corever")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_corever); - p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); - #endif - } - #ifdef ESP8266 - else if(id==F("bootver")){ - p = FPSTR(HTTP_INFO_bootver); - p.replace(FPSTR(T_1),(String)system_get_boot_version()); - } - #endif - else if(id==F("cpufreq")){ - p = FPSTR(HTTP_INFO_cpufreq); - p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); - } - else if(id==F("freeheap")){ - p = FPSTR(HTTP_INFO_freeheap); - p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); - } - else if(id==F("memsketch")){ - p = FPSTR(HTTP_INFO_memsketch); - p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); - } - else if(id==F("memsmeter")){ - p = FPSTR(HTTP_INFO_memsmeter); - p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); - } - else if(id==F("lastreset")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_lastreset); - p.replace(FPSTR(T_1),(String)ESP.getResetReason()); - #elif defined(ESP32) && defined(_ROM_RTC_H_) - // requires #include - p = FPSTR(HTTP_INFO_lastreset); - for(int i=0;i<2;i++){ - int reason = rtc_get_reset_reason(i); - String tok = (String)T_ss+(String)(i+1)+(String)T_es; - switch (reason) - { - //@todo move to array - case 1 : p.replace(tok,F("Vbat power on reset"));break; - case 3 : p.replace(tok,F("Software reset digital core"));break; - case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; - case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; - case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; - case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; - case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; - case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; - case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; - case 11 : p.replace(tok,F("Time Group reset CPU"));break; - case 12 : p.replace(tok,F("Software reset CPU"));break; - case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; - case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; - case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; - case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; - default : p.replace(tok,F("NO_MEAN")); - } - } - #endif - } - else if(id==F("apip")){ - p = FPSTR(HTTP_INFO_apip); - p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); - } - else if(id==F("apmac")){ - p = FPSTR(HTTP_INFO_apmac); - p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); - } - #ifdef ESP32 - else if(id==F("aphost")){ - p = FPSTR(HTTP_INFO_aphost); - p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); - } - #endif - #ifndef WM_NOSOFTAPSSID - #ifdef ESP8266 - else if(id==F("apssid")){ - p = FPSTR(HTTP_INFO_apssid); - p.replace(FPSTR(T_1),htmlEntities(WiFi.softAPSSID())); - } - #endif - #endif - else if(id==F("apbssid")){ - p = FPSTR(HTTP_INFO_apbssid); - p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); - } - // softAPgetHostname // esp32 - // softAPSubnetCIDR - // softAPNetworkID - // softAPBroadcastIP - - else if(id==F("stassid")){ - p = FPSTR(HTTP_INFO_stassid); - p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); - } - else if(id==F("staip")){ - p = FPSTR(HTTP_INFO_staip); - p.replace(FPSTR(T_1),WiFi.localIP().toString()); - } - else if(id==F("stagw")){ - p = FPSTR(HTTP_INFO_stagw); - p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); - } - else if(id==F("stasub")){ - p = FPSTR(HTTP_INFO_stasub); - p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); - } - else if(id==F("dnss")){ - p = FPSTR(HTTP_INFO_dnss); - p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); - } - else if(id==F("host")){ - p = FPSTR(HTTP_INFO_host); - #ifdef ESP32 - p.replace(FPSTR(T_1),WiFi.getHostname()); - #else - p.replace(FPSTR(T_1),WiFi.hostname()); - #endif - } - else if(id==F("stamac")){ - p = FPSTR(HTTP_INFO_stamac); - p.replace(FPSTR(T_1),WiFi.macAddress()); - } - else if(id==F("conx")){ - p = FPSTR(HTTP_INFO_conx); - p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); - } - #ifdef ESP8266 - else if(id==F("autoconx")){ - p = FPSTR(HTTP_INFO_autoconx); - p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); - } - #endif - #if defined(ESP32) && !defined(WM_NOTEMP) - else if(id==F("temp")){ - // temperature is not calibrated, varying large offsets are present, use for relative temp changes only - p = FPSTR(HTTP_INFO_temp); - p.replace(FPSTR(T_1),(String)temperatureRead()); - p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8f)); - } - // else if(id==F("hall")){ - // p = FPSTR(HTTP_INFO_hall); - // p.replace(FPSTR(T_1),(String)hallRead()); // hall sensor reads can cause issues with adcs - // } - #endif - else if(id==F("aboutver")){ - p = FPSTR(HTTP_INFO_aboutver); - p.replace(FPSTR(T_1),FPSTR(WM_VERSION_STR)); - } - else if(id==F("aboutarduinover")){ - #ifdef VER_ARDUINO_STR - p = FPSTR(HTTP_INFO_aboutarduino); - p.replace(FPSTR(T_1),String(VER_ARDUINO_STR)); - #endif - } - // else if(id==F("aboutidfver")){ - // #ifdef VER_IDF_STR - // p = FPSTR(HTTP_INFO_aboutidf); - // p.replace(FPSTR(T_1),String(VER_IDF_STR)); - // #endif - // } - else if(id==F("aboutsdkver")){ - p = FPSTR(HTTP_INFO_sdkver); - #ifdef ESP32 - p.replace(FPSTR(T_1),(String)esp_get_idf_version()); - // p.replace(FPSTR(T_1),(String)system_get_sdk_version()); // deprecated - #else - p.replace(FPSTR(T_1),(String)system_get_sdk_version()); - #endif - } - else if(id==F("aboutdate")){ - p = FPSTR(HTTP_INFO_aboutdate); - p.replace(FPSTR(T_1),String(__DATE__ " " __TIME__)); - } - return p; -} - -/** - * HTTPD CALLBACK exit, closes configportal if blocking, if non blocking undefined - */ -void WiFiManager::handleExit(AsyncWebServerRequest *request) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Exit")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit - page += FPSTR(S_exiting); // @token exiting - // ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) - AsyncWebServerResponse *response = request->beginResponse(200,FPSTR(HTTP_HEAD_CT), page); - response->addHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); - request->send(response); - delay(2000); - abort = true; -} - -/** - * HTTPD CALLBACK reset page - */ -void WiFiManager::handleReset(AsyncWebServerRequest *request) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Reset")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset - page += FPSTR(S_resetting); //@token resetting - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("RESETTING ESP")); - #endif - _rebootNeeded = true; -} - -/** - * HTTPD CALLBACK erase page - */ - -// void WiFiManager::handleErase() { -// handleErase(false); -// } -void WiFiManager::handleErase(AsyncWebServerRequest *request,bool opt = false) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_NOTIFY,F("<- HTTP Erase")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase - - bool ret = erase(opt); - - if(ret) page += FPSTR(S_resetting); // @token resetting - else { - page += FPSTR(S_error); // @token erroroccur - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); - #endif - } - - page += FPSTR(HTTP_END); - HTTPSend(request,page); - - if(ret){ - _rebootNeeded = true; - } -} - -/** - * HTTPD CALLBACK 404 - */ -void WiFiManager::handleNotFound(AsyncWebServerRequest *request) { - if (captivePortal(request)) return; // If captive portal redirect instead of displaying the page - handleRequest(); - String message = FPSTR(S_notfound); // @token notfound - - bool verbose404 = false; // show info in 404 body, uri,method, args - if(verbose404){ - message += FPSTR(S_uri); // @token uri - message += request->url(); - message += FPSTR(S_method); // @token method - message += ( request->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); - message += FPSTR(S_args); // @token args - message += request->args(); - message += F("\n"); - - for ( uint8_t i = 0; i < request->args(); i++ ) { - message += " " + request->argName ( i ) + ": " + request->arg ( i ) + "\n"; - } - } - AsyncWebServerResponse *response = request->beginResponse(404,FPSTR(HTTP_HEAD_CT2), message); - response->addHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); - response->addHeader(F("Pragma"), F("no-cache")); - response->addHeader(F("Expires"), F("-1")); - request->send(response); -} - -/** - * HTTPD redirector - * Redirect to captive portal if we got a request for another domain. - * Return true in that case so the page handler do not try to handle the request again. - */ -boolean WiFiManager::captivePortal(AsyncWebServerRequest *request) { - - if(!_enableCaptivePortal || !configPortalActive) return false; // skip redirections if cp not enabled or not in ap mode - - String serverLoc = toStringIp(request->client()->localIP()); - - #ifdef WM_DEBUG_LEVEL - //DEBUG_WM(WM_DEBUG_DEV,"-> " + request->host()); - //DEBUG_WM(WM_DEBUG_DEV,"serverLoc " + serverLoc); - #endif - - // fallback for ipv6 bug - if(serverLoc == "0.0.0.0"){ - if ((WiFi.status()) != WL_CONNECTED) - serverLoc = toStringIp(WiFi.softAPIP()); - else - serverLoc = toStringIp(WiFi.localIP()); - } - - if(_httpPort != 80) serverLoc += ":" + (String)_httpPort; // add port if not default - bool doredirect = serverLoc != request->host(); // redirect if hostheader not server ip, prevent redirect loops - - if (doredirect) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- Request redirected to captive portal")); - DEBUG_WM(WM_DEBUG_DEV,"serverLoc " + serverLoc); - #endif - AsyncWebServerResponse *response = request->beginResponse(302,FPSTR(HTTP_HEAD_CT2), ""); - response->addHeader(F("Location"), (String)F("http://") + serverLoc); - request->send(response); - return true; - } - return false; -} - -void WiFiManager::stopCaptivePortal(){ - _enableCaptivePortal= false; - // @todo maybe disable configportaltimeout(optional), or just provide callback for user -} - -// HTTPD CALLBACK, handle close, stop captive portal, if not enabled undefined -void WiFiManager::handleClose(AsyncWebServerRequest *request){ - DEBUG_WM(WM_DEBUG_VERBOSE,F("Disabling Captive Portal")); - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - stopCaptivePortal(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP close")); - #endif - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose - page += FPSTR(S_closing); // @token closing - HTTPSend(request,page); -} - -void WiFiManager::reportStatus(String &page){ - // updateConxResult(WiFi.status()); // @todo: this defeats the purpose of last result, update elsewhere or add logic here - DEBUG_WM(WM_DEBUG_DEV,F("[WIFI] reportStatus prev:"),getWLStatusString(_lastconxresult)); - DEBUG_WM(WM_DEBUG_DEV,F("[WIFI] reportStatus current:"),getWLStatusString(WiFi.status())); - String str; - if (WiFi_SSID() != ""){ - if (WiFi.status()==WL_CONNECTED){ - str = FPSTR(HTTP_STATUS_ON); - str.replace(FPSTR(T_i),WiFi.localIP().toString()); - str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); - } - else { - str = FPSTR(HTTP_STATUS_OFF); - str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); - if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ - // wrong password - str.replace(FPSTR(T_c),"D"); // class - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); - } - else if(_lastconxresult == WL_NO_SSID_AVAIL){ - // connect failed, or ap not found - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); - } - else if(_lastconxresult == WL_CONNECT_FAILED){ - // connect failed - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); - } - else if(_lastconxresult == WL_CONNECTION_LOST){ - // connect failed, MOST likely 4WAY_HANDSHAKE_TIMEOUT/incorrect password, state is ambiguous however - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); - } - else{ - str.replace(FPSTR(T_c),""); - str.replace(FPSTR(T_r),""); - } - } - } - else { - str = FPSTR(HTTP_STATUS_NONE); - } - page += str; -} - -// PUBLIC - -// METHODS - -/** - * reset wifi settings, clean stored ap password - */ - -/** - * [stopConfigPortal description] - * @return {[type]} [description] - */ -bool WiFiManager::stopConfigPortal(){ - if(_configPortalIsBlocking){ - abort = true; - return true; - } - return shutdownConfigPortal(); -} - -/** - * disconnect - * @access public - * @since $dev - * @return bool success - */ -bool WiFiManager::disconnect(){ - if(WiFi.status() != WL_CONNECTED){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("Disconnecting: Not connected")); - #endif - return false; - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Disconnecting")); - #endif - return WiFi_Disconnect(); -} - -/** - * reboot the device - * @access public - */ -void WiFiManager::reboot(){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Restarting")); - _debugPort.flush(); - #endif - delay(2000); // time for serial and web flsuh - shutdownConfigPortal(); - ESP.restart(); -} - -/** - * reboot the device - * @access public - */ -bool WiFiManager::erase(){ - return erase(false); -} - -bool WiFiManager::erase(bool opt){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM("Erasing"); - #endif - - #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) - // if opt true, do nvs erase - if(opt){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Erasing NVS")); - #endif - esp_err_t err; - err = nvs_flash_init(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("nvs_flash_init: "),err!=ESP_OK ? (String)err : "Success"); - #endif - err = nvs_flash_erase(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("nvs_flash_erase: "), err!=ESP_OK ? (String)err : "Success"); - #endif - return err == ESP_OK; - } - #elif defined(ESP8266) && defined(spiffs_api_h) - if(opt){ - bool ret = false; - if(SPIFFS.begin()){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Erasing SPIFFS")); - #endif - bool ret = SPIFFS.format(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("spiffs erase: "),ret ? "Success" : "ERROR"); - #endif - } else{ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("[ERROR] Could not start SPIFFS")); - #endif - } - return ret; - } - #else - (void)opt; - #endif - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("Erasing WiFi Config")); - #endif - return WiFi_eraseConfig(); -} - -/** - * [resetSettings description] - * ERASES STA CREDENTIALS - * @access public - */ -void WiFiManager::resetSettings() { -#ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("resetSettings")); - #endif - WiFi_enableSTA(true,true); // must be sta to disconnect erase - delay(500); // ensure sta is enabled - if (_resetcallback != NULL){ - _resetcallback(); // @CALLBACK - } - - #ifdef ESP32 - WiFi.disconnect(true,true); - #else - WiFi.persistent(true); - WiFi.disconnect(true); - WiFi.persistent(false); - #endif - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("SETTINGS ERASED")); - #endif -} - -// SETTERS - -/** - * [setTimeout description] - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setTimeout(unsigned long seconds) { - setConfigPortalTimeout(seconds); -} - -/** - * [setConfigPortalTimeout description] - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { - _configPortalTimeout = seconds * 1000; -} - -/** - * [setConnectTimeout description] - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setConnectTimeout(unsigned long seconds) { - _connectTimeout = seconds * 1000; -} - -/** - * [setConnectRetries description] - * @access public - * @param {[type]} uint8_t numRetries [description] - */ -void WiFiManager::setConnectRetries(uint8_t numRetries){ - _connectRetries = constrain(numRetries,1,10); -} - -/** - * toggle _cleanconnect, always disconnect before connecting - * @param {[type]} bool enable [description] - */ -void WiFiManager::setCleanConnect(bool enable){ - _cleanConnect = enable; -} - -/** - * [setConnectTimeout description - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { - _saveTimeout = seconds * 1000; -} - -/** - * Set save portal connect on save option, - * if false, will only save credentials not connect - * @access public - * @param {[type]} bool connect [description] - */ -void WiFiManager::setSaveConnect(bool connect) { - _connectonsave = connect; -} - -/** - * [setDebugOutput description] - * @access public - * @param {[type]} boolean debug [description] - */ -void WiFiManager::setDebugOutput(boolean debug) { - _debug = debug; - if(_debug && _debugLevel == WM_DEBUG_DEV) debugPlatformInfo(); - if(_debug && _debugLevel >= WM_DEBUG_NOTIFY)DEBUG_WM((__FlashStringHelper *)WM_VERSION_STR," D:"+String(_debugLevel)); -} - -void WiFiManager::setDebugOutput(boolean debug, String prefix) { - _debugPrefix = prefix; - setDebugOutput(debug); -} - -void WiFiManager::setDebugOutput(boolean debug, wm_debuglevel_t level) { - _debugLevel = level; - // _debugPrefix = prefix; - setDebugOutput(debug); -} - - -/** - * [setAPStaticIPConfig description] - * @access public - * @param {[type]} IPAddress ip [description] - * @param {[type]} IPAddress gw [description] - * @param {[type]} IPAddress sn [description] - */ -void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _ap_static_ip = ip; - _ap_static_gw = gw; - _ap_static_sn = sn; -} - -/** - * [setSTAStaticIPConfig description] - * @access public - * @param {[type]} IPAddress ip [description] - * @param {[type]} IPAddress gw [description] - * @param {[type]} IPAddress sn [description] - */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _sta_static_ip = ip; - _sta_static_gw = gw; - _sta_static_sn = sn; -} - -/** - * [setSTAStaticIPConfig description] - * @since $dev - * @access public - * @param {[type]} IPAddress ip [description] - * @param {[type]} IPAddress gw [description] - * @param {[type]} IPAddress sn [description] - * @param {[type]} IPAddress dns [description] - */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { - setSTAStaticIPConfig(ip,gw,sn); - _sta_static_dns = dns; -} - -/** - * [setMinimumSignalQuality description] - * @access public - * @param {[type]} int quality [description] - */ -void WiFiManager::setMinimumSignalQuality(int quality) { - _minimumQuality = quality; -} - -/** - * [setBreakAfterConfig description] - * @access public - * @param {[type]} boolean shouldBreak [description] - */ -void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { - _shouldBreakAfterConfig = shouldBreak; -} - -/** - * setAPCallback, set a callback when softap is started - * @access public - * @param {[type]} void (*func)(WiFiManager* wminstance) - */ -void WiFiManager::setAPCallback( std::function func ) { - _apcallback = func; -} - -/** - * setWebServerCallback, set a callback after webserver is reset, and before routes are setup - * if we set webserver handlers before wm, they are used and wm is not by esp webserver - * on events cannot be overrided once set, and are not mutiples - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setWebServerCallback( std::function func ) { - _webservercallback = func; -} - -/** - * setSaveConfigCallback, set a save config callback after closing configportal - * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setSaveConfigCallback( std::function func ) { - _savewificallback = func; -} - -/** - * setPreSaveConfigCallback, set a callback to fire before saving wifi or params - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setPreSaveConfigCallback( std::function func ) { - _presavewificallback = func; -} - -/** - * setConfigResetCallback, set a callback to occur when a resetSettings() occurs - * @access public - * @param {[type]} void(*func)(void) - */ -void WiFiManager::setConfigResetCallback( std::function func ) { - _resetcallback = func; -} - -/** - * setSaveParamsCallback, set a save params callback on params save in wifi or params pages - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setSaveParamsCallback( std::function func ) { - _saveparamscallback = func; -} - -/** - * setPreSaveParamsCallback, set a pre save params callback on params save prior to anything else - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setPreSaveParamsCallback( std::function func ) { - _presaveparamscallback = func; -} - -/** - * setPreOtaUpdateCallback, set a callback to fire before OTA update - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setPreOtaUpdateCallback( std::function func ) { - _preotaupdatecallback = func; -} - -/** - * setConfigPortalTimeoutCallback, set a callback to config portal is timeout - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setConfigPortalTimeoutCallback( std::function func ) { - _configportaltimeoutcallback = func; -} - -/** - * set custom head html - * custom element will be added to head, eg. new meta,style,script tag etc. - * @access public - * @param char element - */ -void WiFiManager::setCustomHeadElement(const char* html) { - _customHeadElement = html; -} - -/** - * set custom menu html - * custom element will be added to menu under custom menu item. - * @access public - * @param char element - */ -void WiFiManager::setCustomMenuHTML(const char* html) { - _customMenuHTML = html; -} - -/** - * toggle wifiscan hiding of duplicate ssid names - * if this is false, wifiscan will remove duplicat Access Points - defaut true - * @access public - * @param boolean removeDuplicates [true] - */ -void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { - _removeDuplicateAPs = removeDuplicates; -} - -/** - * toggle configportal blocking loop - * if enabled, then the configportal will enter a blocking loop and wait for configuration - * if disabled use with process() to manually process webserver - * @since $dev - * @access public - * @param boolean shoudlBlock [false] - */ -void WiFiManager::setConfigPortalBlocking(boolean shouldBlock) { - _configPortalIsBlocking = shouldBlock; -} - -/** - * toggle restore persistent, track internally - * sets ESP wifi.persistent so we can remember it and restore user preference on destruct - * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 - * @since $dev - * @access public - * @param boolean persistent [true] - */ -void WiFiManager::setRestorePersistent(boolean persistent) { - _userpersistent = persistent; - if(!persistent){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("persistent is off")); - #endif - } -} - -/** - * toggle showing static ip form fields - * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code - * @since $dev - * @access public - * @param boolean alwaysShow [false] - */ -void WiFiManager::setShowStaticFields(boolean alwaysShow){ - if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; - else _staShowStaticFields = alwaysShow ? 1 : 0; -} - -/** - * toggle showing dns fields - * if enabled, then the dns1 field will be visible, even if not set in code - * @since $dev - * @access public - * @param boolean alwaysShow [false] - */ -void WiFiManager::setShowDnsFields(boolean alwaysShow){ - if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; - _staShowDns = alwaysShow ? 1 : 0; -} - -/** - * toggle showing password in wifi password field - * if not enabled, placeholder will be S_passph - * @since $dev - * @access public - * @param boolean alwaysShow [false] - */ -void WiFiManager::setShowPassword(boolean show){ - _showPassword = show; -} - -/** - * toggle captive portal - * if enabled, then devices that use captive portal checks will be redirected to root - * if not you will automatically have to navigate to ip [192.168.4.1] - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setCaptivePortalEnable(boolean enabled){ - _enableCaptivePortal = enabled; -} - -/** - * toggle connecting to the best AP based on RSSI - * @param boolean enabled [false] - */ -void WiFiManager::setFindBestRSSI(boolean enabled) { - _findBestRSSI = enabled; -} - -/** - * toggle wifi autoreconnect policy - * if enabled, then wifi will autoreconnect automatically always - * On esp8266 we force this on when autoconnect is called, see notes - * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setWiFiAutoReconnect(boolean enabled){ - _wifiAutoReconnect = enabled; -} - -/** - * toggle configportal timeout wait for station client - * if enabled, then the configportal will start timeout when no stations are connected to softAP - * disabled by default as rogue stations can keep it open if there is no auth - * @since $dev - * @access public - * @param boolean enabled [false] - */ -void WiFiManager::setAPClientCheck(boolean enabled){ - _apClientCheck = enabled; -} - -/** - * toggle configportal timeout wait for web client - * if enabled, then the configportal will restart timeout when client requests come in - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setWebPortalClientCheck(boolean enabled){ - _webClientCheck = enabled; -} - -/** - * toggle wifiscan percentages or quality icons - * @since $dev - * @access public - * @param boolean enabled [false] - */ -void WiFiManager::setScanDispPerc(boolean enabled){ - _scanDispOptions = enabled; -} - -/** - * toggle configportal if autoconnect failed - * if enabled, then the configportal will be activated on autoconnect failure - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setEnableConfigPortal(boolean enable) -{ - _enableConfigPortal = enable; -} - -/** - * toggle configportal if autoconnect failed - * if enabled, then the configportal will be de-activated on wifi save - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setDisableConfigPortal(boolean enable) -{ - _disableConfigPortal = enable; -} - -/** - * set the hostname (dhcp client id) - * @since $dev - * @access public - * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 - * @return bool false if hostname is not valid - */ -bool WiFiManager::setHostname(const char * hostname){ - //@todo max length 32 - _hostname = String(hostname); - return true; -} - -bool WiFiManager::setHostname(String hostname){ - //@todo max length 32 - _hostname = hostname; - return true; -} - -/** - * set the soft ao channel, ignored if channelsync is true and connected - * @param int32_t wifi channel, 0 to disable - */ -void WiFiManager::setWiFiAPChannel(int32_t channel){ - _apChannel = channel; -} - -/** - * set the soft ap hidden - * @param bool wifi ap hidden, default is false - */ -void WiFiManager::setWiFiAPHidden(bool hidden){ - _apHidden = hidden; -} - - -/** - * toggle showing erase wifi config button on info page - * @param boolean enabled - */ -void WiFiManager::setShowInfoErase(boolean enabled){ - _showInfoErase = enabled; -} - -/** - * toggle showing update upload web ota button on info page - * @param boolean enabled - */ -void WiFiManager::setShowInfoUpdate(boolean enabled){ - _showInfoUpdate = enabled; -} - -/** - * check if the config portal is running - * @return bool true if active - */ -bool WiFiManager::getConfigPortalActive(){ - return configPortalActive; -} - -/** - * [getConfigPortalActive description] - * @return bool true if active - */ -bool WiFiManager::getWebPortalActive(){ - return webPortalActive; -} - - -String WiFiManager::getWiFiHostname(){ - #ifdef ESP32 - return (String)WiFi.getHostname(); - #else - return (String)WiFi.hostname(); - #endif -} - -/** - * [setTitle description] - * @param String title, set app title - */ -void WiFiManager::setTitle(String title){ - _title = title; -} - -/** - * set menu items and order - * if param is present in menu , params will be removed from wifi page automatically - * eg. - * const char * menu[] = {"wifi","setup","sep","info","exit"}; - * WiFiManager.setMenu(menu); - * @since $dev - * @param uint8_t menu[] array of menu ids - */ -void WiFiManager::setMenu(const char * menu[], uint8_t size){ -#ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_DEV,"setmenu array"); - #endif - _menuIds.clear(); - for(size_t i = 0; i < size; i++){ - for(size_t j = 0; j < _nummenutokens; j++){ - if((String)menu[i] == (__FlashStringHelper *)(_menutokens[j])){ - if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag - _menuIds.push_back(j); - } - delay(0); - } - delay(0); - } - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(getMenuOut()); - #endif -} - -/** - * setMenu with vector - * eg. - * std::vector menu = {"wifi","setup","sep","info","exit"}; - * WiFiManager.setMenu(menu); - * tokens can be found in _menutokens array in strings_en.h - * @shiftIncrement $dev - * @param {[type]} std::vector& menu [description] - */ -void WiFiManager::setMenu(std::vector& menu){ -#ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_DEV,"setmenu vector"); - #endif - _menuIds.clear(); - for(auto menuitem : menu ){ - for(size_t j = 0; j < _nummenutokens; j++){ - if((String)menuitem == (__FlashStringHelper *)(_menutokens[j])){ - if((String)menuitem == "param") _paramsInWifi = false; // param auto flag - _menuIds.push_back(j); - } - } - } - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_DEV,getMenuOut()); - #endif -} - - -/** - * set params as sperate page not in wifi - * NOT COMPATIBLE WITH setMenu! - * @todo scan menuids and insert param after wifi or something, same for ota - * @param bool enable - * @since $dev - */ -void WiFiManager::setParamsPage(bool enable){ - _paramsInWifi = !enable; - setMenu(enable ? _menuIdsParams : _menuIdsDefault); -} - -// GETTERS - -/** - * get config portal AP SSID - * @since 0.0.1 - * @access public - * @return String the configportal ap name - */ -String WiFiManager::getConfigPortalSSID() { - return _apName; -} - -/** - * return the last known connection result - * logged on autoconnect and wifisave, can be used to check why failed - * get as readable string with getWLStatusString(getLastConxResult); - * @since $dev - * @access public - * @return bool return wl_status codes - */ -uint8_t WiFiManager::getLastConxResult(){ - return _lastconxresult; -} - -/** - * check if wifi has a saved ap or not - * @since $dev - * @access public - * @return bool true if a saved ap config exists - */ -bool WiFiManager::getWiFiIsSaved(){ - return WiFi_hasAutoConnect(); -} - -/** - * getDefaultAPName - * @since $dev - * @return string - */ -String WiFiManager::getDefaultAPName(){ - String hostString = String(WIFI_getChipId(),HEX); - hostString.toUpperCase(); - // char hostString[16] = {0}; - // sprintf(hostString, "%06X", ESP.getChipId()); - return _wifissidprefix + "_" + hostString; -} - -/** - * setCountry - * @since $dev - * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN - */ -void WiFiManager::setCountry(String cc){ - _wificountry = cc; -} - -/** - * setClass - * @param String str body class string - */ -void WiFiManager::setClass(String str){ - _bodyClass = str; -} - -/** - * setDarkMode - * @param bool enable, enable dark mode via invert class - */ -void WiFiManager::setDarkMode(bool enable){ - _bodyClass = enable ? "invert" : ""; -} - -/** - * setHttpPort - * @param uint16_t port webserver port number default 80 - */ -void WiFiManager::setHttpPort(uint16_t port){ - _httpPort = port; -} - - -bool WiFiManager::preloadWiFi(String ssid, String pass){ - _defaultssid = ssid; - _defaultpass = pass; - return true; -} - -// HELPERS - -/** - * getWiFiSSID - * @since $dev - * @param bool persistent - * @return String - */ -String WiFiManager::getWiFiSSID(bool persistent){ - return WiFi_SSID(persistent); -} - -/** - * getWiFiPass - * @since $dev - * @param bool persistent - * @return String - */ -String WiFiManager::getWiFiPass(bool persistent){ - return WiFi_psk(persistent); -} - -// DEBUG -// @todo fix DEBUG_WM(0,0); -template -void WiFiManager::DEBUG_WM(Generic text) { - DEBUG_WM(WM_DEBUG_NOTIFY,text,""); -} - -template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { - if(_debugLevel >= level) DEBUG_WM(level,text,""); -} - -template -void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { - DEBUG_WM(WM_DEBUG_NOTIFY,text,textb); -} - -template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { - if(!_debug || _debugLevel < level) return; - - if(_debugLevel >= WM_DEBUG_MAX){ - #ifdef ESP8266 - // uint32_t free; - // uint16_t max; - // uint8_t frag; - // ESP.getHeapStats(&free, &max, &frag);// @todo Does not exist in 2.3.0 - // _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); - #elif defined ESP32 - // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). - // total_allocated_bytes; ///< Total bytes allocated to data in the heap. - // largest_free_block; ///< Size of largest free block in the heap. This is the largest malloc-able size. - // minimum_free_bytes; ///< Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). - // allocated_blocks; ///< Number of (variable size) blocks allocated in the heap. - // free_blocks; ///< Number of (variable size) free blocks in the heap. - // total_blocks; ///< Total number of (variable size) blocks in the heap. - multi_heap_info_t info; - heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); - uint32_t free = info.total_free_bytes; - uint16_t max = info.largest_free_block; - uint8_t frag = 100 - (max * 100) / free; - _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); - #endif - } - - _debugPort.print(_debugPrefix); - if(_debugLevel >= debugLvlShow) _debugPort.print("["+(String)level+"] "); - _debugPort.print(text); - if(textb){ - _debugPort.print(" "); - _debugPort.print(textb); - } - _debugPort.println(); -} - -/** - * [debugSoftAPConfig description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::debugSoftAPConfig(){ - - #ifdef ESP8266 - softap_config config; - wifi_softap_get_config(&config); - #if !defined(WM_NOCOUNTRY) - wifi_country_t country; - wifi_get_country(&country); - #endif - #elif defined(ESP32) - wifi_country_t country; - wifi_config_t conf_config; - esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK - wifi_ap_config_t config = conf_config.ap; - esp_wifi_get_country(&country); - #endif - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("SoftAP Configuration")); - DEBUG_WM(FPSTR(D_HR)); - DEBUG_WM(F("ssid: "),(char *) config.ssid); - DEBUG_WM(F("password: "),(char *) config.password); - DEBUG_WM(F("ssid_len: "),config.ssid_len); - DEBUG_WM(F("channel: "),config.channel); - DEBUG_WM(F("authmode: "),config.authmode); - DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); - DEBUG_WM(F("max_connection: "),config.max_connection); - #endif - #if !defined(WM_NOCOUNTRY) - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("country: "),(String)country.cc); - #endif - DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); - DEBUG_WM(FPSTR(D_HR)); - #endif -} - -/** - * [debugPlatformInfo description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::debugPlatformInfo(){ - #ifdef ESP8266 - system_print_meminfo(); - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("[SYS] getCoreVersion(): "),ESP.getCoreVersion()); - DEBUG_WM(F("[SYS] system_get_sdk_version(): "),system_get_sdk_version()); - DEBUG_WM(F("[SYS] system_get_boot_version():"),system_get_boot_version()); - DEBUG_WM(F("[SYS] getFreeHeap(): "),(String)ESP.getFreeHeap()); - #endif - #elif defined(ESP32) - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("[SYS] WM version: "), String((__FlashStringHelper *)WM_VERSION_STR) +" D:"+String(_debugLevel)); - DEBUG_WM(F("[SYS] Arduino version: "), VER_ARDUINO_STR); - DEBUG_WM(F("[SYS] ESP SDK version: "), ESP.getSdkVersion()); - DEBUG_WM(F("[SYS] Free heap: "), ESP.getFreeHeap()); - #endif - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("[SYS] Chip ID:"),WIFI_getChipId()); - DEBUG_WM(F("[SYS] Chip Model:"), ESP.getChipModel()); - DEBUG_WM(F("[SYS] Chip Cores:"), ESP.getChipCores()); - DEBUG_WM(F("[SYS] Chip Rev:"), ESP.getChipRevision()); - #endif - #endif -} - -int WiFiManager::getRSSIasQuality(int RSSI) { - int quality = 0; - - if (RSSI <= -100) { - quality = 0; - } else if (RSSI >= -50) { - quality = 100; - } else { - quality = 2 * (RSSI + 100); - } - return quality; -} - -/** Is this an IP? */ -boolean WiFiManager::isIp(String str) { - for (size_t i = 0; i < str.length(); i++) { - int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { - return false; - } - } - return true; -} - -/** IP to String? */ -String WiFiManager::toStringIp(IPAddress ip) { - String res = ""; - for (int i = 0; i < 3; i++) { - res += String((ip >> (8 * i)) & 0xFF) + "."; - } - res += String(((ip >> 8 * 3)) & 0xFF); - return res; -} - -boolean WiFiManager::validApPassword(){ - // check that ap password is valid, return false - if (_apPassword == NULL) _apPassword = ""; - if (_apPassword != "") { - if (_apPassword.length() < 8 || _apPassword.length() > 63) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); - #endif - _apPassword = ""; - return false; // @todo FATAL or fallback to empty , currently fatal, fail secure. - } - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("AccessPoint set password is VALID")); - DEBUG_WM(WM_DEBUG_DEV,"ap pass",_apPassword); - #endif - } - return true; -} - -/** - * encode htmlentities - * @since $dev - * @param string str string to replace entities - * @return string encoded string - */ -String WiFiManager::htmlEntities(String str, bool whitespace) { - str.replace("&","&"); - str.replace("<","<"); - str.replace(">",">"); - str.replace("'","'"); - if(whitespace) str.replace(" "," "); - // str.replace("-","–"); - // str.replace("\"","""); - // str.replace("/": "/"); - // str.replace("`": "`"); - // str.replace("=": "="); -return str; -} - -/** - * [getWLStatusString description] - * @access public - * @param {[type]} uint8_t status [description] - * @return {[type]} [description] - */ -String WiFiManager::getWLStatusString(uint8_t status){ - if(status <= 7) return WIFI_STA_STATUS[status]; - return FPSTR(S_NA); -} - -String WiFiManager::getWLStatusString(){ - uint8_t status = WiFi.status(); - if(status <= 7) return WIFI_STA_STATUS[status]; - return FPSTR(S_NA); -} - -String WiFiManager::encryptionTypeStr(uint8_t authmode) { -#ifdef WM_DEBUG_LEVEL - // DEBUG_WM("enc_tye: ",authmode); - #endif - return AUTH_MODE_NAMES[authmode]; -} - -String WiFiManager::getModeString(uint8_t mode){ - if(mode <= 3) return WIFI_MODES[mode]; - return FPSTR(S_NA); -} - -bool WiFiManager::WiFiSetCountry(){ - if(_wificountry == "") return false; // skip not set - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFiSetCountry to"),_wificountry); - #endif - -/* - * @return - * - ESP_OK: succeed - * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by eps_wifi_init - * - ESP_ERR_WIFI_IF: invalid interface - * - ESP_ERR_WIFI_ARG: invalid argument - * - others: refer to error codes in esp_err.h - */ - - // @todo move these definitions, and out of cpp `esp_wifi_set_country(&WM_COUNTRY_US)` - bool ret = true; - // ret = esp_wifi_set_bandwidth(WIFI_IF_AP,WIFI_BW_HT20); // WIFI_BW_HT40 - #ifdef ESP32 - esp_err_t err = ESP_OK; - // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( check again it might be now! ) - if(WiFi.getMode() == WIFI_MODE_NULL){ - DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] cannot set country, wifi not init"); - } // exception if wifi not init! - // Assumes that _wificountry is set to one of the supported country codes : "01"(world safe mode) "AT","AU","BE","BG","BR", - // "CA","CH","CN","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HK","HR","HU", - // "IE","IN","IS","IT","JP","KR","LI","LT","LU","LV","MT","MX","NL","NO","NZ","PL","PT", - // "RO","SE","SI","SK","TW","US" - // If an invalid country code is passed, ESP_ERR_WIFI_ARG will be returned - // This also uses 802.11d mode, which matches the STA to the country code of the AP it connects to (meaning - // that the country code will be overridden if connecting to a "foreign" AP) - else { - #ifndef WM_NOCOUNTRY - err = esp_wifi_set_country_code(_wificountry.c_str(), true); - #else - DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] esp wifi set country is not available"); - err = true; - #endif - } - #ifdef WM_DEBUG_LEVEL - if(err){ - if(err == ESP_ERR_WIFI_NOT_INIT) DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_NOT_INIT"); - else if(err == ESP_ERR_INVALID_ARG) DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_ARG (invalid country code)"); - else if(err != ESP_OK)DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] unknown error",(String)err); - } - #endif - ret = err == ESP_OK; - - #elif defined(ESP8266) && !defined(WM_NOCOUNTRY) - // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! - if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); - else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); - else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); - #ifdef WM_DEBUG_LEVEL - else DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] country code not found")); - #endif - #endif - - #ifdef WM_DEBUG_LEVEL - if(ret) DEBUG_WM(WM_DEBUG_VERBOSE,F("[OK] esp_wifi_set_country: "),_wificountry); - else DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] esp_wifi_set_country failed")); - #endif - return ret; -} - -// set mode ignores WiFi.persistent -bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { - bool ret; - #ifdef ESP8266 - if((wifi_get_opmode() == (uint8) m ) && !persistent) { - return true; - } - ETS_UART_INTR_DISABLE(); - if(persistent) ret = wifi_set_opmode(m); - else ret = wifi_set_opmode_current(m); - ETS_UART_INTR_ENABLE(); - return ret; - #elif defined(ESP32) - if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.mode(m); // @todo persistent check persistant mode, was eventually added to esp lib, but have to add version checking probably - if(persistent && esp32persistent) WiFi.persistent(false); - return ret; - #endif -} -bool WiFiManager::WiFi_Mode(WiFiMode_t m) { - return WiFi_Mode(m,false); -} - -// sta disconnect without persistent -bool WiFiManager::WiFi_Disconnect() { - #ifdef ESP8266 - if((WiFi.getMode() & WIFI_STA) != 0) { - bool ret; - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("WiFi station disconnect")); - #endif - ETS_UART_INTR_DISABLE(); // @todo possibly not needed - ret = wifi_station_disconnect(); - ETS_UART_INTR_ENABLE(); - return ret; - } - #elif defined(ESP32) - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("WiFi station disconnect")); - #endif - return WiFi.disconnect(); // not persistent atm - #endif - return false; -} - -// toggle STA without persistent -bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { -#ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("WiFi_enableSTA"),(String) enable? "enable" : "disable"); - #endif - #ifdef ESP8266 - WiFiMode_t newMode; - WiFiMode_t currentMode = WiFi.getMode(); - bool isEnabled = (currentMode & WIFI_STA) != 0; - if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); - else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); - - if((isEnabled != enable) || persistent) { - if(enable) { - #ifdef WM_DEBUG_LEVEL - if(persistent) DEBUG_WM(WM_DEBUG_DEV,F("enableSTA PERSISTENT ON")); - #endif - return WiFi_Mode(newMode,persistent); - } - else { - return WiFi_Mode(newMode,persistent); - } - } else { - return true; - } - #elif defined(ESP32) - bool ret; - if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform - if(persistent && esp32persistent) WiFi.persistent(false); - return ret; - #endif -} - -bool WiFiManager::WiFi_enableSTA(bool enable) { - return WiFi_enableSTA(enable,false); -} - -bool WiFiManager::WiFi_eraseConfig() { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_DEV,F("WiFi_eraseConfig")); - #endif - - #ifdef ESP8266 - #ifndef WM_FIXERASECONFIG - return ESP.eraseConfig(); - #else - // erase config BUG replacement - // https://github.com/esp8266/Arduino/pull/3635 - const size_t cfgSize = 0x4000; - size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; - - for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { - if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { - return false; - } - } - return true; - #endif - #elif defined(ESP32) - - bool ret; - WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! - WiFi.persistent(true); - ret = WiFi.disconnect(true,true); // disconnect(bool wifioff, bool eraseap) - delay(500); - WiFi.persistent(false); - return ret; - #endif -} - -uint8_t WiFiManager::WiFi_softap_num_stations(){ - #ifdef ESP8266 - return wifi_softap_get_station_num(); - #elif defined(ESP32) - return WiFi.softAPgetStationNum(); - #endif -} - -bool WiFiManager::WiFi_hasAutoConnect(){ - return WiFi_SSID(true) != ""; -} - -String WiFiManager::WiFi_SSID(bool persistent) const{ - - #ifdef ESP8266 - struct station_config conf; - if(persistent) wifi_station_get_config_default(&conf); - else wifi_station_get_config(&conf); - - char tmp[33]; //ssid can be up to 32chars, => plus null term - memcpy(tmp, conf.ssid, sizeof(conf.ssid)); - tmp[32] = 0; //nullterm in case of 32 char ssid - return String(reinterpret_cast(tmp)); - - #elif defined(ESP32) - // bool res = WiFi.wifiLowLevelInit(true); // @todo fix for S3, not found - // wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - if(persistent){ - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.ssid)); - } - else { - if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ - return String(); - } - wifi_ap_record_t info; - if(!esp_wifi_sta_get_ap_info(&info)) { - return String(reinterpret_cast(info.ssid)); - } - return String(); - } - #endif -} - -String WiFiManager::WiFi_psk(bool persistent) const { - #ifdef ESP8266 - struct station_config conf; - - if(persistent) wifi_station_get_config_default(&conf); - else wifi_station_get_config(&conf); - - char tmp[65]; //psk is 64 bytes hex => plus null term - memcpy(tmp, conf.password, sizeof(conf.password)); - tmp[64] = 0; //null term in case of 64 byte psk - return String(reinterpret_cast(tmp)); - - #elif defined(ESP32) - // only if wifi is init - if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ - return String(); - } - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.password)); - #endif -} - -#ifdef ESP32 - #ifdef WM_ARDUINOEVENTS - void WiFiManager::WiFiEvent(WiFiEvent_t event,arduino_event_info_t info){ - #else - void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ - #define wifi_sta_disconnected disconnected - #define ARDUINO_EVENT_WIFI_STA_DISCONNECTED SYSTEM_EVENT_STA_DISCONNECTED - #define ARDUINO_EVENT_WIFI_SCAN_DONE SYSTEM_EVENT_SCAN_DONE - #endif - if(!_hasBegun){ - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); - #endif - // Serial.println(F("\n[EVENT] WiFiEvent logging (wm debug not available)")); - // Serial.print(F("[EVENT] ID: ")); - // Serial.println(event); - return; - } - #ifdef WM_DEBUG_LEVEL - // DEBUG_WM(WM_DEBUG_VERBOSE,"[EVENT]",event); - #endif - if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED){ - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: "),info.wifi_sta_disconnected.reason); - #endif - if(info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_FAIL){ - _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail - } else _lastconxresulttmp = WiFi.status(); - #ifdef WM_DEBUG_LEVEL - if(info.wifi_sta_disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(WM_DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: NO_AP_FOUND")); - if(info.wifi_sta_disconnected.reason == WIFI_REASON_ASSOC_FAIL){ - if(_aggresiveReconn && _connectRetries<4) _connectRetries=4; - DEBUG_WM(WM_DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: AUTH FAIL")); - } - #endif - #ifdef esp32autoreconnect - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting")); - #endif - //WiFi.reconnect(); - #endif - } - else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE && _asyncScan){ - uint16_t scans = WiFi.scanComplete(); - WiFi_scanComplete(scans); - } -} -#endif - -void WiFiManager::WiFi_autoReconnect(){ - #ifdef ESP8266 - WiFi.setAutoReconnect(_wifiAutoReconnect); - #elif defined(ESP32) - // if(_wifiAutoReconnect){ - // @todo move to seperate method, used for event listener now - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("ESP32 event handler enabled")); - #endif - using namespace std::placeholders; - if(wm_event_id == 0) wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); - // } - #endif -} - -// Called when /update is requested -void WiFiManager::handleUpdate(AsyncWebServerRequest *request) { - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,F("<- Handle update")); - #endif - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - if (captivePortal(request)) return; // If captive portal redirect instead of displaying the page - String page = getHTTPHead(_title); // @token options - String str = FPSTR(HTTP_ROOT_MAIN); - str.replace(FPSTR(T_t), _title); - str.replace(FPSTR(T_v), configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading - page += str; - - page += FPSTR(HTTP_UPDATE); - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - -} - -// upload via /u POST -void WiFiManager::handleUpdating(AsyncWebServerRequest *request,String filename, size_t index, uint8_t *data, size_t len, bool final){ - // @todo - // cannot upload files in captive portal, file select is not allowed, show message with link or hide - // cannot upload if softreset after upload, maybe check for hard reset at least for dev, ERROR[11]: Invalid bootstrapping state, reset ESP8266 before updating - // add upload status to webpage somehow - // abort upload if error detected ? - // [x] supress cp timeout on upload, so it doesnt keep uploading? - // add progress handler for debugging - // combine route handlers into one callback and use argument or post checking instead of mutiple functions maybe, if POST process else server upload page? - // [x] add upload checking, do we need too check file? - // convert output to debugger if not moving to example - - // if (captivePortal()) return; // If captive portal redirect instead of displaying the page - bool error = false; - unsigned long _configPortalTimeoutSAV = _configPortalTimeout; // store cp timeout - _configPortalTimeout = 0; // disable timeout - bool otadebug = false; - - // UPLOAD START - if (!index) { - // if(_debug) Serial.setDebugOutput(true); - uint32_t maxSketchSpace; - - // Use new callback for before OTA update - if (_preotaupdatecallback != NULL) { - _preotaupdatecallback(); // @CALLBACK - } - #ifdef ESP8266 - WiFiUDP::stopAll(); - maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - #elif defined(ESP32) - // Think we do not need to stop WiFIUDP because we haven't started a listener - // maxSketchSpace = (ESP.getFlashChipSize() - 0x1000) & 0xFFFFF000; - // #define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF // include update.h - maxSketchSpace = UPDATE_SIZE_UNKNOWN; - #endif - - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_VERBOSE,"[OTA] Update file: ", filename.c_str()); - #endif - - // Update.onProgress(THandlerFunction_Progress fn); - // Update.onProgress([](unsigned int progress, unsigned int total) { - // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); - // }); - - if (!Update.begin(maxSketchSpace)) { // start with max available size - #ifdef WM_DEBUG_LEVEL - DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] OTA Update ERROR"), Update.getError()); - #endif - error = true; - Update.end(); // Not sure the best way to abort, I think client will keep sending.. - } - #ifdef ESP8266 - Update.runAsync(true); // tell the updaterClass to run in async mode - #endif - } - // UPLOAD WRITE - if (index 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - String page = getHTTPHead(FPSTR(S_options)); // @token options - String str = FPSTR(HTTP_ROOT_MAIN); - str.replace(FPSTR(T_t),_title); - str.replace(FPSTR(T_v), configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading - page += str; - - if (Update.hasError()) { - page += FPSTR(HTTP_UPDATE_FAIL); - #ifdef ESP32 - page += "OTA Error: " + (String)Update.errorString(); - #else - page += "OTA Error: " + (String)Update.getError(); - #endif - DEBUG_WM(F("[OTA] update failed")); - } - else { - page += FPSTR(HTTP_UPDATE_SUCCESS); - DEBUG_WM(F("[OTA] update ok")); - } - page += FPSTR(HTTP_END); - - HTTPSend(request,page); - - // delay(1000); // send page - if (!Update.hasError()) { - //ESP.restart(); - _rebootNeeded = true; - } -} - -#endif diff --git a/lib/WiFiManager/WiFiManager.h b/lib/WiFiManager/WiFiManager.h deleted file mode 100644 index 9f0eac5..0000000 --- a/lib/WiFiManager/WiFiManager.h +++ /dev/null @@ -1,885 +0,0 @@ -/** - * WiFiManager.h - * - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - - -#ifndef WiFiManager_h -#define WiFiManager_h - -#if defined(ESP8266) || defined(ESP32) - -#ifdef ESP8266 -#include -#endif - -#include - -// #define WM_MDNS // includes MDNS, also set MDNS with sethostname -// #define WM_FIXERASECONFIG // use erase flash fix -// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS -// #define WM_RTC // esp32 info page will include reset reasons - -// #define WM_JSTEST // build flag for enabling js xhr tests -// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include - -#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 -#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" -// @todo check failing on platform = espressif8266@1.7.3 -#define WM_NOASYNC // esp8266 no async scan wifi -#define WM_NOCOUNTRY // esp8266 no country -#define WM_NOAUTH // no httpauth -#define WM_NOSOFTAPSSID // no softapssid() @todo shim -#endif - -// #ifdef CONFIG_IDF_TARGET_ESP32S2 -// #warning ESP32S2 -// #endif - -// #ifdef CONFIG_IDF_TARGET_ESP32C3 -// #warning ESP32C3 -// #endif - -// #ifdef CONFIG_IDF_TARGET_ESP32S3 -// #warning ESP32S3 -// #endif - -// #if defined(ARDUINO_ESP32S3_DEV) || defined(CONFIG_IDF_TARGET_ESP32S3) -// #warning "WM_NOTEMP" -// #define WM_NOTEMP // disabled temp sensor, have to determine which chip we are on -// #endif - -// #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. - -// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED -// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 - -#define WM_WEBSERVERSHIM // use webserver shim lib -#define WM_ASYNCWEBSERVER // use async webserver - -#define WM_G(string_literal) (String(FPSTR(string_literal)).c_str()) - -#ifdef ESP8266 - - extern "C" { - #include "user_interface.h" - } - #include - - #ifdef WM_ASYNCWEBSERVER - #include - #include - #else - #include - #endif - - #ifdef WM_MDNS - #include - #endif - - #define WIFI_getChipId() ESP.getChipId() - #define WM_WIFIOPEN ENC_TYPE_NONE - -#elif defined(ESP32) - - #include - #include - #include - - #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() - #define WM_WIFIOPEN WIFI_AUTH_OPEN - - #ifdef WM_ASYNCWEBSERVER - #include - #include - #else - #ifndef WEBSERVER_H - #ifdef WM_WEBSERVERSHIM - #include - #else - #include - // Forthcoming official ? probably never happening - // https://github.com/esp8266/ESPWebServer - #endif - #endif - #endif - - #ifdef WM_ERASE_NVS - #include - #include - #endif - - #ifdef WM_MDNS - #include - #endif - - #ifdef WM_RTC - #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ - #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 - #include "esp32/rom/rtc.h" - #elif CONFIG_IDF_TARGET_ESP32S2 - #include "esp32s2/rom/rtc.h" - #elif CONFIG_IDF_TARGET_ESP32C3 - #include "esp32c3/rom/rtc.h" - #elif CONFIG_IDF_TARGET_ESP32S3 - #include "esp32s3/rom/rtc.h" - #else - #error Target CONFIG_IDF_TARGET is not supported - #endif - #else // ESP32 Before IDF 4.0 - #include "rom/rtc.h" - #endif - #endif - -#else -#endif - -#include -#include - - -// Include wm strings vars -// Pass in strings env override via WM_STRINGS_FILE -#ifndef WM_STRINGS_FILE -#define WM_STRINGS_FILE "wm_strings_en.h" // this includes constants as dependency -#endif -#include WM_STRINGS_FILE - -// prep string concat vars -#define WM_STRING2(x) #x -#define WM_STRING(x) WM_STRING2(x) - -// #include -#ifdef ESP_IDF_VERSION - // #pragma message "ESP_IDF_VERSION_MAJOR = " WM_STRING(ESP_IDF_VERSION_MAJOR) - // #pragma message "ESP_IDF_VERSION_MINOR = " WM_STRING(ESP_IDF_VERSION_MINOR) - // #pragma message "ESP_IDF_VERSION_PATCH = " WM_STRING(ESP_IDF_VERSION_PATCH) - #define VER_IDF_STR WM_STRING(ESP_IDF_VERSION_MAJOR) "." WM_STRING(ESP_IDF_VERSION_MINOR) "." WM_STRING(ESP_IDF_VERSION_PATCH) -#else - #define VER_IDF_STR "Unknown" -#endif - -#ifdef Arduino_h - #ifdef ESP32 - // #include "esp_arduino_version.h" // esp32 arduino > 2.x - #endif - // esp_get_idf_version - #ifdef ESP_ARDUINO_VERSION - // #pragma message "ESP_ARDUINO_VERSION_MAJOR = " WM_STRING(ESP_ARDUINO_VERSION_MAJOR) - // #pragma message "ESP_ARDUINO_VERSION_MINOR = " WM_STRING(ESP_ARDUINO_VERSION_MINOR) - // #pragma message "ESP_ARDUINO_VERSION_PATCH = " WM_STRING(ESP_ARDUINO_VERSION_PATCH) - #ifdef ESP_ARDUINO_VERSION_MAJOR - #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) - #else - #define VER_ARDUINO_STR "Unknown" - #endif - #else - #include - // #pragma message "ESP_ARDUINO_VERSION_GIT = " WM_STRING(ARDUINO_ESP32_GIT_VER)// 0x46d5afb1 - // #pragma message "ESP_ARDUINO_VERSION_DESC = " WM_STRING(ARDUINO_ESP32_GIT_DESC) // 1.0.6 - // #pragma message "ESP_ARDUINO_VERSION_REL = " WM_STRING(ARDUINO_ESP32_RELEASE) //"1_0_6" - #ifdef ESP_ARDUINO_VERSION_MAJOR - #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) - #else - #define VER_ARDUINO_STR "Unknown" - #endif - #endif -#else -#define VER_ARDUINO_STR "Unknown" -#endif - -// #pragma message "VER_IDF_STR = " WM_STRING(VER_IDF_STR) -// #pragma message "VER_ARDUINO_STR = " WM_STRING(VER_ARDUINO_STR) - -#ifndef WIFI_MANAGER_MAX_PARAMS - #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached -#endif - -#define WFM_LABEL_BEFORE 1 -#define WFM_LABEL_AFTER 2 -#define WFM_NO_LABEL 0 -#define WFM_LABEL_DEFAULT 1 - -class WiFiManagerParameter { - public: - /** - Create custom parameters that can be added to the WiFiManager setup web page - @id is used for HTTP queries and must not contain spaces nor other special characters - */ - WiFiManagerParameter(); - WiFiManagerParameter(const char *custom); - WiFiManagerParameter(const char *id, const char *label); - WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); - WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); - WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); - ~WiFiManagerParameter(); - // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); - - const char *getID() const; - const char *getValue() const; - const char *getLabel() const; - const char *getPlaceholder() const; // @deprecated, use getLabel - int getValueLength() const; - int getLabelPlacement() const; - virtual const char *getCustomHTML() const; - void setValue(const char *defaultValue, int length); - - protected: - void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); - - WiFiManagerParameter& operator=(const WiFiManagerParameter&); - const char *_id; - const char *_label; - char *_value; - int _length; - int _labelPlacement; - - const char *_customHTML; - friend class WiFiManager; -}; - - - // debugging - typedef enum { - WM_DEBUG_SILENT = 0, // debug OFF but still compiled for runtime - WM_DEBUG_ERROR = 1, // error only - WM_DEBUG_NOTIFY = 2, // default stable,INFO - WM_DEBUG_VERBOSE = 3, // move verbose info - WM_DEBUG_DEV = 4, // development useful debugging info - WM_DEBUG_MAX = 5 // MAX extra dev auditing, var dumps etc (MAX+1 will print timing,mem and frag info) - } wm_debuglevel_t; - -class WiFiManager -{ - public: - WiFiManager(Print& consolePort); - WiFiManager(const char* user, const char* password); - WiFiManager(); - ~WiFiManager(); - void WiFiManagerInit(); - - // auto connect to saved wifi, or custom, and start config portal on failures - boolean autoConnect(); - boolean autoConnect(char const *apName, char const *apPassword = NULL); - - //manually start the config portal, autoconnect does this automatically on connect failure - boolean startConfigPortal(); // auto generates apname - boolean startConfigPortal(char const *apName, char const *apPassword = NULL); - - //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking - bool stopConfigPortal(); - - //manually start the web portal, autoconnect does this automatically on connect failure - void startWebPortal(); - - //manually stop the web portal if started manually - void stopWebPortal(); - - // Run webserver processing, if setConfigPortalBlocking(false) - boolean process(); - - // get the AP name of the config portal, so it can be used in the callback - String getConfigPortalSSID(); - int getRSSIasQuality(int RSSI); - - // erase wifi credentials - void resetSettings(); - - // reset wifi scan - void resetScan(); - - // reboot esp - void reboot(); - - // disconnect wifi, without persistent saving or erasing - bool disconnect(); - - // erase esp - bool erase(); - bool erase(bool opt); - - //adds a custom parameter, returns false on failure - bool addParameter(WiFiManagerParameter *p); - - //returns the list of Parameters - WiFiManagerParameter** getParameters(); - - // returns the Parameters Count - int getParametersCount(); - - // SET CALLBACKS - - //called after AP mode and config portal has started - void setAPCallback( std::function func ); - - //called after webserver has started - void setWebServerCallback( std::function func ); - - //called when settings reset have been triggered - void setConfigResetCallback( std::function func ); - - //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) - void setSaveConfigCallback( std::function func ); - - //called when saving params-in-wifi or params before anything else happens (eg wifi) - void setPreSaveConfigCallback( std::function func ); - - //called when saving params before anything else happens - void setPreSaveParamsCallback( std::function func ); - - //called when saving either params-in-wifi or params page - void setSaveParamsCallback( std::function func ); - - //called just before doing OTA update - void setPreOtaUpdateCallback( std::function func ); - - //called when config portal is timeout - void setConfigPortalTimeoutCallback( std::function func ); - - //sets timeout before AP,webserver loop ends and exits even if there has been no setup. - //useful for devices that failed to connect at some point and got stuck in a webserver loop - //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking - void setConfigPortalTimeout(unsigned long seconds); - void setTimeout(unsigned long seconds); // @deprecated, alias - - //sets timeout for which to attempt connecting, useful if you get a lot of failed connects - void setConnectTimeout(unsigned long seconds); - - // sets number of retries for autoconnect, force retry after wait failure exit - void setConnectRetries(uint8_t numRetries); // default 1 - - //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop - void setSaveConnectTimeout(unsigned long seconds); - - // lets you disable automatically connecting after save from webportal - void setSaveConnect(bool connect = true); - - // toggle debug output - void setDebugOutput(boolean debug); - void setDebugOutput(boolean debug, String prefix); // log line prefix, default "*wm:" - void setDebugOutput(boolean debug, wm_debuglevel_t level ); // log line prefix, default "*wm:" - - //set min quality percentage to include in scan, defaults to 8% if not specified - void setMinimumSignalQuality(int quality = 8); - - //sets a custom ip /gateway /subnet configuration - void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); - - //sets config for a static IP - void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); - - //sets config for a static IP with DNS - void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); - - //if this is set, it will exit after config, even if connection is unsuccessful. - void setBreakAfterConfig(boolean shouldBreak); - - // if this is set, portal will be blocking and wait until save or exit, - // is false user must manually `process()` to handle config portal, - // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal - void setConfigPortalBlocking(boolean shouldBlock); - - //add custom html at inside for all pages - void setCustomHeadElement(const char* html); - - //if this is set, customise style - void setCustomMenuHTML(const char* html); - - //if this is true, remove duplicated Access Points - defaut true - void setRemoveDuplicateAPs(boolean removeDuplicates); - - //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected - void setRestorePersistent(boolean persistent); - - //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig - void setShowStaticFields(boolean alwaysShow); - - //if true, always show static dns, esle only show if set via setSTAStaticIPConfig - void setShowDnsFields(boolean alwaysShow); - - // toggle showing the saved wifi password in wifi form, could be a security issue. - void setShowPassword(boolean show); - - //if false, disable captive portal redirection - void setCaptivePortalEnable(boolean enabled); - - //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open - void setAPClientCheck(boolean enabled); - - //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open - void setWebPortalClientCheck(boolean enabled); - - // if true, enable autoreconnecting - void setWiFiAutoReconnect(boolean enabled); - - // if true, wifiscan will show percentage instead of quality icons, until we have better templating - void setScanDispPerc(boolean enabled); - - // if true (default) then start the config portal from autoConnect if connection failed - void setEnableConfigPortal(boolean enable); - - // if true (default) then stop the config portal from autoConnect when wifi is saved - void setDisableConfigPortal(boolean enable); - - // if true then find the AP with the best RSSI for the given SSID - void setFindBestRSSI(boolean enabled); - - // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 - bool setHostname(const char * hostname); - bool setHostname(String hostname); - - // show erase wifi onfig button on info page, true - void setShowInfoErase(boolean enabled); - - // show OTA upload button on info page - void setShowInfoUpdate(boolean enabled); - - // set ap channel - void setWiFiAPChannel(int32_t channel); - - // set ap hidden - void setWiFiAPHidden(bool hidden); // default false - - // clean connect, always disconnect before connecting - void setCleanConnect(bool enable); // default false - - // set custom menu items and order, vector or arr - // see _menutokens for ids - void setMenu(std::vector& menu); - void setMenu(const char* menu[], uint8_t size); - - // set the webapp title, default WiFiManager - void setTitle(String title); - - // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! - void setParamsPage(bool enable); - - // get last connection result, includes autoconnect and wifisave - uint8_t getLastConxResult(); - - // get a status as string - String getWLStatusString(uint8_t status); - String getWLStatusString(); - - // get wifi mode as string - String getModeString(uint8_t mode); - - // check if the module has a saved ap to connect to - bool getWiFiIsSaved(); - - // helper to get saved password, if persistent get stored, else get current if connected - String getWiFiPass(bool persistent = true); - - // helper to get saved ssid, if persistent get stored, else get current if connected - String getWiFiSSID(bool persistent = true); - - // debug output the softap config - void debugSoftAPConfig(); - - // debug output platform info and versioning - void debugPlatformInfo(); - - // helper for html - String htmlEntities(String str, bool whitespace = false); - - // set the country code for wifi settings, CN - void setCountry(String cc); - - // set body class (invert), may be used for hacking in alt classes - void setClass(String str); - - // set dark mode via invert class - void setDarkMode(bool enable); - - // get default ap esp uses , esp_chipid etc - String getDefaultAPName(); - - // set port of webserver, 80 - void setHttpPort(uint16_t port); - - // check if config portal is active (true) - bool getConfigPortalActive(); - - // check if web portal is active (true) - bool getWebPortalActive(); - - // to preload autoconnect for test fixtures or other uses that skip esp sta config - bool preloadWiFi(String ssid, String pass); - - // get hostname helper - String getWiFiHostname(); - - - std::unique_ptr dnsServer; - - #if defined(ESP32) && defined(WM_WEBSERVERSHIM) - #ifdef WM_ASYNCWEBSERVER - using WM_WebServer = AsyncWebServer; - #else - using WM_WebServer = WebServer; - #endif - #else - #ifdef WM_ASYNCWEBSERVER - using WM_WebServer = AsyncWebServer; - #else - using WM_WebServer = ESP8266WebServer; - #endif - #endif - - std::unique_ptr server; - - protected: - // vars - std::vector _menuIds; - std::vector _menuIdsParams = {"wifi","param","info","exit"}; - std::vector _menuIdsUpdate = {"wifi","param","info","update","exit"}; - std::vector _menuIdsDefault = {"wifi","info","exit","sep","update"}; - - // ip configs @todo struct ? - IPAddress _ap_static_ip; - IPAddress _ap_static_gw; - IPAddress _ap_static_sn; - IPAddress _sta_static_ip; - IPAddress _sta_static_gw; - IPAddress _sta_static_sn; - IPAddress _sta_static_dns; - - unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) - unsigned long _webPortalAccessed = 0; // ms last web access time - uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations - int _numNetworks = 0; // init index for numnetworks wifiscans - unsigned long _lastscan = 0; // ms for timing wifi scans - unsigned long _startscan = 0; // ms for timing wifi scans - unsigned long _startconn = 0; // ms for timing wifi connects - - // defaults - const byte DNS_PORT = 53; - String _apName = "no-net"; - String _apPassword = ""; - String _ssid = ""; // var temp ssid - String _pass = ""; // var temp psk - String _defaultssid = ""; // preload ssid - String _defaultpass = ""; // preload pass - - // options flags - unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) - unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set - unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult - - WiFiMode_t _usermode = WIFI_STA; // Default user mode - String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid - int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. - bool _cleanConnect = false; // disconnect before connect in connectwifi, increases stability on connects - bool _connectonsave = true; // connect to wifi when saving creds - bool _disableSTA = false; // disable sta when starting ap, always - bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) - bool _channelSync = false; // use same wifi sta channel when starting ap - int32_t _apChannel = 0; // default channel to use for ap, 0 for auto - bool _apHidden = false; // store softap hidden value - uint16_t _httpPort = 80; // port for webserver - // uint8_t _retryCount = 0; // counter for retries, probably not needed if synchronous - uint8_t _connectRetries = 1; // number of sta connect retries, force reconnect, wait loop (connectimeout) does not always work and first disconnect bails - bool _aggresiveReconn = false; // use an agrressive reconnect strategy, WILL delay conxs - // on some conn failure modes will add delays and many retries to work around esp and ap bugs, ie, anti de-auth protections - // https://github.com/tzapu/WiFiManager/issues/1067 - bool _allowExit = true; // allow exit in nonblocking, else user exit/abort calls will be ignored including cptimeout - - #ifdef ESP32 - wifi_event_id_t wm_event_id = 0; - static uint8_t _lastconxresulttmp; // tmp var for esp32 callback - #endif - - #ifndef WL_STATION_WRONG_PASSWORD - uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password - #endif - - // parameter options - int _minimumQuality = -1; // filter wifiscan ap by this rssi - int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) - int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) - boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan - boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! - boolean _shouldBreakAfterConfig = false; // stop configportal on save failure - boolean _configPortalIsBlocking = true; // configportal enters blocking loop - boolean _enableCaptivePortal = true; // enable captive portal redirection - boolean _userpersistent = true; // users preffered persistence to restore - boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so - boolean _apClientCheck = false; // keep cp alive if ap have station - boolean _webClientCheck = true; // keep cp alive if web have client - boolean _scanDispOptions = false; // show percentage in scans not icons - boolean _paramsInWifi = true; // show custom parameters on wifi page - boolean _showInfoErase = true; // info page erase button - boolean _showInfoUpdate = true; // info page update button - boolean _showBack = false; // show back button - boolean _enableConfigPortal = true; // FOR autoconnect - start config portal if autoconnect failed - boolean _disableConfigPortal = true; // FOR autoconnect - stop config portal if cp wifi save - boolean _findBestRSSI = false; // find best rssi ap in wifiscan - String _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS - - const char* _customHeadElement = ""; // store custom head element html from user isnide - const char* _customMenuHTML = ""; // store custom head element html from user inside <> - String _bodyClass = ""; // class to add to body - String _title = FPSTR(S_brand); // app title - default WiFiManager - - // internal options - - bool _rebootNeeded = false; // async reboot flag - - // wifiscan notes - // currently disabled due to issues with caching, sometimes first scan is empty esp32 wifi not init yet race, or portals hit server nonstop flood - // The following are background wifi scanning optimizations - // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list - // ideally we would add async and xhr here but I am holding off on js requirements atm - // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. - // cache time helps throttle this - // async enables asyncronous scans, so they do not block anything - // the refresh button bypasses cache - // no aps found is problematic as scans are always going to want to run, leading to page load delays - // - // These settings really only make sense with _preloadwifiscan true - // but not limited to, we could run continuous background scans on various page hits, or xhr hits - // which would be better coupled with asyncscan - // atm preload is only done on root hit and startcp - // - // preload scanning causes AP to delay showing for users, but also caches and lets the cp load faster once its open - // my scan takes 7-10 seconds -public: - boolean _preloadwifiscan = false; // preload wifiscan if true - unsigned int _scancachetime = 30000; // ms cache time for preload scans - boolean _asyncScan = false; // perform wifi network scan async - bool wifiConnectDefault(); -protected: - - boolean _autoforcerescan = false; // automatically force rescan if scan networks is 0, ignoring cache - - boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 - - String _wificountry = ""; // country code, @todo define in strings lang - - // wrapper functions for handling setting and unsetting persistent for now. - bool esp32persistent = false; - bool _hasBegun = false; // flag wm loaded,unloaded - void _begin(); - void _end(); - - void setupConfigPortal(); - bool shutdownConfigPortal(); - bool setupHostname(bool restart); - void setupHTTPServer(); - void teardownHTTPServer(); - -#ifdef NO_EXTRA_4K_HEAP - boolean _tryWPS = false; // try WPS on save failure, unsupported - void startWPS(); -#endif - - bool startAP(); - void setupDNSD(); - - uint8_t connectWifi(String ssid, String pass, bool connect = true); - bool setSTAConfig(); - bool wifiConnectNew(String ssid, String pass,bool connect = true); - - uint8_t waitForConnectResult(); - uint8_t waitForConnectResult(uint32_t timeout); - void updateConxResult(uint8_t status); -public: - bool WiFi_scanNetworks(bool force,bool async); -protected: - // webserver handlers - void handleRoot(AsyncWebServerRequest *request); - void handleWifi(AsyncWebServerRequest *request,bool scan); - void handleWifiSave(AsyncWebServerRequest *request); - void handleInfo(AsyncWebServerRequest *request); - void handleReset(AsyncWebServerRequest *request); - void handleNotFound(AsyncWebServerRequest *request); - void handleExit(AsyncWebServerRequest *request); - void handleClose(AsyncWebServerRequest *request); - // void handleErase(AsyncWebServerRequest *request); - void handleErase(AsyncWebServerRequest *request, bool opt); - void handleParam(AsyncWebServerRequest *request); - void handleWiFiStatus(AsyncWebServerRequest *request); - void handleParamSave(AsyncWebServerRequest *request); - void doParamSave(AsyncWebServerRequest *request); - - void handleRequest(); - void HTTPSend(AsyncWebServerRequest *request, String page); - - boolean captivePortal(AsyncWebServerRequest *request); - boolean configPortalHasTimeout(); - uint8_t processConfigPortal(); - void stopCaptivePortal(); - // OTA Update handler - void handleUpdate(AsyncWebServerRequest *request); - void handleUpdating(AsyncWebServerRequest *request,String filename, size_t index, uint8_t *data, size_t len, bool final); - void handleUpdateDone(AsyncWebServerRequest *request); - - // wifi platform abstractions - bool WiFi_Mode(WiFiMode_t m); - bool WiFi_Mode(WiFiMode_t m,bool persistent); - bool WiFi_Disconnect(); - bool WiFi_enableSTA(bool enable); - bool WiFi_enableSTA(bool enable,bool persistent); - bool WiFi_eraseConfig(); - uint8_t WiFi_softap_num_stations(); - bool WiFi_hasAutoConnect(); - void WiFi_autoReconnect(); - String WiFi_SSID(bool persistent = true) const; - String WiFi_psk(bool persistent = true) const; - bool WiFi_scanNetworks(); - bool WiFi_scanNetworks(unsigned int cachetime,bool async); - bool WiFi_scanNetworks(unsigned int cachetime); - void WiFi_scanComplete(int networksFound); - bool WiFiSetCountry(); - - #ifdef ESP32 - - // check for arduino or system event system, handle esp32 arduino v2 and IDF - #if defined(ESP_ARDUINO_VERSION) && defined(ESP_ARDUINO_VERSION_VAL) - - #define WM_ARDUINOVERCHECK ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) - #define WM_ARDUINOVERCHECK_204 ESP_ARDUINO_VERSION <= ESP_ARDUINO_VERSION_VAL(2, 0, 5) - - #ifdef WM_ARDUINOVERCHECK - #define WM_ARDUINOEVENTS - #else - #define WM_NOSOFTAPSSID - #define WM_NOCOUNTRY - #endif - - #ifdef WM_ARDUINOVERCHECK_204 - #define WM_DISCONWORKAROUND - #endif - - #else - #define WM_NOCOUNTRY - #endif - - #ifdef WM_NOCOUNTRY - #warning "ESP32 set country unavailable" - #endif - - - #ifdef WM_ARDUINOEVENTS - void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info); - #else - void WiFiEvent(WiFiEvent_t event, system_event_info_t info); - #endif - #endif - - // output helpers - String getParamOut(); - String getIpForm(String id, String title, String value); - String getScanItemOut(); - String getStaticOut(); - String getHTTPHead(String title); - String getMenuOut(); - //helpers - boolean isIp(String str); - String toStringIp(IPAddress ip); - boolean validApPassword(); - String encryptionTypeStr(uint8_t authmode); - void reportStatus(String &page); - String getInfoData(String id); - - // flags - boolean connect = false; - boolean abort = false; - boolean reset = false; - boolean configPortalActive = false; - - - // these are state flags for portal mode, we are either in webportal mode(STA) or configportal mode(AP) - // these are mutually exclusive as STA+AP mode is not supported due to channel restrictions and stability - // if we decide to support this, these checks will need to be replaced with something client aware to check if client origin is ap or web - // These state checks are critical and used for internal function checks - boolean webPortalActive = false; - boolean portalTimeoutResult = false; - - boolean portalAbortResult = false; - boolean storeSTAmode = true; // option store persistent STA mode in connectwifi - int timer = 0; // timer for debug throttle for numclients, and portal timeout messages - - // WiFiManagerParameter - int _paramsCount = 0; - int _max_params; - WiFiManagerParameter** _params = NULL; - - boolean _debug = true; - String _debugPrefix = FPSTR(S_debugPrefix); - - wm_debuglevel_t debugLvlShow = WM_DEBUG_VERBOSE; // at which level start showing [n] level tags - - // build debuglevel support - // @todo use DEBUG_ESP_x? - - // Set default debug level - #ifndef WM_DEBUG_LEVEL - #define WM_DEBUG_LEVEL WM_DEBUG_NOTIFY - #endif - - // override debug level OFF - #ifdef WM_NODEBUG - #undef WM_DEBUG_LEVEL - #endif - - #ifdef WM_DEBUG_LEVEL - uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; - #else - uint8_t _debugLevel = 0; // default debug level - #endif - - // @todo use DEBUG_ESP_PORT ? - #ifdef WM_DEBUG_PORT - Print& _debugPort = WM_DEBUG_PORT; - #else - Print& _debugPort = Serial; // debug output stream ref - #endif - - template - void DEBUG_WM(Generic text); - - template - void DEBUG_WM(wm_debuglevel_t level,Generic text); - template - void DEBUG_WM(Generic text,Genericb textb); - template - void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); - - // callbacks - // @todo use cb list (vector) maybe event ids, allow no return value - std::function _apcallback; - std::function _webservercallback; - std::function _savewificallback; - std::function _presavewificallback; - std::function _presaveparamscallback; - std::function _saveparamscallback; - std::function _resetcallback; - std::function _preotaupdatecallback; - std::function _configportaltimeoutcallback; - - bool _hasCredentials = false; - char _credUser[31] = {0}; - char _credPassword[31] = {0}; - - template - auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { - return obj->fromString(s); - } - auto optionalIPFromString(...) -> bool { - // DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); - return false; - } - -}; - -#endif - -#endif diff --git a/lib/WiFiManager/examples/Advanced/Advanced.ino b/lib/WiFiManager/examples/Advanced/Advanced.ino deleted file mode 100644 index 3834e56..0000000 --- a/lib/WiFiManager/examples/Advanced/Advanced.ino +++ /dev/null @@ -1,141 +0,0 @@ -/** - * WiFiManager advanced demo, contains advanced configurartion options - * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. - */ -#include // https://github.com/tzapu/WiFiManager - -#define TRIGGER_PIN 0 - -// wifimanager can run in a blocking mode or a non blocking mode -// Be sure to know how to process loops with no delay() if using non blocking -bool wm_nonblocking = false; // change to true to use non blocking - -WiFiManager wm; // global wm instance -WiFiManagerParameter custom_field; // global param ( for non blocking w params ) - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - Serial.begin(115200); - Serial.setDebugOutput(true); - delay(3000); - Serial.println("\n Starting"); - - pinMode(TRIGGER_PIN, INPUT); - - // wm.resetSettings(); // wipe settings - - if(wm_nonblocking) wm.setConfigPortalBlocking(false); - - // add a custom input field - int customFieldLength = 40; - - - // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); - - // test custom html input type(checkbox) - // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type - - // test custom html(radio) - const char* custom_radio_str = "
One
Two
Three"; - new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input - - wm.addParameter(&custom_field); - wm.setSaveParamsCallback(saveParamCallback); - - // custom menu via array or vector - // - // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) - // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; - // wm.setMenu(menu,6); - std::vector menu = {"wifi","info","param","sep","restart","exit"}; - wm.setMenu(menu); - - // set dark theme - wm.setClass("invert"); - - - //set static ip - // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn - // wm.setShowStaticFields(true); // force show static ip fields - // wm.setShowDnsFields(true); // force show dns field always - - // wm.setConnectTimeout(20); // how long to try to connect for before continuing - wm.setConfigPortalTimeout(30); // auto close configportal after n seconds - // wm.setCaptivePortalEnable(false); // disable captive portal redirection - // wm.setAPClientCheck(true); // avoid timeout if client connected to softap - - // wifi scan settings - // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) - // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% - // wm.setShowInfoErase(false); // do not show erase button on info page - // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons - - // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails - - bool res; - // res = wm.autoConnect(); // auto generated AP name from chipid - // res = wm.autoConnect("AutoConnectAP"); // anonymous ap - res = wm.autoConnect("AutoConnectAP","password"); // password protected ap - - if(!res) { - Serial.println("Failed to connect or hit timeout"); - // ESP.restart(); - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } -} - -void checkButton(){ - // check for button press - if ( digitalRead(TRIGGER_PIN) == LOW ) { - // poor mans debounce/press-hold, code not ideal for production - delay(50); - if( digitalRead(TRIGGER_PIN) == LOW ){ - Serial.println("Button Pressed"); - // still holding button for 3000 ms, reset settings, code not ideaa for production - delay(3000); // reset delay hold - if( digitalRead(TRIGGER_PIN) == LOW ){ - Serial.println("Button Held"); - Serial.println("Erasing Config, restarting"); - wm.resetSettings(); - ESP.restart(); - } - - // start portal w delay - Serial.println("Starting config portal"); - wm.setConfigPortalTimeout(120); - - if (!wm.startConfigPortal("OnDemandAP","password")) { - Serial.println("failed to connect or hit timeout"); - delay(3000); - // ESP.restart(); - } else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - } - } -} - - -String getParam(String name){ - //read parameter from server, for customhmtl input - String value; - if(wm.server->hasArg(name)) { - value = wm.server->arg(name); - } - return value; -} - -void saveParamCallback(){ - Serial.println("[CALLBACK] saveParamCallback fired"); - Serial.println("PARAM customfieldid = " + getParam("customfieldid")); -} - -void loop() { - if(wm_nonblocking) wm.process(); // avoid delays() in loop when non-blocking and other long running code - checkButton(); - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager/examples/Basic/Basic.ino b/lib/WiFiManager/examples/Basic/Basic.ino deleted file mode 100644 index bf1e263..0000000 --- a/lib/WiFiManager/examples/Basic/Basic.ino +++ /dev/null @@ -1,41 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - - -void setup() { - // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // it is a good practice to make sure your code sets wifi mode how you want it. - - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wm; - - // reset settings - wipe stored credentials for testing - // these are stored by the esp library - // wm.resetSettings(); - - // Automatically connect using saved credentials, - // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), - // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) - // then goes into a blocking loop awaiting configuration and will return success result - - bool res; - // res = wm.autoConnect(); // auto generated AP name from chipid - // res = wm.autoConnect("AutoConnectAP"); // anonymous ap - res = wm.autoConnect("AutoConnectAP","password"); // password protected ap - - if(!res) { - Serial.println("Failed to connect"); - // ESP.restart(); - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - -} - -void loop() { - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/lib/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino deleted file mode 100644 index ab52396..0000000 --- a/lib/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino +++ /dev/null @@ -1,27 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager -WiFiManager wm; - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - - wm.setConfigPortalBlocking(false); - wm.setConfigPortalTimeout(60); - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - if(wm.autoConnect("AutoConnectAP")){ - Serial.println("connected...yeey :)"); - } - else { - Serial.println("Configportal running"); - } -} - -void loop() { - wm.process(); - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/lib/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino deleted file mode 100644 index 3af79f0..0000000 --- a/lib/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino +++ /dev/null @@ -1,36 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager -WiFiManager wm; -WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - wm.addParameter(&custom_mqtt_server); - wm.setConfigPortalBlocking(false); - wm.setSaveParamsCallback(saveParamsCallback); - - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - if(wm.autoConnect("AutoConnectAP")){ - Serial.println("connected...yeey :)"); - } - else { - Serial.println("Configportal running"); - } -} - -void loop() { - wm.process(); - // put your main code here, to run repeatedly: -} - -void saveParamsCallback () { - Serial.println("Get Params:"); - Serial.print(custom_mqtt_server.getID()); - Serial.print(" : "); - Serial.println(custom_mqtt_server.getValue()); -} diff --git a/lib/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/lib/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino deleted file mode 100644 index 0bc3992..0000000 --- a/lib/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino +++ /dev/null @@ -1,85 +0,0 @@ -/** - * OnDemandNonBlocking.ino - * example of running the webportal or configportal manually and non blocking - * trigger pin will start a webportal for 120 seconds then turn it off. - * startAP = true will start both the configportal AP and webportal - */ -#include // https://github.com/tzapu/WiFiManager - -// include MDNS -#ifdef ESP8266 -#include -#elif defined(ESP32) -#include -#endif - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -WiFiManager wm; - -unsigned int timeout = 120; // seconds to run for -unsigned int startTime = millis(); -bool portalRunning = false; -bool startAP = false; // start AP and webserver if true, else start only webserver - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once - Serial.begin(115200); - Serial.setDebugOutput(true); - delay(1000); - Serial.println("\n Starting"); - - pinMode(TRIGGER_PIN, INPUT_PULLUP); - - // wm.resetSettings(); - wm.setHostname("MDNSEXAMPLE"); - // wm.setEnableConfigPortal(false); - // wm.setConfigPortalBlocking(false); - wm.autoConnect(); -} - -void loop() { - #ifdef ESP8266 - MDNS.update(); - #endif - doWiFiManager(); - // put your main code here, to run repeatedly: -} - -void doWiFiManager(){ - // is auto timeout portal running - if(portalRunning){ - wm.process(); // do processing - - // check for timeout - if((millis()-startTime) > (timeout*1000)){ - Serial.println("portaltimeout"); - portalRunning = false; - if(startAP){ - wm.stopConfigPortal(); - } - else{ - wm.stopWebPortal(); - } - } - } - - // is configuration portal requested? - if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { - if(startAP){ - Serial.println("Button Pressed, Starting Config Portal"); - wm.setConfigPortalBlocking(false); - wm.startConfigPortal(); - } - else{ - Serial.println("Button Pressed, Starting Web Portal"); - wm.startWebPortal(); - } - portalRunning = true; - startTime = millis(); - } -} - - diff --git a/lib/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/lib/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino deleted file mode 100644 index d3c4ed8..0000000 --- a/lib/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino +++ /dev/null @@ -1,42 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("Entered config mode"); - Serial.println(WiFi.softAPIP()); - //if you used auto generated SSID, print it - Serial.println(myWiFiManager->getConfigPortalSSID()); -} - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset settings - for testing - //wifiManager.resetSettings(); - - //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wifiManager.setAPCallback(configModeCallback); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if(!wifiManager.autoConnect()) { - Serial.println("failed to connect and hit timeout"); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(1000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/lib/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino b/lib/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino deleted file mode 100644 index 53a0d13..0000000 --- a/lib/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino +++ /dev/null @@ -1,43 +0,0 @@ -#include // this needs to be first, or it all crashes and burns... -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //exit after config instead of connecting - wifiManager.setBreakAfterConfig(true); - - //reset settings - for testing - //wifiManager.resetSettings(); - - - //tries to connect to last known settings - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" with password "password" - //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { - Serial.println("failed to connect, we should reset as see if it connects"); - delay(3000); - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - - Serial.println("local ip"); - Serial.println(WiFi.localIP()); -} - -void loop() { - // put your main code here, to run repeatedly: - - -} diff --git a/lib/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/lib/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino deleted file mode 100644 index 9f88e47..0000000 --- a/lib/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino +++ /dev/null @@ -1,71 +0,0 @@ -#include // this needs to be first, or it all crashes and burns... -#include // https://github.com/tzapu/WiFiManager - -/************************************************************************************** - * this example shows how to set a static IP configuration for the ESP - * although the IP shows in the config portal, the changes will revert - * to the IP set in the source file. - * if you want the ability to configure and persist the new IP configuration - * look at the FS examples, which save the config to file - *************************************************************************************/ - -//default custom static IP -//char static_ip[16] = "10.0.1.59"; -//char static_gw[16] = "10.0.1.1"; -//char static_sn[16] = "255.255.255.0"; - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //reset settings - for testing - //wifiManager.resetSettings(); - - //set static ip - //block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2 - - //start-block1 - //IPAddress _ip,_gw,_sn; - //_ip.fromString(static_ip); - //_gw.fromString(static_gw); - //_sn.fromString(static_sn); - //end-block1 - - //start-block2 - IPAddress _ip = IPAddress(10, 0, 1, 78); - IPAddress _gw = IPAddress(10, 0, 1, 1); - IPAddress _sn = IPAddress(255, 255, 255, 0); - //end-block2 - - wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); - - - //tries to connect to last known settings - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" with password "password" - //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { - Serial.println("failed to connect, we should reset as see if it connects"); - delay(3000); - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - - Serial.println("local ip"); - Serial.println(WiFi.localIP()); -} - -void loop() { - // put your main code here, to run repeatedly: - - -} diff --git a/lib/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/lib/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino deleted file mode 100644 index 9df428d..0000000 --- a/lib/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino +++ /dev/null @@ -1,38 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset settings - for testing - //wifiManager.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setConfigPortalTimeout(180); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if(!wifiManager.autoConnect("AutoConnectAP")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/lib/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino b/lib/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino deleted file mode 100644 index a45122a..0000000 --- a/lib/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,47 +0,0 @@ -/** - * OnDemandConfigPortal.ino - * example of running the configPortal AP manually, independantly from the captiveportal - * trigger pin will start a configPortal AP for 120 seconds then turn it off. - * - */ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -int timeout = 120; // seconds to run for - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\n Starting"); - pinMode(TRIGGER_PIN, INPUT_PULLUP); -} - -void loop() { - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW) { - WiFiManager wm; - - //reset settings - for testing - //wm.resetSettings(); - - // set configportal timeout - wm.setConfigPortalTimeout(timeout); - - if (!wm.startConfigPortal("OnDemandAP")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - } - - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/lib/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino deleted file mode 100644 index 33fa384..0000000 --- a/lib/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino +++ /dev/null @@ -1,51 +0,0 @@ -/** - * OnDemandWebPortal.ino - * example of running the webportal (always NON blocking) - */ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -WiFiManager wm; - -bool portalRunning = false; - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once - Serial.begin(115200); - Serial.println("\n Starting"); - pinMode(TRIGGER_PIN, INPUT_PULLUP); -} - -void loop() { - checkButton(); - // put your main code here, to run repeatedly: -} - -void checkButton(){ - // is auto timeout portal running - if(portalRunning){ - wm.process(); - } - - // is configuration portal requested? - if(digitalRead(TRIGGER_PIN) == LOW) { - delay(50); - if(digitalRead(TRIGGER_PIN) == LOW) { - if(!portalRunning){ - Serial.println("Button Pressed, Starting Portal"); - wm.startWebPortal(); - portalRunning = true; - } - else{ - Serial.println("Button Pressed, Stopping Portal"); - wm.stopWebPortal(); - portalRunning = false; - } - } - } -} - - diff --git a/lib/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino b/lib/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino deleted file mode 100644 index 188b3c1..0000000 --- a/lib/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Basic example using LittleFS to store data - */ - -#include -#include -#include - -String readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\r\n", path); - File file = fs.open(path, "r"); - if(!file || file.isDirectory()){ - Serial.println("- empty file or failed to open file"); - return String(); - } - Serial.println("- read from file:"); - String fileContent; - while(file.available()){ - fileContent+=String((char)file.read()); - } - file.close(); - Serial.println(fileContent); - return fileContent; -} -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\r\n", path); - File file = fs.open(path, "w"); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("- file written"); - } else { - Serial.println("- write failed"); - } - file.close(); -} - -int data = 4; - -#include -#define TRIGGER_PIN 2 -int timeout = 120; // seconds to run for - -void setup() { -if (!LittleFS.begin()) { //to start littlefs -Serial.println("LittleFS mount failed"); -return; -} -data = readFile(LittleFS, "/data.txt").toInt(); -WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - pinMode(TRIGGER_PIN, INPUT_PULLUP); - WiFiManager wm; - //wm.resetSettings(); - bool res; - res = wm.autoConnect("Setup"); - if(!res) { - Serial.println("Failed to connect"); - // ESP.restart(); - } - -} - -void loop() { -if ( digitalRead(TRIGGER_PIN) == LOW) { - WiFiManager wm; - //wm.resetSettings(); - wm.setConfigPortalTimeout(timeout); - if (!wm.startConfigPortal("Sharmander")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - ESP.restart(); - delay(5000); - } - Serial.println("connected...yeey :)"); -} -} \ No newline at end of file diff --git a/lib/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/lib/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino deleted file mode 100644 index a9c7b79..0000000 --- a/lib/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ /dev/null @@ -1,169 +0,0 @@ -#include //this needs to be first, or it all crashes and burns... -#include //https://github.com/tzapu/WiFiManager - -#ifdef ESP32 - #include -#endif - -#include //https://github.com/bblanchon/ArduinoJson - -//define your default values here, if there are different values in config.json, they are overwritten. -char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char api_token[34] = "YOUR_API_TOKEN"; - -//flag for saving data -bool shouldSaveConfig = false; - -//callback notifying us of the need to save config -void saveConfigCallback () { - Serial.println("Should save config"); - shouldSaveConfig = true; -} - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - - //clean FS, for testing - //SPIFFS.format(); - - //read configuration from FS json - Serial.println("mounting FS..."); - - if (SPIFFS.begin()) { - Serial.println("mounted file system"); - if (SPIFFS.exists("/config.json")) { - //file exists, reading and loading - Serial.println("reading config file"); - File configFile = SPIFFS.open("/config.json", "r"); - if (configFile) { - Serial.println("opened config file"); - size_t size = configFile.size(); - // Allocate a buffer to store contents of the file. - std::unique_ptr buf(new char[size]); - - configFile.readBytes(buf.get(), size); - - #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 - DynamicJsonDocument json(1024); - auto deserializeError = deserializeJson(json, buf.get()); - serializeJson(json, Serial); - if ( ! deserializeError ) { -#else - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.parseObject(buf.get()); - json.printTo(Serial); - if (json.success()) { -#endif - Serial.println("\nparsed json"); - strcpy(mqtt_server, json["mqtt_server"]); - strcpy(mqtt_port, json["mqtt_port"]); - strcpy(api_token, json["api_token"]); - } else { - Serial.println("failed to load json config"); - } - configFile.close(); - } - } - } else { - Serial.println("failed to mount FS"); - } - //end read - - // The extra parameters to be configured (can be either global or just in the setup) - // After connecting, parameter.getValue() will get you the configured value - // id/name placeholder/prompt default length - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip - wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0)); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_api_token); - - //reset settings - for testing - //wifiManager.resetSettings(); - - //set minimu quality of signal so it ignores AP's under that quality - //defaults to 8% - //wifiManager.setMinimumSignalQuality(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setTimeout(120); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - //read updated parameters - strcpy(mqtt_server, custom_mqtt_server.getValue()); - strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(api_token, custom_api_token.getValue()); - Serial.println("The values in the file are: "); - Serial.println("\tmqtt_server : " + String(mqtt_server)); - Serial.println("\tmqtt_port : " + String(mqtt_port)); - Serial.println("\tapi_token : " + String(api_token)); - - //save the custom parameters to FS - if (shouldSaveConfig) { - Serial.println("saving config"); - #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 - DynamicJsonDocument json(1024); -#else - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.createObject(); -#endif - json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["api_token"] = api_token; - - File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) { - Serial.println("failed to open config file for writing"); - } - -#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 - serializeJson(json, Serial); - serializeJson(json, configFile); -#else - json.printTo(Serial); - json.printTo(configFile); -#endif - configFile.close(); - //end save - } - - Serial.println("local ip"); - Serial.println(WiFi.localIP()); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/lib/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/lib/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino deleted file mode 100644 index 63523e9..0000000 --- a/lib/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ /dev/null @@ -1,194 +0,0 @@ -#include //this needs to be first, or it all crashes and burns... - -#include //https://github.com/tzapu/WiFiManager - -#ifdef ESP32 - #include -#endif - -#include //https://github.com/bblanchon/ArduinoJson - -//define your default values here, if there are different values in config.json, they are overwritten. -//length should be max size + 1 -char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char api_token[34] = "YOUR_APITOKEN"; -//default custom static IP -char static_ip[16] = "10.0.1.56"; -char static_gw[16] = "10.0.1.1"; -char static_sn[16] = "255.255.255.0"; - -//flag for saving data -bool shouldSaveConfig = false; - -//callback notifying us of the need to save config -void saveConfigCallback () { - Serial.println("Should save config"); - shouldSaveConfig = true; -} - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - - //clean FS, for testing - //SPIFFS.format(); - - //read configuration from FS json - Serial.println("mounting FS..."); - - if (SPIFFS.begin()) { - Serial.println("mounted file system"); - if (SPIFFS.exists("/config.json")) { - //file exists, reading and loading - Serial.println("reading config file"); - File configFile = SPIFFS.open("/config.json", "r"); - if (configFile) { - Serial.println("opened config file"); - size_t size = configFile.size(); - // Allocate a buffer to store contents of the file. - std::unique_ptr buf(new char[size]); - - configFile.readBytes(buf.get(), size); - #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 - DynamicJsonDocument json(1024); - auto deserializeError = deserializeJson(json, buf.get()); - serializeJson(json, Serial); - if ( ! deserializeError ) { -#else - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.parseObject(buf.get()); - json.printTo(Serial); - if (json.success()) { -#endif - Serial.println("\nparsed json"); - - strcpy(mqtt_server, json["mqtt_server"]); - strcpy(mqtt_port, json["mqtt_port"]); - strcpy(api_token, json["api_token"]); - - if (json["ip"]) { - Serial.println("setting custom ip from config"); - strcpy(static_ip, json["ip"]); - strcpy(static_gw, json["gateway"]); - strcpy(static_sn, json["subnet"]); - Serial.println(static_ip); - } else { - Serial.println("no custom ip in config"); - } - } else { - Serial.println("failed to load json config"); - } - } - } - } else { - Serial.println("failed to mount FS"); - } - //end read - Serial.println(static_ip); - Serial.println(api_token); - Serial.println(mqtt_server); - - - // The extra parameters to be configured (can be either global or just in the setup) - // After connecting, parameter.getValue() will get you the configured value - // id/name placeholder/prompt default length - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); - WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 34); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip - IPAddress _ip, _gw, _sn; - _ip.fromString(static_ip); - _gw.fromString(static_gw); - _sn.fromString(static_sn); - - wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_api_token); - - //reset settings - for testing - //wifiManager.resetSettings(); - - //set minimu quality of signal so it ignores AP's under that quality - //defaults to 8% - wifiManager.setMinimumSignalQuality(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setTimeout(120); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - //read updated parameters - strcpy(mqtt_server, custom_mqtt_server.getValue()); - strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(api_token, custom_api_token.getValue()); - - //save the custom parameters to FS - if (shouldSaveConfig) { - Serial.println("saving config"); - #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 - DynamicJsonDocument json(1024); -#else - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.createObject(); -#endif - json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["api_token"] = api_token; - - json["ip"] = WiFi.localIP().toString(); - json["gateway"] = WiFi.gatewayIP().toString(); - json["subnet"] = WiFi.subnetMask().toString(); - - File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) { - Serial.println("failed to open config file for writing"); - } - - #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 - serializeJson(json, Serial); - serializeJson(json, configFile); -#else - json.printTo(Serial); - json.printTo(configFile); -#endif - configFile.close(); - //end save - } - - Serial.println("local ip"); - Serial.println(WiFi.localIP()); - Serial.println(WiFi.gatewayIP()); - Serial.println(WiFi.subnetMask()); -} - -void loop() { - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino b/lib/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino deleted file mode 100644 index 8739a05..0000000 --- a/lib/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino +++ /dev/null @@ -1,143 +0,0 @@ -/** - * WiFiManagerParameter child class example - */ -#include // https://github.com/tzapu/WiFiManager -#include -#include - -#define SETUP_PIN 0 - -class IPAddressParameter : public WiFiManagerParameter { -public: - IPAddressParameter(const char *id, const char *placeholder, IPAddress address) - : WiFiManagerParameter("") { - init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); - } - - bool getValue(IPAddress &ip) { - return ip.fromString(WiFiManagerParameter::getValue()); - } -}; - -class IntParameter : public WiFiManagerParameter { -public: - IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) - : WiFiManagerParameter("") { - init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); - } - - long getValue() { - return String(WiFiManagerParameter::getValue()).toInt(); - } -}; - -class FloatParameter : public WiFiManagerParameter { -public: - FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) - : WiFiManagerParameter("") { - init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); - } - - float getValue() { - return String(WiFiManagerParameter::getValue()).toFloat(); - } -}; - -struct Settings { - float f; - int i; - char s[20]; - uint32_t ip; -} sett; - - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - pinMode(SETUP_PIN, INPUT_PULLUP); - Serial.begin(115200); - - //Delay to push SETUP button - Serial.println("Press setup button"); - for (int sec = 3; sec > 0; sec--) { - Serial.print(sec); - Serial.print(".."); - delay(1000); - } - - // warning for example only, this will initialize empty memory into your vars - // always init flash memory or add some checksum bits - EEPROM.begin( 512 ); - EEPROM.get(0, sett); - Serial.println("Settings loaded"); - - if (digitalRead(SETUP_PIN) == LOW) { - // Button pressed - Serial.println("SETUP"); - - WiFiManager wm; - - sett.s[19] = '\0'; //add null terminator at the end cause overflow - WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); - FloatParameter param_float( "float", "param_float", sett.f); - IntParameter param_int( "int", "param_int", sett.i); - - IPAddress ip(sett.ip); - IPAddressParameter param_ip("ip", "param_ip", ip); - - wm.addParameter( ¶m_str ); - wm.addParameter( ¶m_float ); - wm.addParameter( ¶m_int ); - wm.addParameter( ¶m_ip ); - - //SSID & password parameters already included - wm.startConfigPortal(); - - strncpy(sett.s, param_str.getValue(), 20); - sett.s[19] = '\0'; - sett.f = param_float.getValue(); - sett.i = param_int.getValue(); - - Serial.print("String param: "); - Serial.println(sett.s); - Serial.print("Float param: "); - Serial.println(sett.f); - Serial.print("Int param: "); - Serial.println(sett.i, DEC); - - if (param_ip.getValue(ip)) { - sett.ip = ip; - - Serial.print("IP param: "); - Serial.println(ip); - } else { - Serial.println("Incorrect IP"); - } - - EEPROM.put(0, sett); - if (EEPROM.commit()) { - Serial.println("Settings saved"); - } else { - Serial.println("EEPROM error"); - } - } - else { - Serial.println("WORK"); - - //connect to saved SSID - WiFi.begin(); - - //do smth - Serial.print("String param: "); - Serial.println(sett.s); - Serial.print("Float param: "); - Serial.println(sett.f); - Serial.print("Int param: "); - Serial.println(sett.i, DEC); - Serial.print("IP param: "); - IPAddress ip(sett.ip); - Serial.println(ip); - } -} - -void loop() { -} diff --git a/lib/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino b/lib/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino deleted file mode 100644 index 7962d62..0000000 --- a/lib/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,444 +0,0 @@ -/** - * This is a kind of unit test for DEV for now - * It contains many of the public methods - * - */ -#include // https://github.com/tzapu/WiFiManager -#include -#include - -#define USEOTA -// enable OTA -#ifdef USEOTA -#include -#include -#endif - -const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; - -unsigned long mtime = 0; - - -WiFiManager wm; - - -// TEST OPTION FLAGS -bool TEST_CP = false; // always start the configportal, even if ap found -int TESP_CP_TIMEOUT = 90; // test cp timeout - -bool TEST_NET = true; // do a network test after connect, (gets ntp time) -bool ALLOWONDEMAND = true; // enable on demand -int ONDDEMANDPIN = 0; // gpio for button -bool WMISBLOCKING = true; // use blocking or non blocking mode, non global params wont work in non blocking - -uint8_t BUTTONFUNC = 1; // 0 resetsettings, 1 configportal, 2 autoconnect - -// char ssid[] = "*************"; // your network SSID (name) -// char pass[] = "********"; // your network password - - -//callbacks - // called after AP mode and config portal has started - // setAPCallback( std::function func ); - // called after webserver has started - // setWebServerCallback( std::function func ); - // called when settings reset have been triggered - // setConfigResetCallback( std::function func ); - // called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) - // setSaveConfigCallback( std::function func ); - // called when saving either params-in-wifi or params page - // setSaveParamsCallback( std::function func ); - // called when saving params-in-wifi or params before anything else happens (eg wifi) - // setPreSaveConfigCallback( std::function func ); - // called just before doing OTA update - // setPreOtaUpdateCallback( std::function func ); - -void saveWifiCallback(){ - Serial.println("[CALLBACK] saveCallback fired"); -} - -//gets called when WiFiManager enters configuration mode -void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("[CALLBACK] configModeCallback fired"); - // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // Serial.println(WiFi.softAPIP()); - //if you used auto generated SSID, print it - // Serial.println(myWiFiManager->getConfigPortalSSID()); - // - // esp_wifi_set_bandwidth(WIFI_IF_AP, WIFI_BW_HT20); -} - -void saveParamCallback(){ - Serial.println("[CALLBACK] saveParamCallback fired"); - // wm.stopConfigPortal(); -} - -void bindServerCallback(){ - wm.server->on("/custom",handleRoute); - - // you can override wm route endpoints, I have not found a way to remove handlers, but this would let you disable them or add auth etc. - // wm.server->on("/info",handleNotFound); - // wm.server->on("/update",handleNotFound); - wm.server->on("/erase",handleNotFound); // disable erase -} - -void handleRoute(){ - Serial.println("[HTTP] handle custom route"); - wm.server->send(200, "text/plain", "hello from user code"); -} - -void handleNotFound(){ - Serial.println("[HTTP] override handle route"); - wm.handleNotFound(); -} - -void handlePreOtaUpdateCallback(){ - Update.onProgress([](unsigned int progress, unsigned int total) { - Serial.printf("CUSTOM Progress: %u%%\r", (progress / (total / 100))); - }); -} - -void setup() { - // WiFi.mode(WIFI_STA); // explicitly set mode, esp can default to STA+AP - - // put your setup code here, to run once: - Serial.begin(115200); - delay(3000); - // Serial.setDebugOutput(true); - - // WiFi.setTxPower(WIFI_POWER_8_5dBm); - - Serial.println("\n Starting"); - // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability - - Serial.println("Error - TEST"); - Serial.println("Information- - TEST"); - - Serial.println("[ERROR] TEST"); - Serial.println("[INFORMATION] TEST"); - - - // WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); // wifi_scan_method_t scanMethod - // WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); // wifi_sort_method_t sortMethod - WIFI_CONNECT_AP_BY_SIGNAL,WIFI_CONNECT_AP_BY_SECURITY - // WiFi.setMinSecurity(WIFI_AUTH_WPA2_PSK); - - wm.setDebugOutput(true, WM_DEBUG_DEV); - wm.debugPlatformInfo(); - - //reset settings - for testing - // wm.resetSettings(); - // wm.erase(); - - // setup some parameters - - WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); - WiFiManagerParameter custom_token("api_token", "api token", "", 16); - WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces - WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) - WiFiManagerParameter custom_input_type("input_pwd", "input pass", "", 15,"type='password'"); // custom input attrs (ip mask) - - const char _customHtml_checkbox[] = "type=\"checkbox\""; - WiFiManagerParameter custom_checkbox("my_checkbox", "My Checkbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); - - const char *bufferStr = R"( - -
-

Select Choice

- -
- -
- - -
- - - )"; - - WiFiManagerParameter custom_html_inputs(bufferStr); - - // callbacks - wm.setAPCallback(configModeCallback); - wm.setWebServerCallback(bindServerCallback); - wm.setSaveConfigCallback(saveWifiCallback); - wm.setSaveParamsCallback(saveParamCallback); - wm.setPreOtaUpdateCallback(handlePreOtaUpdateCallback); - - // add all your parameters here - wm.addParameter(&custom_html); - wm.addParameter(&custom_mqtt_server); - wm.addParameter(&custom_mqtt_port); - wm.addParameter(&custom_token); - wm.addParameter(&custom_tokenb); - wm.addParameter(&custom_ipaddress); - wm.addParameter(&custom_checkbox); - wm.addParameter(&custom_input_type); - - wm.addParameter(&custom_html_inputs); - - // set values later if you want - custom_html.setValue("test",4); - custom_token.setValue("test",4); - - // const char* icon = " - // "; - - - // set custom html head content , inside - // examples of favicon, or meta tags etc - // const char* headhtml = ""; - // const char* headhtml = ""; - // wm.setCustomHeadElement(headhtml); - - // set custom html menu content , inside menu item "custom", see setMenu() - const char* menuhtml = "

\n"; - wm.setCustomMenuHTML(menuhtml); - - // invert theme, dark - wm.setDarkMode(true); - - // show scan RSSI as percentage, instead of signal stength graphic - // wm.setScanDispPerc(true); - -/* - Set cutom menu via menu[] or vector - const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - wm.setMenu(menu,9); // custom menu array must provide length -*/ - - std::vector menu = {"wifi","wifinoscan","info","param","custom","close","sep","erase","update","restart","exit"}; - // wm.setMenu(menu); // custom menu, pass vector - - // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! - - // set STA static ip - // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wm.setShowStaticFields(false); - // wm.setShowDnsFields(false); - - // set AP static ip - // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - // set country - // setting wifi country seems to improve OSX soft ap connectivity, - // may help others as well, default is CN which has different channels - - // wm.setCountry("US"); // crashing on esp32 2.0 - - // set Hostname - - // wm.setHostname(("WM_"+wm.getDefaultAPName()).c_str()); - // wm.setHostname("WM_RANDO_1234"); - - // set custom channel - // wm.setWiFiAPChannel(13); - - // set AP hidden - // wm.setAPHidden(true); - - // show password publicly in form - // wm.setShowPassword(true); - - // sets wether wm configportal is a blocking loop(legacy) or not, use wm.process() in loop if false - // wm.setConfigPortalBlocking(false); - - if(!WMISBLOCKING){ - wm.setConfigPortalBlocking(false); - } - - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep in seconds - wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); - - // set min quality to show in web list, default 8% - // wm.setMinimumSignalQuality(50); - - // set connection timeout - // wm.setConnectTimeout(20); - - // set wifi connect retries - // wm.setConnectRetries(2); - - // connect after portal save toggle - // wm.setSaveConnect(false); // do not connect, only save - - // show static ip fields - // wm.setShowStaticFields(true); - - // wm.startConfigPortal("AutoConnectAP", "password"); - - // This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib - // wm.setCleanConnect(true); // disconnect before connect, clean connect - - wm.setBreakAfterConfig(true); // needed to use saveWifiCallback - - // set custom webserver port, automatic captive portal does not work with custom ports! - // wm.setHttpPort(8080); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - - // use autoconnect, but prevent configportal from auto starting - // wm.setEnableConfigPortal(false); - - wifiInfo(); - - // to preload autoconnect with credentials - // wm.preloadWiFi("ssid","password"); - - if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { - Serial.println("failed to connect and hit timeout"); - } - else if(TEST_CP) { - // start configportal always - delay(1000); - Serial.println("TEST_CP ENABLED"); - wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); - wm.startConfigPortal("WM_ConnectAP","12345678"); - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - - wifiInfo(); - pinMode(ONDDEMANDPIN, INPUT_PULLUP); - - #ifdef USEOTA - ArduinoOTA.begin(); - #endif - -} - -void wifiInfo(){ - // can contain gargbage on esp32 if wifi is not ready yet - Serial.println("[WIFI] WIFI_INFO DEBUG"); - WiFi.printDiag(Serial); - Serial.println("[WIFI] MODE: " + (String)(wm.getModeString(WiFi.getMode()))); - Serial.println("[WIFI] SAVED: " + (String)(wm.getWiFiIsSaved() ? "YES" : "NO")); - Serial.println("[WIFI] SSID: " + (String)wm.getWiFiSSID()); - Serial.println("[WIFI] PASS: " + (String)wm.getWiFiPass()); - // Serial.println("[WIFI] HOSTNAME: " + (String)WiFi.getHostname()); -} - -void loop() { - - if(!WMISBLOCKING){ - wm.process(); - } - - - #ifdef USEOTA - ArduinoOTA.handle(); - #endif - // is configuration portal requested? - if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW ) { - delay(100); - if ( digitalRead(ONDDEMANDPIN) == LOW || BUTTONFUNC == 2){ - Serial.println("BUTTON PRESSED"); - - // button reset/reboot - if(BUTTONFUNC == 0){ - wm.resetSettings(); - wm.reboot(); - delay(200); - return; - } - - // start configportal - if(BUTTONFUNC == 1){ - if (!wm.startConfigPortal("OnDemandAP","12345678")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - } - return; - } - - //test autoconnect as reconnect etc. - if(BUTTONFUNC == 2){ - wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); - wm.autoConnect(); - return; - } - - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - getTime(); - } - } - - // every 10 seconds - if(millis()-mtime > 10000 ){ - if(WiFi.status() == WL_CONNECTED){ - getTime(); - } - else Serial.println("No Wifi"); - mtime = millis(); - } - // put your main code here, to run repeatedly: - delay(100); -} - -void getTime() { - int tz = -5; - int dst = 0; - time_t now = time(nullptr); - unsigned timeout = 5000; // try for timeout - unsigned start = millis(); - configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); - Serial.print("Waiting for NTP time sync: "); - while (now < 8 * 3600 * 2 ) { // what is this ? - delay(100); - Serial.print("."); - now = time(nullptr); - if((millis() - start) > timeout){ - Serial.println("\n[ERROR] Failed to get NTP time."); - return; - } - } - Serial.println(""); - struct tm timeinfo; - gmtime_r(&now, &timeinfo); - Serial.print("Current time: "); - Serial.print(asctime(&timeinfo)); -} - -void debugchipid(){ - // WiFi.mode(WIFI_STA); - // WiFi.printDiag(Serial); - // Serial.println(modes[WiFi.getMode()]); - - // ESP.eraseConfig(); - // wm.resetSettings(); - // wm.erase(true); - WiFi.mode(WIFI_AP); - // WiFi.softAP(); - WiFi.enableAP(true); - delay(500); - // esp_wifi_start(); - delay(1000); - WiFi.printDiag(Serial); - delay(60000); - ESP.restart(); - - // AP esp_267751 - // 507726A4AE30 - // ESP32 Chip ID = 507726A4AE30 -} diff --git a/lib/WiFiManager/examples/Tests/wifi_softap/wifi_softap.ino b/lib/WiFiManager/examples/Tests/wifi_softap/wifi_softap.ino deleted file mode 100644 index aa3e45c..0000000 --- a/lib/WiFiManager/examples/Tests/wifi_softap/wifi_softap.ino +++ /dev/null @@ -1,51 +0,0 @@ -// wifi_basic.ino - -#include -#include - -// #define NVSERASE -#ifdef NVSERASE -#include -#include -#endif - -void setup(){ - Serial.begin(115200); - delay(2000); - Serial.println("Startup...."); - - #ifdef NVSERASE - esp_err_t err; - err = nvs_flash_init(); - err = nvs_flash_erase(); - #endif - - Serial.setDebugOutput(true); - - WiFi.begin("hellowifi","noonehere"); - - while (WiFi.status() != WL_CONNECTED && millis()<15000) { - delay(500); - Serial.print("."); - } - - if(WiFi.status() == WL_CONNECTED){ - Serial.println(""); - Serial.println("WiFi connected."); - Serial.println("IP address: "); - // Serial.println(WiFi.localIP()); - } - else { - Serial.println("WiFi NOT CONNECTED, starting ap"); - /////////////// - /// BUG - // WiFi.enableSTA(false); // BREAKS softap start, says ok BUT no ap found - - delay(2000); - WiFi.softAP("espsoftap","12345678"); - } -} - -void loop(){ - -} \ No newline at end of file diff --git a/lib/WiFiManager/examples/Unique/cb/AnonymousCB.ino b/lib/WiFiManager/examples/Unique/cb/AnonymousCB.ino deleted file mode 100644 index f34d80f..0000000 --- a/lib/WiFiManager/examples/Unique/cb/AnonymousCB.ino +++ /dev/null @@ -1,26 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -bool _enteredConfigMode = false; - -void setup(){ - Serial.begin(115200); - WiFiManager wifiManager; - - // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { - wifiManager.setAPCallback([&](WiFiManager* wifiManager) { - Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", - WiFi.softAPIP().toString().c_str(), - wifiManager->getConfigPortalSSID().c_str()); - _enteredConfigMode = true; - }); - wifiManager.resetSettings(); - if (!wifiManager.autoConnect()) { - Serial.printf("*** Failed to connect and hit timeout\n"); - ESP.restart(); - delay(1000); - } -} - -void loop(){ - -} diff --git a/lib/WiFiManager/extras/WiFiManager.template.html b/lib/WiFiManager/extras/WiFiManager.template.html deleted file mode 100644 index 934c033..0000000 --- a/lib/WiFiManager/extras/WiFiManager.template.html +++ /dev/null @@ -1,400 +0,0 @@ - - - - - - {v} - - - - - - - - - - -
- - - -

/


- - - - -

-

-

-

-

-

-

-

-

-

-

- - -

/wifi


- - - - - - - - - - - - - - - - - - - - -



- - -

custom parameter


-
-
- - -
- - -
- - -
- - -
- - -

Saving Credentials

Trying to connect ESP to network.
If it fails reconnect to AP to try again
- - -
Connected to {v}
with IP {i}
- - -
Not Connected to {v}{r}
- - -
Not Connected to apname - - -
Authentication Failure - - -
AP not found - - -
Could not Connect - -
- -
No AP set
- - -

H4 Color Header P

content
- - -

H4 Color Header S

content
- - -

Heading 1

-

Heading 2

-

Heading 3

-

Heading 4

-

WIFI HEAD (WIFI_OFF)


-
-
Chip ID
123456
-
Flash Chip ID
1234556
-
IDE Flash Size
4194304 bytes
-
Real Flash Size
4194304 bytes
-
Empty
-
Soft AP IP
192.168.4.1
-
Soft AP MAC
00:00:00:00:00:00
-
Station MAC
00:00:00:00:00:00
-
- - -

Available Pages


- - - - - - - - - - - - - - - - - - - - -
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/closeClose the configuration server and configuration WiFi network.
/infoInformation page
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
-

About


- Version v1.x.x-xxxxx
- Build_date
- Build_file
- Arduino_version
-

Github https://github.com/tzapu/WiFiManager - - -

Form UPLOAD
-

- - - * Upload may not function inside captive portal, Open in browser - http://192.168.4.1 - - - - -



-
- -
- -
- - - - - -
- - -

Select Choice

- -
- -
- - -
- - - -
- - - - -
- - - diff --git a/lib/WiFiManager/extras/parse.js b/lib/WiFiManager/extras/parse.js deleted file mode 100644 index 97a3e38..0000000 --- a/lib/WiFiManager/extras/parse.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -const fs = require('fs'); - -console.log('starting'); - -const inFile = 'WiFiManager.template.html'; -const outFile = 'template.h'; - -const defineRegEx = //gm; -console.log('parsing', inFile); - -fs.readFile(inFile, 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - //console.log(data); - - let defines = data.match(defineRegEx); - - //console.log(defines); - var stream = fs.createWriteStream(outFile); - stream.once('open', function(fd) { - for (const i in defines) { - - const start = defines[i]; - const end = start.replace(' - - - - diff --git a/lib/WiFiManager/keywords.txt b/lib/WiFiManager/keywords.txt deleted file mode 100644 index 7159e74..0000000 --- a/lib/WiFiManager/keywords.txt +++ /dev/null @@ -1,39 +0,0 @@ -####################################### -# Syntax Coloring Map For WifiManager -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -WiFiManager KEYWORD1 -WiFiManagerParameter KEYWORD1 - - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -autoConnect KEYWORD2 -getSSID KEYWORD2 -getPassword KEYWORD2 -getConfigPortalSSID KEYWORD2 -resetSettings KEYWORD2 -setConfigPortalTimeout KEYWORD2 -setConnectTimeout KEYWORD2 -setDebugOutput KEYWORD2 -setMinimumSignalQuality KEYWORD2 -setAPStaticIPConfig KEYWORD2 -setSTAStaticIPConfig KEYWORD2 -setAPCallback KEYWORD2 -setSaveConfigCallback KEYWORD2 -addParameter KEYWORD2 -getID KEYWORD2 -getValue KEYWORD2 -getPlaceholder KEYWORD2 -getValueLength KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -# LITERAL1 diff --git a/lib/WiFiManager/library.json b/lib/WiFiManager/library.json deleted file mode 100644 index a04050a..0000000 --- a/lib/WiFiManager/library.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "WiFiManager", - "version": "2.0.17", - "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", - "description": "WiFi Configuration manager with web configuration portal for ESP boards", - "authors": - [ - { - "name": "tzapu", - "url": "https://github.com/tzapu" - }, - { - "name": "tablatronix", - "url": "https://github.com/tablatronix", - "maintainer": true - } - ], - "repository": - { - "type": "git", - "url": "https://github.com/tzapu/WiFiManager.git" - }, - "frameworks": "arduino", - "platforms": - [ - "espressif8266", - "espressif32" - ] -} \ No newline at end of file diff --git a/lib/WiFiManager/library.properties b/lib/WiFiManager/library.properties deleted file mode 100644 index 559ff72..0000000 --- a/lib/WiFiManager/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=WiFiManager -version=2.0.17 -author=tzapu -maintainer=tablatronix -sentence=WiFi Configuration manager with web configuration portal for Espressif ESPx boards, by tzapu -paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime with captive portal. -category=Communication -url=https://github.com/tzapu/WiFiManager.git -architectures=esp8266,esp32 diff --git a/lib/WiFiManager/strings_en.h b/lib/WiFiManager/strings_en.h deleted file mode 100644 index cabeb58..0000000 --- a/lib/WiFiManager/strings_en.h +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Contents of this file have moved to 2 new locations - * wm_strings_nn.h - * wm_consts_nn.h - */ - -#warning "This file is deprecated" - -#ifndef _STRINGS_EN_H_ -#define _STRINGS_EN_H_ - -// strings files must include a consts file! -#include "wm_strings_en.h" // include constants, tokens, routes - -#endif \ No newline at end of file diff --git a/lib/WiFiManager/travis/common.sh b/lib/WiFiManager/travis/common.sh deleted file mode 100644 index 4b3e655..0000000 --- a/lib/WiFiManager/travis/common.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -function build_examples() -{ - excludes=("$@") - # track the exit code for this platform - local exit_code=0 - # loop through results and add them to the array - examples=($(find $PWD/examples/ -name "*.pde" -o -name "*.ino")) - - # get the last example in the array - local last="${examples[@]:(-1)}" - - # loop through example sketches - for example in "${examples[@]}"; do - - # store the full path to the example's sketch directory - local example_dir=$(dirname $example) - - # store the filename for the example without the path - local example_file=$(basename $example) - - # skip files listed as excludes - for exclude in "${excludes[@]}"; do - if [ "${example_file}" == "${exclude}" ] ; then - echo ">>>>>>>>>>>>>>>>>>>>>>>> Skipping ${example_file} <<<<<<<<<<<<<<<<<<<<<<<<<<" - continue 2 - fi - done - - echo "$example_file: " - local sketch="$example_dir/$example_file" - echo "$sketch" - #arduino -v --verbose-build --verify $sketch - - # verify the example, and save stdout & stderr to a variable - # we have to avoid reading the exit code of local: - # "when declaring a local variable in a function, the local acts as a command in its own right" - local build_stdout - build_stdout=$(arduino --verify $sketch 2>&1) - - # echo output if the build failed - if [ $? -ne 0 ]; then - # heavy X - echo -e "\xe2\x9c\x96" - echo -e "----------------------------- DEBUG OUTPUT -----------------------------\n" - echo "$build_stdout" - echo -e "\n------------------------------------------------------------------------\n" - - # mark as fail - exit_code=1 - - else - # heavy checkmark - echo -e "\xe2\x9c\x93" - fi - done - - return $exit_code -} diff --git a/lib/WiFiManager/wm_consts_en.h b/lib/WiFiManager/wm_consts_en.h deleted file mode 100644 index dac35e4..0000000 --- a/lib/WiFiManager/wm_consts_en.h +++ /dev/null @@ -1,265 +0,0 @@ -/** - * wm_consts.h - * internal const strings/tokens - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - -#ifndef _WM_CONSTS_H -#define _WM_CONSTS_H - - -// ----------------------------------------------------------------------------------------------- -// TOKENS - -const char WM_VERSION_STR[] PROGMEM = "v2.0.17"; - -static const char _wifi_token[] PROGMEM = "wifi"; -static const char _wifinoscan_token[] PROGMEM = "wifinoscan"; -static const char _info_token[] PROGMEM = "info"; -static const char _param_token[] PROGMEM = "param"; -static const char _close_token[] PROGMEM = "close"; -static const char _restart_token[] PROGMEM = "restart"; -static const char _exit_token[] PROGMEM = "exit"; -static const char _erase_token[] PROGMEM = "erase"; -static const char _update_token[] PROGMEM = "update"; -static const char _sep_token[] PROGMEM = "sep"; -static const char _custom_token[] PROGMEM = "custom"; -static PGM_P _menutokens[] PROGMEM = { - _wifi_token, - _wifinoscan_token, - _info_token, - _param_token, - _close_token, - _restart_token, - _exit_token, - _erase_token, - _update_token, - _sep_token, - _custom_token -}; -const uint8_t _nummenutokens = (sizeof(_menutokens) / sizeof(PGM_P)); - - -const char R_root[] PROGMEM = "/"; -const char R_wifi[] PROGMEM = "/wifi"; -const char R_wifinoscan[] PROGMEM = "/0wifi"; -const char R_wifisave[] PROGMEM = "/wifisave"; -const char R_info[] PROGMEM = "/info"; -const char R_param[] PROGMEM = "/param"; -const char R_paramsave[] PROGMEM = "/paramsave"; -const char R_restart[] PROGMEM = "/restart"; -const char R_exit[] PROGMEM = "/exit"; -const char R_close[] PROGMEM = "/close"; -const char R_erase[] PROGMEM = "/erase"; -const char R_status[] PROGMEM = "/status"; -const char R_update[] PROGMEM = "/update"; -const char R_updatedone[] PROGMEM = "/u"; - - -//Strings -const char S_ip[] PROGMEM = "ip"; -const char S_gw[] PROGMEM = "gw"; -const char S_sn[] PROGMEM = "sn"; -const char S_dns[] PROGMEM = "dns"; - - - -//Tokens -//@todo consolidate and reduce -const char T_ss[] PROGMEM = "{"; // token start sentinel -const char T_es[] PROGMEM = "}"; // token end sentinel -const char T_1[] PROGMEM = "{1}"; // @token 1 -const char T_2[] PROGMEM = "{2}"; // @token 2 -const char T_3[] PROGMEM = "{3}"; // @token 2 -const char T_v[] PROGMEM = "{v}"; // @token v -const char T_V[] PROGMEM = "{V}"; // @token v -const char T_I[] PROGMEM = "{I}"; // @token I -const char T_i[] PROGMEM = "{i}"; // @token i -const char T_n[] PROGMEM = "{n}"; // @token n -const char T_p[] PROGMEM = "{p}"; // @token p -const char T_t[] PROGMEM = "{t}"; // @token t -const char T_l[] PROGMEM = "{l}"; // @token l -const char T_c[] PROGMEM = "{c}"; // @token c -const char T_e[] PROGMEM = "{e}"; // @token e -const char T_q[] PROGMEM = "{q}"; // @token q -const char T_r[] PROGMEM = "{r}"; // @token r -const char T_R[] PROGMEM = "{R}"; // @token R -const char T_h[] PROGMEM = "{h}"; // @token h - -// http -const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; -const char HTTP_HEAD_CT[] PROGMEM = "text/html"; -const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; -const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; -const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; - -const char * const WIFI_STA_STATUS[] PROGMEM -{ - "WL_IDLE_STATUS", // 0 STATION_IDLE - "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND - "WL_SCAN_COMPLETED", // 2 - "WL_CONNECTED", // 3 STATION_GOT_IP - "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) - "WL_CONNECTION_LOST", // 5 - "WL_DISCONNECTED", // 6 - "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE -}; - -#ifdef ESP32 -const char * const AUTH_MODE_NAMES[] PROGMEM -{ - "OPEN", - "WEP", - "WPA_PSK", - "WPA2_PSK", - "WPA_WPA2_PSK", - "WPA2_ENTERPRISE", - "MAX" -}; -#elif defined(ESP8266) -const char * const AUTH_MODE_NAMES[] PROGMEM -{ - "", - "", - "WPA_PSK", // 2 ENC_TYPE_TKIP - "", - "WPA2_PSK", // 4 ENC_TYPE_CCMP - "WEP", // 5 ENC_TYPE_WEP - "", - "OPEN", //7 ENC_TYPE_NONE - "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO -}; -#endif - -const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; - - -#ifdef ESP32 -// as 2.5.2 -// typedef struct { -// char cc[3]; /**< country code string */ -// uint8_t schan; /**< start channel */ -// uint8_t nchan; /**< total channel number */ -// int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ -// wifi_country_policy_t policy; /**< country policy */ -// } wifi_country_t; -const wifi_country_t WM_COUNTRY_US{"US",1,11,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_CN{"CN",1,13,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_JP{"JP",1,14,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; -#elif defined(ESP8266) && !defined(WM_NOCOUNTRY) -// typedef struct { -// char cc[3]; /**< country code string */ -// uint8_t schan; /**< start channel */ -// uint8_t nchan; /**< total channel number */ -// uint8_t policy; /**< country policy */ -// } wifi_country_t; -const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; -#endif - - -/* -* ESP32 WiFi Events - -0 SYSTEM_EVENT_WIFI_READY < ESP32 WiFi ready -1 SYSTEM_EVENT_SCAN_DONE < ESP32 finish scanning AP -2 SYSTEM_EVENT_STA_START < ESP32 station start -3 SYSTEM_EVENT_STA_STOP < ESP32 station stop -4 SYSTEM_EVENT_STA_CONNECTED < ESP32 station connected to AP -5 SYSTEM_EVENT_STA_DISCONNECTED < ESP32 station disconnected from AP -6 SYSTEM_EVENT_STA_AUTHMODE_CHANGE < the auth mode of AP connected by ESP32 station changed -7 SYSTEM_EVENT_STA_GOT_IP < ESP32 station got IP from connected AP -8 SYSTEM_EVENT_STA_LOST_IP < ESP32 station lost IP and the IP is reset to 0 -9 SYSTEM_EVENT_STA_WPS_ER_SUCCESS < ESP32 station wps succeeds in enrollee mode -10 SYSTEM_EVENT_STA_WPS_ER_FAILED < ESP32 station wps fails in enrollee mode -11 SYSTEM_EVENT_STA_WPS_ER_TIMEOUT < ESP32 station wps timeout in enrollee mode -12 SYSTEM_EVENT_STA_WPS_ER_PIN < ESP32 station wps pin code in enrollee mode -13 SYSTEM_EVENT_AP_START < ESP32 soft-AP start -14 SYSTEM_EVENT_AP_STOP < ESP32 soft-AP stop -15 SYSTEM_EVENT_AP_STACONNECTED < a station connected to ESP32 soft-AP -16 SYSTEM_EVENT_AP_STADISCONNECTED < a station disconnected from ESP32 soft-AP -17 SYSTEM_EVENT_AP_STAIPASSIGNED < ESP32 soft-AP assign an IP to a connected station -18 SYSTEM_EVENT_AP_PROBEREQRECVED < Receive probe request packet in soft-AP interface -19 SYSTEM_EVENT_GOT_IP6 < ESP32 station or ap or ethernet interface v6IP addr is preferred -20 SYSTEM_EVENT_ETH_START < ESP32 ethernet start -21 SYSTEM_EVENT_ETH_STOP < ESP32 ethernet stop -22 SYSTEM_EVENT_ETH_CONNECTED < ESP32 ethernet phy link up -23 SYSTEM_EVENT_ETH_DISCONNECTED < ESP32 ethernet phy link down -24 SYSTEM_EVENT_ETH_GOT_IP < ESP32 ethernet got IP from connected AP -25 SYSTEM_EVENT_MAX - - -typedef enum { - ARDUINO_EVENT_WIFI_READY = 0, - ARDUINO_EVENT_WIFI_SCAN_DONE, - ARDUINO_EVENT_WIFI_STA_START, - ARDUINO_EVENT_WIFI_STA_STOP, - ARDUINO_EVENT_WIFI_STA_CONNECTED, - ARDUINO_EVENT_WIFI_STA_DISCONNECTED, - ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE, - ARDUINO_EVENT_WIFI_STA_GOT_IP, - ARDUINO_EVENT_WIFI_STA_GOT_IP6, - ARDUINO_EVENT_WIFI_STA_LOST_IP, - ARDUINO_EVENT_WIFI_AP_START, - ARDUINO_EVENT_WIFI_AP_STOP, - ARDUINO_EVENT_WIFI_AP_STACONNECTED, - ARDUINO_EVENT_WIFI_AP_STADISCONNECTED, - ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED, - ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED, - ARDUINO_EVENT_WIFI_AP_GOT_IP6, - ARDUINO_EVENT_WIFI_FTM_REPORT, - ARDUINO_EVENT_ETH_START, - ARDUINO_EVENT_ETH_STOP, - ARDUINO_EVENT_ETH_CONNECTED, - ARDUINO_EVENT_ETH_DISCONNECTED, - ARDUINO_EVENT_ETH_GOT_IP, - ARDUINO_EVENT_ETH_GOT_IP6, - ARDUINO_EVENT_WPS_ER_SUCCESS, - ARDUINO_EVENT_WPS_ER_FAILED, - ARDUINO_EVENT_WPS_ER_TIMEOUT, - ARDUINO_EVENT_WPS_ER_PIN, - ARDUINO_EVENT_WPS_ER_PBC_OVERLAP, - ARDUINO_EVENT_SC_SCAN_DONE, - ARDUINO_EVENT_SC_FOUND_CHANNEL, - ARDUINO_EVENT_SC_GOT_SSID_PSWD, - ARDUINO_EVENT_SC_SEND_ACK_DONE, - ARDUINO_EVENT_PROV_INIT, - ARDUINO_EVENT_PROV_DEINIT, - ARDUINO_EVENT_PROV_START, - ARDUINO_EVENT_PROV_END, - ARDUINO_EVENT_PROV_CRED_RECV, - ARDUINO_EVENT_PROV_CRED_FAIL, - ARDUINO_EVENT_PROV_CRED_SUCCESS, - ARDUINO_EVENT_MAX -} arduino_event_id_t; - -typedef union { - wifi_event_sta_scan_done_t wifi_scan_done; - wifi_event_sta_authmode_change_t wifi_sta_authmode_change; - wifi_event_sta_connected_t wifi_sta_connected; - wifi_event_sta_disconnected_t wifi_sta_disconnected; - wifi_event_sta_wps_er_pin_t wps_er_pin; - wifi_event_sta_wps_fail_reason_t wps_fail_reason; - wifi_event_ap_probe_req_rx_t wifi_ap_probereqrecved; - wifi_event_ap_staconnected_t wifi_ap_staconnected; - wifi_event_ap_stadisconnected_t wifi_ap_stadisconnected; - wifi_event_ftm_report_t wifi_ftm_report; - ip_event_ap_staipassigned_t wifi_ap_staipassigned; - ip_event_got_ip_t got_ip; - ip_event_got_ip6_t got_ip6; - smartconfig_event_got_ssid_pswd_t sc_got_ssid_pswd; - esp_eth_handle_t eth_connected; - wifi_sta_config_t prov_cred_recv; - wifi_prov_sta_fail_reason_t prov_fail_reason; -} arduino_event_info_t; - -*/ - -#endif \ No newline at end of file diff --git a/lib/WiFiManager/wm_strings_en.h b/lib/WiFiManager/wm_strings_en.h deleted file mode 100644 index 4b53160..0000000 --- a/lib/WiFiManager/wm_strings_en.h +++ /dev/null @@ -1,275 +0,0 @@ -/** - * wm_strings_en.h - * engligh strings for - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - -#ifndef _WM_STRINGS_EN_H_ -#define _WM_STRINGS_EN_H_ - - -#ifndef WIFI_MANAGER_OVERRIDE_STRINGS -// !!! ABOVE WILL NOT WORK if you define in your sketch, must be build flag, if anyone one knows how to order includes to be able to do this it would be neat.. I have seen it done.. - -// strings files must include a consts file! -#include "wm_consts_en.h" // include constants, tokens, routes - -const char WM_LANGUAGE[] PROGMEM = "en-US"; // i18n lang code - -const char HTTP_HEAD_START[] PROGMEM = "" -"" -"" -"" -"" -"{v}"; - -const char HTTP_SCRIPT[] PROGMEM = ""; // @todo add button states, disable on click , show ack , spinner etc - -const char HTTP_HEAD_END[] PROGMEM = "
"; // {c} = _bodyclass -// example of embedded logo, base64 encoded inline, No styling here -// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; -const char HTTP_ROOT_MAIN[] PROGMEM = "

{t}

{v}

"; - -const char * const HTTP_PORTAL_MENU[] PROGMEM = { -"

\n", // MENU_WIFI -"

\n", // MENU_WIFINOSCAN -"

\n", // MENU_INFO -"

\n",//MENU_PARAM -"

\n", // MENU_CLOSE -"

\n",// MENU_RESTART -"

\n", // MENU_EXIT -"

\n", // MENU_ERASE -"

\n",// MENU_UPDATE -"

" // MENU_SEP -}; - -// const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); -const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; -const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons -const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage {h} = hidden showperc pref -const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP -// const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens - -const char HTTP_FORM_START[] PROGMEM = "
"; -const char HTTP_FORM_WIFI[] PROGMEM = "

"; -const char HTTP_FORM_WIFI_END[] PROGMEM = ""; -const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; -const char HTTP_FORM_END[] PROGMEM = "

"; -const char HTTP_FORM_LABEL[] PROGMEM = ""; -const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "

"; -const char HTTP_FORM_PARAM[] PROGMEM = "
\n"; // do not remove newline! - -const char HTTP_SCAN_LINK[] PROGMEM = "
"; -const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; -const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; -const char HTTP_END[] PROGMEM = "
"; -const char HTTP_ERASEBTN[] PROGMEM = "
"; -const char HTTP_UPDATEBTN[] PROGMEM = "
"; -const char HTTP_BACKBTN[] PROGMEM = "

"; - -const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; -const char HTTP_STATUS_OFF[] PROGMEM = "
Not connected to {v}{r}
"; // {c=class} {v=ssid} {r=status_off} -const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication failure"; // STATION_WRONG_PASSWORD, no eps32 -const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL -const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not connect"; // WL_CONNECT_FAILED -const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; -const char HTTP_BR[] PROGMEM = "
"; - -const char HTTP_STYLE[] PROGMEM = ""; - -#ifndef WM_NOHELP -const char HTTP_HELP[] PROGMEM = - "

Available pages


" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/paramParameter page
/infoInformation page
/uOTA Update
/closeClose the captiveportal popup, config portal will remain active
/exitExit Config portal, config portal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot device. Device will not reconnect to a network until new WiFi configuration data is entered.
" - "

Github https://github.com/tzapu/WiFiManager."; -#else -const char HTTP_HELP[] PROGMEM = ""; -#endif - -const char HTTP_UPDATE[] PROGMEM = "Upload new firmware

* May not function inside captive portal, open in browser http://192.168.4.1"; -const char HTTP_UPDATE_FAIL[] PROGMEM = "
Update failed!
Reboot device and try again
"; -const char HTTP_UPDATE_SUCCESS[] PROGMEM = "
Update successful.
Device rebooting now...
"; - -#ifdef WM_JSTEST -const char HTTP_JS[] PROGMEM = -""; -#endif - -// Info html -// @todo remove html elements from progmem, repetetive strings -#ifdef ESP32 - const char HTTP_INFO_esphead[] PROGMEM = "

esp32


"; - const char HTTP_INFO_chiprev[] PROGMEM = "
Chip rev
{1}
"; - const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; - const char HTTP_INFO_aphost[] PROGMEM = "
Access point hostname
{1}
"; - const char HTTP_INFO_psrsize[] PROGMEM = "
PSRAM Size
{1} bytes
"; - const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
"; - const char HTTP_INFO_hall[] PROGMEM = "
Hall
{1}
"; -#else - const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; - const char HTTP_INFO_fchipid[] PROGMEM = "
Flash chip ID
{1}
"; - const char HTTP_INFO_corever[] PROGMEM = "
Core version
{1}
"; - const char HTTP_INFO_bootver[] PROGMEM = "
Boot version
{1}
"; - const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
{1}
"; - const char HTTP_INFO_flashsize[] PROGMEM = "
Real flash size
{1} bytes
"; -#endif - -const char HTTP_INFO_memsmeter[] PROGMEM = "
"; -const char HTTP_INFO_memsketch[] PROGMEM = "
Memory - Sketch size
Used / Total bytes
{1} / {2}"; -const char HTTP_INFO_freeheap[] PROGMEM = "
Memory - Free heap
{1} bytes available
"; -const char HTTP_INFO_wifihead[] PROGMEM = "

WiFi


"; -const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} mins {2} secs
"; -const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; -const char HTTP_INFO_idesize[] PROGMEM = "
Flash size
{1} bytes
"; -const char HTTP_INFO_sdkver[] PROGMEM = "
SDK version
{1}
"; -const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU frequency
{1}MHz
"; -const char HTTP_INFO_apip[] PROGMEM = "
Access point IP
{1}
"; -const char HTTP_INFO_apmac[] PROGMEM = "
Access point MAC
{1}
"; -const char HTTP_INFO_apssid[] PROGMEM = "
Access point SSID
{1}
"; -const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; -const char HTTP_INFO_stassid[] PROGMEM = "
Station SSID
{1}
"; -const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; -const char HTTP_INFO_stagw[] PROGMEM = "
Station gateway
{1}
"; -const char HTTP_INFO_stasub[] PROGMEM = "
Station subnet
{1}
"; -const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; -const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; -const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; -const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; -const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; - -const char HTTP_INFO_aboutver[] PROGMEM = "
WiFiManager
{1}
"; -const char HTTP_INFO_aboutarduino[] PROGMEM = "
Arduino
{1}
"; -const char HTTP_INFO_aboutsdk[] PROGMEM = "
ESP-SDK/IDF
{1}
"; -const char HTTP_INFO_aboutdate[] PROGMEM = "
Build date
{1}
"; - -const char S_brand[] PROGMEM = "WiFiManager"; -const char S_debugPrefix[] PROGMEM = "*wm:"; -const char S_y[] PROGMEM = "Yes"; -const char S_n[] PROGMEM = "No"; -const char S_enable[] PROGMEM = "Enabled"; -const char S_disable[] PROGMEM = "Disabled"; -const char S_GET[] PROGMEM = "GET"; -const char S_POST[] PROGMEM = "POST"; -const char S_NA[] PROGMEM = "Unknown"; -const char S_passph[] PROGMEM = "********"; -const char S_titlewifisaved[] PROGMEM = "Credentials saved"; -const char S_titlewifisettings[] PROGMEM = "Settings saved"; -const char S_titlewifi[] PROGMEM = "Config ESP"; -const char S_titleinfo[] PROGMEM = "Info"; -const char S_titleparam[] PROGMEM = "Setup"; -const char S_titleparamsaved[] PROGMEM = "Setup saved"; -const char S_titleexit[] PROGMEM = "Exit"; -const char S_titlereset[] PROGMEM = "Reset"; -const char S_titleerase[] PROGMEM = "Erase"; -const char S_titleclose[] PROGMEM = "Close"; -const char S_options[] PROGMEM = "options"; -const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; -const char S_staticip[] PROGMEM = "Static IP"; -const char S_staticgw[] PROGMEM = "Static gateway"; -const char S_staticdns[] PROGMEM = "Static DNS"; -const char S_subnet[] PROGMEM = "Subnet"; -const char S_exiting[] PROGMEM = "Exiting"; -const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; -const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; -const char S_error[] PROGMEM = "An error occured"; -const char S_notfound[] PROGMEM = "File not found\n\n"; -const char S_uri[] PROGMEM = "URI: "; -const char S_method[] PROGMEM = "\nMethod: "; -const char S_args[] PROGMEM = "\nArguments: "; -const char S_parampre[] PROGMEM = "param_"; - -// debug strings -const char D_HR[] PROGMEM = "--------------------"; - - -// softap ssid default prefix -#ifdef ESP8266 - const char S_ssidpre[] PROGMEM = "ESP"; -#elif defined(ESP32) - const char S_ssidpre[] PROGMEM = "ESP32"; -#else - const char S_ssidpre[] PROGMEM = "WM"; -#endif - -// END WIFI_MANAGER_OVERRIDE_STRINGS -#endif - -#endif diff --git a/lib/WiFiManager/wm_strings_es.h b/lib/WiFiManager/wm_strings_es.h deleted file mode 100644 index 781d055..0000000 --- a/lib/WiFiManager/wm_strings_es.h +++ /dev/null @@ -1,282 +0,0 @@ -/** - * SAMPLE SAMPLE SAMPLE - * - * wm_strings_es.h - * spanish strings for - * WiFiManager, a library for the ESPX/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - -#ifndef _WM_STRINGS_EN_H_ -#define _WM_STRINGS_EN_H_ - - -/** - * ADD TO BUILD FLAGS - * -DWM_STRINGS_FILE="\"wm_strings_es.h\"" - */ - -#ifndef WIFI_MANAGER_OVERRIDE_STRINGS -// !!! ABOVE WILL NOT WORK if you define in your sketch, must be build flag, if anyone one knows how to order includes to be able to do this it would be neat.. I have seen it done.. - -// strings files must include a consts file! -// Copy and change to custom locale tokens if necessary, but strings should be good enough -#include "wm_consts_en.h" // include constants, tokens, routes - -const char WM_LANGUAGE[] PROGMEM = "es-ES"; // i18n lang code - -const char HTTP_HEAD_START[] PROGMEM = "" -"" -"" -"" -"" -"{v}"; - -const char HTTP_SCRIPT[] PROGMEM = ""; // @todo add button states, disable on click , show ack , spinner etc - -const char HTTP_HEAD_END[] PROGMEM = "
"; // {c} = _bodyclass -// example of embedded logo, base64 encoded inline, No styling here -// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; -const char HTTP_ROOT_MAIN[] PROGMEM = "

{t}

{v}

"; - -const char * const HTTP_PORTAL_MENU[] PROGMEM = { -"

\n", // MENU_WIFI -"

\n", // MENU_WIFINOSCAN -"

\n", // MENU_INFO -"

\n",//MENU_PARAM -"

\n", // MENU_CLOSE -"

\n",// MENU_RESTART -"

\n", // MENU_EXIT -"

\n", // MENU_ERASE -"

\n",// MENU_UPDATE -"

" // MENU_SEP -}; - -// const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); -const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; -const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons -const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage {h} = hidden showperc pref -const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP -// const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens - -const char HTTP_FORM_START[] PROGMEM = "
"; -const char HTTP_FORM_WIFI[] PROGMEM = "
Mostrar contraseña"; -const char HTTP_FORM_WIFI_END[] PROGMEM = ""; -const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; -const char HTTP_FORM_END[] PROGMEM = "

"; -const char HTTP_FORM_LABEL[] PROGMEM = ""; -const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "

"; -const char HTTP_FORM_PARAM[] PROGMEM = "
\n"; // do not remove newline! - -const char HTTP_SCAN_LINK[] PROGMEM = "
"; -const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; -const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; -const char HTTP_END[] PROGMEM = "
"; -const char HTTP_ERASEBTN[] PROGMEM = "
"; -const char HTTP_UPDATEBTN[] PROGMEM = "
"; -const char HTTP_BACKBTN[] PROGMEM = "

"; - -const char HTTP_STATUS_ON[] PROGMEM = "
Conectado a {v}
con IP {i}
"; -const char HTTP_STATUS_OFF[] PROGMEM = "
No conectado a {v}{r}
"; // {c=class} {v=ssid} {r=status_off} -const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 -const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
No Encontrado"; // WL_NO_SSID_AVAIL -const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
No se pudo conectar"; // WL_CONNECT_FAILED -const char HTTP_STATUS_NONE[] PROGMEM = "
Sin AP establecido
"; -const char HTTP_BR[] PROGMEM = "
"; - -const char HTTP_STYLE[] PROGMEM = ""; - -#ifndef WM_NOHELP -const char HTTP_HELP[] PROGMEM = - "

Available Pages


" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/paramParameter page
/infoInformation page
/uOTA Update
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
" - "

Github https://github.com/tzapu/WiFiManager."; -#else -const char HTTP_HELP[] PROGMEM = ""; -#endif - -const char HTTP_UPDATE[] PROGMEM = "Upload New Firmware

* May not function inside captive portal, Open in browser http://192.168.4.1"; -const char HTTP_UPDATE_FAIL[] PROGMEM = "
Update Failed!
Reboot device and try again
"; -const char HTTP_UPDATE_SUCCESS[] PROGMEM = "
Update Successful.
Device Rebooting now...
"; - -#ifdef WM_JSTEST -const char HTTP_JS[] PROGMEM = -""; -#endif - -// Info html -// @todo remove html elements from progmem, repetetive strings -#ifdef ESP32 - const char HTTP_INFO_esphead[] PROGMEM = "

esp32


"; - const char HTTP_INFO_chiprev[] PROGMEM = "
Chip Rev
{1}
"; - const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; - const char HTTP_INFO_aphost[] PROGMEM = "
Access Point Hostname
{1}
"; - const char HTTP_INFO_psrsize[] PROGMEM = "
PSRAM Size
{1} bytes
"; - const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
Hall
{3}
"; -#else - const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; - const char HTTP_INFO_fchipid[] PROGMEM = "
Flash Chip ID
{1}
"; - const char HTTP_INFO_corever[] PROGMEM = "
Core Version
{1}
"; - const char HTTP_INFO_bootver[] PROGMEM = "
Boot Version
{1}
"; - const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
{1}
"; - const char HTTP_INFO_flashsize[] PROGMEM = "
Real Flash Size
{1} bytes
"; -#endif - -const char HTTP_INFO_memsmeter[] PROGMEM = "
"; -const char HTTP_INFO_memsketch[] PROGMEM = "
Memory - Sketch Size
Used / Total bytes
{1} / {2}"; -const char HTTP_INFO_freeheap[] PROGMEM = "
Memory - Free Heap
{1} bytes available
"; -const char HTTP_INFO_wifihead[] PROGMEM = "

WiFi


"; -const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} Mins {2} Secs
"; -const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; -const char HTTP_INFO_idesize[] PROGMEM = "
Flash Size
{1} bytes
"; -const char HTTP_INFO_sdkver[] PROGMEM = "
SDK Version
{1}
"; -const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU Frequency
{1}MHz
"; -const char HTTP_INFO_apip[] PROGMEM = "
Access Point IP
{1}
"; -const char HTTP_INFO_apmac[] PROGMEM = "
Access Point MAC
{1}
"; -const char HTTP_INFO_apssid[] PROGMEM = "
Access Point SSID
{1}
"; -const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; -const char HTTP_INFO_stassid[] PROGMEM = "
Station SSID
{1}
"; -const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; -const char HTTP_INFO_stagw[] PROGMEM = "
Station Gateway
{1}
"; -const char HTTP_INFO_stasub[] PROGMEM = "
Station Subnet
{1}
"; -const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; -const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; -const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; -const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; -const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; - -const char HTTP_INFO_aboutver[] PROGMEM = "
WiFiManager
{1}
"; -const char HTTP_INFO_aboutarduino[] PROGMEM = "
Arduino
{1}
"; -const char HTTP_INFO_aboutsdk[] PROGMEM = "
ESP-SDK/IDF
{1}
"; -const char HTTP_INFO_aboutdate[] PROGMEM = "
Build Date
{1}
"; - -const char S_brand[] PROGMEM = "WiFiManager"; -const char S_debugPrefix[] PROGMEM = "*wm:"; -const char S_y[] PROGMEM = "Yes"; -const char S_n[] PROGMEM = "No"; -const char S_enable[] PROGMEM = "Enabled"; -const char S_disable[] PROGMEM = "Disabled"; -const char S_GET[] PROGMEM = "GET"; -const char S_POST[] PROGMEM = "POST"; -const char S_NA[] PROGMEM = "Unknown"; -const char S_passph[] PROGMEM = "********"; -const char S_titlewifisaved[] PROGMEM = "Credentials Saved"; -const char S_titlewifisettings[] PROGMEM = "Settings Saved"; -const char S_titlewifi[] PROGMEM = "Config ESP"; -const char S_titleinfo[] PROGMEM = "Info"; -const char S_titleparam[] PROGMEM = "Setup"; -const char S_titleparamsaved[] PROGMEM = "Setup Saved"; -const char S_titleexit[] PROGMEM = "Exit"; -const char S_titlereset[] PROGMEM = "Reset"; -const char S_titleerase[] PROGMEM = "Erase"; -const char S_titleclose[] PROGMEM = "Close"; -const char S_options[] PROGMEM = "options"; -const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; -const char S_staticip[] PROGMEM = "Static IP"; -const char S_staticgw[] PROGMEM = "Static Gateway"; -const char S_staticdns[] PROGMEM = "Static DNS"; -const char S_subnet[] PROGMEM = "Subnet"; -const char S_exiting[] PROGMEM = "Exiting"; -const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; -const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; -const char S_error[] PROGMEM = "An Error Occured"; -const char S_notfound[] PROGMEM = "File Not Found\n\n"; -const char S_uri[] PROGMEM = "URI: "; -const char S_method[] PROGMEM = "\nMethod: "; -const char S_args[] PROGMEM = "\nArguments: "; -const char S_parampre[] PROGMEM = "param_"; - -// debug strings -const char D_HR[] PROGMEM = "--------------------"; - - -// softap ssid default prefix -#ifdef ESP8266 - const char S_ssidpre[] PROGMEM = "ESP"; -#elif defined(ESP32) - const char S_ssidpre[] PROGMEM = "ESP32"; -#else - const char S_ssidpre[] PROGMEM = "WM"; -#endif - -// END WIFI_MANAGER_OVERRIDE_STRINGS -#endif - -#endif diff --git a/lib/espMqttClient/CMakeLists.txt b/lib/espMqttClient/CMakeLists.txt deleted file mode 100644 index 3702227..0000000 --- a/lib/espMqttClient/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -set(COMPONENT_SRCDIRS - "src" "src/Packets" "src/Transport" -) - -set(COMPONENT_ADD_INCLUDEDIRS - "src" "src/Packets" "src/Transport" -) - -set(COMPONENT_REQUIRES - "arduino-esp32" - "AsyncTCP" -) - -register_component() - -target_compile_definitions(${COMPONENT_TARGET} PUBLIC -DESP32) -target_compile_options(${COMPONENT_TARGET} PRIVATE -fno-rtti) diff --git a/lib/espMqttClient/LICENSE b/lib/espMqttClient/LICENSE deleted file mode 100644 index 1cc5546..0000000 --- a/lib/espMqttClient/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 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/README.md b/lib/espMqttClient/README.md deleted file mode 100644 index 7b0bfdd..0000000 --- a/lib/espMqttClient/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# espMqttClient - -MQTT client library for the Espressif devices ESP8266 and ESP32 on the Arduino framework. -Aims to be a non-blocking, fully compliant MQTT 3.1.1 client. - -![platformio](https://github.com/bertmelis/espMqttClient/actions/workflows/build_platformio.yml/badge.svg) -![cpplint](https://github.com/bertmelis/espMqttClient/actions/workflows/cpplint.yml/badge.svg) -![cppcheck](https://github.com/bertmelis/espMqttClient/actions/workflows/cppcheck.yml/badge.svg) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/bertmelis/library/espMqttClient.svg)](https://registry.platformio.org/libraries/bertmelis/espMqttClient) - -# Features - -- MQTT 3.1.1 compliant library -- Sending and receiving at all QoS levels -- 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/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 `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/). - -## Limitations - -### MQTT 3.1.1 Compliancy - -Outgoing messages and session data are not stored in non-volatile memory. Any events like loss of power or sudden resets result in loss of data. Despite this limitation, one could still consider this library as fully complaint based on the non normative remark in point 4.1.1 of the specification. - -### Non-blocking - -This library aims to be fully non-blocking. It is however limited by the underlying `WiFiClient` library which is part of the Arduino framework and has a blocking `connect` method. This is not an issue on ESP32 because the call is offloaded to a separate task. On ESP8266 however, connecting will block until succesful or until the connection timeouts. - -If you need a fully asynchronous MQTT client, you can use `espMqttClientAsync` which uses AsyncTCP/ESPAsyncTCP under the hood. These underlying libraries do not support TLS (anymore). I will not provide support TLS for the async client. - -# Bugs and feature requests - -Please use Github's facilities to get in touch. - -# About this library - -This client wouldn't exist without [Async-mqtt-client](https://github.com/marvinroger/async-mqtt-client). It has been my go-to MQTT client for many years. It was fast, reliable and had features that were non-existing in alternative libraries. However, the underlying async TCP libraries are lacking updates, especially updates related to secure connections. Adapting this library to use up-to-date TCP clients would not be trivial. I eventually decided to write my own MQTT library, from scratch. - -The result is an almost non-blocking library with no external dependencies. The library is almost a drop-in replacement for the async-mqtt-client except a few parameter type changes (eg. `uint8_t*` instead of `char*` for payloads). - -# License - -This library is released under the MIT Licence. A copy is included in the repo. -Parts of this library, most notably the API, are based on [Async MQTT client for ESP8266 and ESP32](https://github.com/marvinroger/async-mqtt-client). diff --git a/lib/espMqttClient/component.mk b/lib/espMqttClient/component.mk deleted file mode 100644 index bb5bb16..0000000 --- a/lib/espMqttClient/component.mk +++ /dev/null @@ -1,3 +0,0 @@ -COMPONENT_ADD_INCLUDEDIRS := src -COMPONENT_SRCDIRS := src -CXXFLAGS += -fno-rtti diff --git a/lib/espMqttClient/docs/_config.yml b/lib/espMqttClient/docs/_config.yml deleted file mode 100644 index 6975b20..0000000 --- a/lib/espMqttClient/docs/_config.yml +++ /dev/null @@ -1,6 +0,0 @@ -theme: jekyll-theme-cayman -title: espMqttClient -description: | - MQTT client library for the Espressif devices ESP8266 and ESP32 on the Arduino framework. - Aims to be a non-blocking fully compliant MQTT 3.1.1 client. -show_downloads: false diff --git a/lib/espMqttClient/docs/index.md b/lib/espMqttClient/docs/index.md deleted file mode 100644 index 4385ee9..0000000 --- a/lib/espMqttClient/docs/index.md +++ /dev/null @@ -1,587 +0,0 @@ -![platformio](https://github.com/bertmelis/espMqttClient/actions/workflows/build_platformio.yml/badge.svg) -![cpplint](https://github.com/bertmelis/espMqttClient/actions/workflows/cpplint.yml/badge.svg) -![cppcheck](https://github.com/bertmelis/espMqttClient/actions/workflows/cppcheck.yml/badge.svg) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/bertmelis/library/espMqttClient.svg)](https://registry.platformio.org/libraries/bertmelis/espMqttClient) - -# Features - -- MQTT 3.1.1 compliant library -- Sending and receiving at all QoS levels -- 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/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) -2. [API Reference](#api-reference) -3. [Compile-time configuration](#compile-time-configuration) -4. [Code samples](#code-samples) - -# Runtime behaviour - -A normal operation cycle of an MQTT client goes like this: - -1. setup the client -2. connect to the broker -3. subscribe/publish/receive -4. disconnect/reconnect when disconnected -5. Cleanly disconnect - -### Setup - -Setting up the client means to tell which host and port to connect to, possible credentials to use and so on. espMqttClient has a set of methods to configure the client. Setup is generally done in the `setup()` function of the Arduino framework. -One important thing to remember is that there are a number of settings that are not stored inside the library: `username`, `password`, `willTopic`, `willPayload`, `clientId` and `host`. Make sure these variables stay available during the lifetime of the `espMqttClient`. - -For TLS secured connections, the relevant methods from `WiFiClientSecure` have been made available to setup the TLS mechanisms. - -### Connecting - -After setting up the client, you are ready to connect. A simple call to `connect()` does the job. If you set an `OnConnectCallback`, you will be notified when the connection has been made. On failure, `OnDisconnectCallback` will be called. Although good code structure can avoid this, you can call `connect()` multiple times. - -### Subscribing, publishing and receiving - -Once connected, you can subscribe, publish and receive. The methods to do this return the packetId of the generated packet or `1` for packets without packetId. In case of an error, the method returns `0`. When the client is not connected, you cannot subscribe, unsubscribe or publish (configurable, see [EMC_ALLOW_NOT_CONNECTED_PUBLISH](#EMC_ALLOW_NOT_CONNECTED_PUBLISH)). - -Receiving packets is done via the `onMessage`-callback. This callback gives you the topic, properties (qos, dup, retain, packetId) and payload. For the payload, you get a pointer to the data, the index, length and total length. On long payloads it is normal that you get multiple callbacks for the same packet. This way, you can receive payloads longer than what could fit in the microcontroller's memory. - - > Beware that MQTT payloads are binary. MQTT payloads are **not** c-strings unless explicitely constructed like that. You therefore can **not** print the payload to your Serial monitor without supporting code. - -### Disconnecting - -You can disconnect from the broker by calling `disconnect()`. If you do not force-disconnect, the client will first send the remaining messages that are in the queue and disconnect afterwards. During this period however, no new incoming PUBLISH messages will be processed. - -# API Reference - -```cpp -espMqttClient() -espMqttClientSecure() -espMqttClientAsync() -``` - -Instantiate a new espMqttClient or espMqttSecure object. -On ESP32, three optional parameters are available: `espMqttClient(bool internalTask = true, uint8_t priority = 1, uint8_t core = 1)`. By default, espMqttclient creates its own task to manage TCP. By setting `internalTask` to false, no task will be created and you will be responsible yourself to call `espMqttClient.loop()`. `priority` changes the priority of the MQTT client task and the core on which it runs (higher priority = more cpu-time). - -For the asynchronous version, use `espMqttClientAsync`. - -### Configuration - -```cpp -espMqttClient& setKeepAlive(uint16_t keepAlive) -``` - -Set the keep alive. Defaults to 15 seconds. - -* **`keepAlive`**: Keep alive in seconds - -```cpp -espMqttClient& setClientId(const char* clientId) -``` - -Set the client ID. Defaults to `esp8266123456` or `esp32123456` where `123456` is the chip ID. -The library only stores a pointer to the client ID. Make sure the variable pointed to stays available throughout the lifetime of espMqttClient. - -- **`clientId`**: Client ID, expects a null-terminated char array (c-string) - -```cpp -espMqttClient& setCleanSession(bool cleanSession) -``` - -Set the CleanSession flag. Defaults to `true`. - -- **`cleanSession`**: clean session wanted or not - -```cpp -espMqttClient& setCredentials(const char* username, const char* password) -``` - -Set the username/password. Defaults to non-auth. -The library only stores a pointer to the username and password. Make sure the variable to pointed stays available throughout the lifetime of espMqttClient. - -- **`username`**: Username, expects a null-terminated char array (c-string) -- **`password`**: Password, expects a null-terminated char array (c-string) - -```cpp -espMqttClient& setWill(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length) -``` - -Set the Last Will. Defaults to none. -The library only stores a pointer to the topic and payload. Make sure the variable pointed to stays available throughout the lifetime of espMqttClient. - -- **`topic`**: Topic of the LWT, expects a null-terminated char array (c-string) -- **`qos`**: QoS of the LWT -- **`retain`**: Retain flag of the LWT -- **`payload`**: Payload of the LWT. -- **`length`**: Payload length - -```cpp -espMqttClient& setWill(const char* topic, uint8_t qos, bool retain, const char* payload) -``` - -Set the Last Will. Defaults to none. -The library only stores a pointer to the topic and payload. Make sure the variable pointed to stays available throughout the lifetime of espMqttClient. - -- **`topic`**: Topic of the LWT, expects a null-terminated char array (c-string) -- **`qos`**: QoS of the LWT -- **`retain`**: Retain flag of the LWT -- **`payload`**: Payload of the LWT, expects a null-terminated char array (c-string). Its lenght will be calculated using `strlen(payload)` - -```cpp -espMqttClient& setServer(IPAddress ip, uint16_t port) -``` - -Set the server. Mind that when using `espMqttClientSecure` with a certificate, the hostname will be chacked against the certificate. Often IP-addresses are not valid and the connection will fail. - -- **`ip`**: IP of the server -- **`port`**: Port of the server - -```cpp -espMqttClient& setServer(const char* host, uint16_t port) -``` - -Set the server. - -- **`host`**: Host of the server, expects a null-terminated char array (c-string) -- **`port`**: Port of the server - -```cpp -espMqttClient& setTimeout(uint16_t timeout) -``` - -Set the timeout for packets that need acknowledgement. Defaults to 10 seconds. -When no acknowledgement has been received from the broker after sending a packet, the client will retransmit **all** the packets in the queue. - -* **`timeout`**: Timeout in seconds - -#### Options for TLS connections - -All common options from WiFiClientSecure to setup an encrypted connection are made available. These include: - -- `espMqttClientSecure& setInsecure()` -- `espMqttClientSecure& setCACert(const char* rootCA)` (ESP32 only) -- `espMqttClientSecure& setCertificate(const char* clientCa)` (ESP32 only) -- `espMqttClientSecure& setPrivateKey(const char* privateKey)` (ESP32 only) -- `espMqttClientSecure& setPreSharedKey(const char* pskIdent, const char* psKey)` (ESP32 only) -- `espMqttClientSecure& setFingerprint(const uint8_t fingerprint[20])` (ESP8266 only) -- `espMqttClientSecure& setTrustAnchors(const X509List *ta)` (ESP8266 only) -- `espMqttClientSecure& setClientRSACert(const X509List *cert, const PrivateKey *sk)` (ESP8266 only) -- `espMqttClientSecure& setClientECCert(const X509List *cert, const PrivateKey *sk, unsigned allowed_usages, unsigned cert_issuer_key_type)` (ESP8266 only) -- `espMqttClientSecure& setCertStore(CertStoreBase *certStore)` (ESP8266 only) - -For documenation, please visit [ESP8266's documentation](https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure) or [ESP32's documentation](https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFiClientSecure). - -### Events handlers - -```cpp -espMqttClient& onConnect(espMqttClientTypes::OnConnectCallback callback) -``` - -Add a connect event handler. Function signature: `void(bool sessionPresent)` - -- **`callback`**: Function to call - -```cpp -espMqttClient& onDisconnect(espMqttClientTypes::OnDisconnectCallback callback) -``` - -Add a disconnect event handler. Function signature: `void(espMqttClientTypes::DisconnectReason reason)` - -- **`callback`**: Function to call - -```cpp -espMqttClient& onSubscribe(espMqttClientTypes::OnSubscribeCallback callback) -``` - -Add a subscribe acknowledged event handler. Function signature: `void(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* returncodes, size_t len)` - -- **`callback`**: Function to call - -```cpp -espMqttClient& onUnsubscribe(espMqttClientTypes::OnUnsubscribeCallback callback) -``` - -Add an unsubscribe acknowledged event handler. Function signature: `void(uint16_t packetId)` - -- **`callback`**: Function to call - -```cpp -espMqttClient& onMessage(espMqttClientTypes::OnMessageCallback callback) -``` - -Add a publish received event handler. Function signature: `void(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total)` - -- **`callback`**: Function to call - -```cpp -espMqttClient& onPublish(espMqttClientTypes::OnPublishCallback callback) -``` - -Add a publish acknowledged event handler. Function signature: `void(uint16_t packetId)` - -- **`callback`**: Function to call - -### Operational functions - -```cpp -bool connected() -``` - -Returns `true` if the client is currently fully connected to the broker. During connecting or disconnecting, it will return `false`. - -```cpp -bool disconnected() -``` - -Returns `true` if the client is currently disconnected from the broker. During disconnecting or connecting, it will return `false`. - -```cpp -bool connect() -``` - -Start the connect procedure. Returns `true` if successful. A positive return value doesn not mean the client is already connected. - -```cpp -bool disconnect(bool force = false) -``` - -Start the disconnect procedure, return `true` if successful. A positive return value doesn not mean the client is already disconnected. -When disconnecting with `force` false, the client first tries to handle all the outgoing messages in the queue and disconnect cleanly afterwards. During this time, no incoming PUBLISH messages are handled. - -- **`force`**: Whether to force the disconnection. Defaults to `false` (clean disconnection). - -```cpp -uint16_t subscribe(const char* topic, uint8_t qos) -``` - -Subscribe to the given topic at the given QoS. Return the packet ID or 0 if failed. - -- **`topic`**: Topic, expects a null-terminated char array (c-string) -- **`qos`**: QoS - -It is also possible to subscribe to multiple topics at once. Just add the topic/qos pairs to the parameters: - -```cpp -uint16_t packetId = yourclient.subscribe(topic1, qos1, topic2, qos2, topic3, qos3); // add as many topics as you like* -``` - -```cpp -uint16_t unsubscribe(const char* topic) -``` - -Unsubscribe from the given topic. Return the packet ID or 0 if failed. - -- **`topic`**: Topic, expects a null-terminated char array (c-string) - -It is also possible to unsubscribe to multiple topics at once. Just add the topics to the parameters: - -```cpp -uint16_t packetId = yourclient.unsubscribe(topic1, topic2, topic3); // add as many topics as you like* -``` - -```cpp -uint16_t publish(const char* topic, uint8_t qos, bool retain, const uint8* payload, size_t length) -``` - -Publish a packet. Return the packet ID (or 1 if QoS 0) or 0 if failed. The topic and payload will be buffered by the library. - -- **`topic`**: Topic, expects a null-terminated char array (c-string) -- **`qos`**: QoS -- **`retain`**: Retain flag -- **`payload`**: Payload -- **`length`**: Payload length - -```cpp -uint16_t publish(const char* topic, uint8_t qos, bool retain, const char* payload) -``` - -Publish a packet. Return the packet ID (or 1 if QoS 0) or 0 if failed. The topic and payload will be buffered by the library. - -- **`topic`**: Topic, expects a null-terminated char array (c-string) -- **`qos`**: QoS -- **`retain`**: Retain flag -- **`payload`**: Payload, expects a null-terminated char array (c-string). Its lenght will be calculated using `strlen(payload)` - -```cpp -uint16_t publish(const char* topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length) -``` - -Publish a packet with a callback for payload handling. Return the packet ID (or 1 if QoS 0) or 0 if failed. The topic will be buffered by the library. - -- **`topic`**: Topic, expects a null-terminated char array (c-string) -- **`qos`**: QoS -- **`retain`**: Retain flag -- **`callback`**: callback to fetch the payload. - -The callback has the following signature: `size_t callback(uint8_t* data, size_t maxSize, size_t index)`. When the library needs payload data, the callback will be invoked. It is the callback's job to write data indo `data` with a maximum of `maxSize` bytes, according the `index` and return the amount of bytes written. - -```cpp -void clearQueue(bool deleteSessionData = false) -``` - -Clears all queued messages. -Keep in mind that this may also delete any session data and therefore is not MQTT compliant. - -- **`deleteSessionData`**: When true, delete all outgoing messages. Not MQTT compliant! - -```cpp -void loop() -``` - -This is the worker function of the MQTT client. For ESP8266 you must call this function in the Arduino loop. For ESP32 you have to call this function yourself **only if you have disabled the internal task** (see the constructors). - -```cpp -const char* getClientId() const -``` - -Retuns the client ID. - -```cpp -size_t queueSize(); -``` - -Returns the amount of elements, regardless of type, in the queue. - -# Compile time configuration - -A number of constants which influence the behaviour of the client can be set at compile time. You can set these options in the `Config.h` file or pass the values as compiler flags. Because these options are compile-time constants, they are used for all instances of `espMqttClient` you create in your program. - -### EMC_TX_TIMEOUT 10000 - -Timeout in milliseconds before a (qos > 0) message will be retransmitted. - -### EMC_RX_BUFFER_SIZE 1440 - -The client copies incoming data into a buffer before parsing. This sets the buffer size. - -### EMC_TX_BUFFER_SIZE 1440 - -When publishing using the callback, the client fetches data in chunks of EMC_TX_BUFFER_SIZE size. This is not necessarily the same as the actual outging TCP packets. - -### EMC_MAX_TOPIC_LENGTH 128 - -For **incoming** messages, a maximum topic length is set. Topics longer than this will be truncated. - -### EMC_PAYLOAD_BUFFER_SIZE 32 - -Set the incoming payload buffer size for SUBACK messages. When subscribing to multiple topics at once, the acknowledgement contains all the return codes in its payload. The detault of 32 means you can theoretically subscribe to 32 topics at once. - -### EMC_MIN_FREE_MEMORY 4096 - -The client keeps all outgoing packets in a queue which stores its data in heap memory. With this option, you can set the minimum available (contiguous) heap memory that needs to be available for adding a message to the queue. - -### EMC_ESP8266_MULTITHREADING 0 - -Set this to 1 if you use the async version on ESP8266. For the regular client this setting can be kept disabled because the ESP8266 doesn't use multithreading and is only single-core. - -### EMC_ALLOW_NOT_CONNECTED_PUBLISH 1 - -By default, you can publish when the client is not connected. If you don't want this, set this to 0. -Regardless of this setting, after you called `disconnect()`, no messages can be published until fully disconnected. - -### EMC_WAIT_FOR_CONNACK 1 - -espMqttClient waits for the CONNACK (connection acknowledge) packet before starting to send other packets. -The MQTT specification allows to start sending before the broker acknowledges the connection but some brokers -don't allow this (AWS for example doesn't). - -### EMC_CLIENTID_LENGTH 18 + 1 - -The (maximum) length of the client ID. (Keep in mind that this is a c-string. You need to have 1 position available for the null-termination.) - -### EMC_TASK_STACK_SIZE 5120 - -Only used on ESP32. Sets the stack size (in words) of the MQTT client worker task. - -### EMC_MULTIPLE_CALLBACKS - -This macro is by default not enabled so you can add a single callbacks to an event. Assigning a second will overwrite the existing callback. When enabling multiple callbacks, multiple callbacks (with uint32_t id) can be assigned. Removing is done by referencing the id. - -### EMC_USE_WATCHDOG 0 - -(ESP32 only) - -**Experimental** - -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. - -ESP8266: - -- Enable logging for Arduino [see docs](https://arduino-esp8266.readthedocs.io/en/latest/Troubleshooting/debugging.html) -- Pass the `DEBUG_ESP_MQTT_CLIENT` flag to the compiler - -ESP32 - -- Enable logging for Arduino [see docs](https://docs.espressif.com/projects/arduino-esp32/en/latest/guides/tools_menu.html?#core-debug-level) - -# Code samples - -A number of examples are in the [examples](/examples) directory. These include basic operation on ESP8266 and ESP32. Please examine these to understand the basic operation of the MQTT client. - -Below are examples on specific points for working with this library. - -### Printing payloads - -MQTT 3.1.1 defines no special format for the payload so it is treated as binary. If you want to print a payload to the Arduino serial console, you have to make sure that the payload is null-terminated (c-string). - -```cpp -// option one: print the payload char by char -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - Serial.println("Publish received:"); - Serial.printf(" topic: %s\n payload:", topic); - const char* p = reinterpret_cast(payload); - for (size_t i = 0; i < len; ++i) { - Serial.print(p[i]); - } - Serial.print("\n"); -} -``` - -```cpp -// option two: copy the payload into a c-string -// you cannot just do payload[len] = 0 because you do not own this memory location! -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - Serial.println("Publish received:"); - Serial.printf(" topic: %s\n payload:", topic); - char* strval = new char[len + 1]; - memcpy(strval, payload, len); - strval[len] = "\0"; - Serial.println(strval); - delete[] strval; -} -``` - -### Assembling chunked messages - -The `onMessage`-callback is called as data comes in. So if the data comes in partially, the callback will be called on every receipt of a chunk, with the proper `index`, (chunk)`size` and `total` set. With little code, you can reassemble chunked messages yourself. - -```cpp -const size_t maxPayloadSize = 8192; -uint8_t* payloadbuffer = nullptr; -size_t payloadbufferSize = 0; -size_t payloadbufferIndex = 0; - -void onOversizedMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - // handle oversized messages -} - -void onCompleteMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - // handle assembled messages -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - // payload is bigger then max: return chunked - if (total > maxPayloadSize) { - onOversizedMqttMessage(properties, topic, payload, len, index, total); - return; - } - - // start new packet, increase buffer size if neccesary - if (index == 0) { - if (total > payloadbufferSize) { - delete[] payloadbuffer; - payloadbufferSize = total; - payloadbuffer = new (std::nothrow) uint8_t[payloadbufferSize]; - if (!payloadbuffer) { - // no buffer could be created. you might want to log this somewhere - return; - } - } - payloadbufferIndex = 0; - } - - // add data and dispatch when done - if (payloadBuffer) { - memcpy(&payloadbuffer[payloadbufferIndex], payload, len); - payloadbufferIndex += len; - if (payloadbufferIndex == total) { - // message is complete here - onCompleteMqttMessage(properties, topic, payloadBuffer, total, 0, total); - // optionally: - delete[] payloadBuffer; - payloadBuffer = nullptr; - payloadbufferSize = 0; - } - } -} - -// attach callback to MQTT client -mqttClient.onMessage(onMqttMessage); -``` - -### onMessage callbacks per topic - -espMqttClient allows only one callback for incoming messages. You might want to have specific ones per topic. This example shows one way on how to achieve this. - -Limitations of this code sample: only the first match is served and no wildcard topics allowed. - -```cpp -#include -#include - -// definitions of the std::map where we will store the topic/callback combinations -struct MatchTopic { - bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; -std::map topicCallbacks; - -// callbacks per topic -void onTopic1(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - // received a packet on topic 1 -} -void onTopic2(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - // received a packet on topic 2 -} - -// general callback to dispatch to specific handlers -void onMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - auto it = topicCallbacks.find(topic); - if (it != topicCallbacks.end()) { - // if found, run specific callback - (it->second)(properties, topic, payload, len, index, total); - } else { - // or handle it here - } -} - -// in your Arduino setup() function: -topicCallbacks.emplace("base/topic1", onTopic1); -topicCallbacks.emplace("base/topic2", onTopic2); - -mqttClient.onMessage(onMessage); -``` diff --git a/lib/espMqttClient/docs/mqtt-v3.1.1.pdf b/lib/espMqttClient/docs/mqtt-v3.1.1.pdf deleted file mode 100644 index e4095f1..0000000 Binary files a/lib/espMqttClient/docs/mqtt-v3.1.1.pdf and /dev/null differ diff --git a/lib/espMqttClient/examples/largepayload-esp8266/largepayload-esp8266.ino b/lib/espMqttClient/examples/largepayload-esp8266/largepayload-esp8266.ino deleted file mode 100644 index f64c9e7..0000000 --- a/lib/espMqttClient/examples/largepayload-esp8266/largepayload-esp8266.ino +++ /dev/null @@ -1,106 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -WiFiEventHandler wifiConnectHandler; -WiFiEventHandler wifiDisconnectHandler; -espMqttClient mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -size_t fetchPayload(uint8_t* dest, size_t len, size_t index) { - Serial.printf("filling buffer at index %zu\n", index); - // fill the buffer with random bytes - // but maybe don't fill the entire buffer - size_t i = 0; - for (; i < len; ++i) { - dest[i] = random(0xFF); - if (dest[i] > 0xFC) { - ++i; // extra increment to compensate 'break' - break; - } - } - return i; -} - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void onWiFiConnect(const WiFiEventStationModeGotIP& event) { - (void) event; - Serial.println("Connected to Wi-Fi."); - connectToMqtt(); -} - -void onWiFiDisconnect(const WiFiEventStationModeDisconnected& event) { - (void) event; - Serial.println("Disconnected from Wi-Fi."); -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - mqttClient.publish("topic/largepayload", 1, false, fetchPayload, 6000); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.setAutoConnect(false); - WiFi.setAutoReconnect(true); - wifiConnectHandler = WiFi.onStationModeGotIP(onWiFiConnect); - wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - mqttClient.loop(); - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} \ No newline at end of file diff --git a/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino b/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino deleted file mode 100644 index 867d883..0000000 --- a/lib/espMqttClient/examples/notask-esp32/notask-esp32.ino +++ /dev/null @@ -1,148 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -espMqttClient mqttClient(espMqttClientTypes::UseInternalTask::NO); -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void WiFiEvent(WiFiEvent_t event) { - Serial.printf("[WiFi-event] event: %d\n", event); - switch(event) { - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - connectToMqtt(); - break; - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - Serial.println("WiFi lost connection"); - break; - default: - break; - } -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("foo/bar", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("foo/bar", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("foo/bar", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("foo/bar", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.persistent(false); - WiFi.setAutoReconnect(true); - WiFi.onEvent(WiFiEvent); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } - - // We used to option not to use the internal task - // so we need to call the loop-method ourselves. - // During connecting it may block. - // Creating a separate task yourself is obviously - // also a possibility. - mqttClient.loop(); -} diff --git a/lib/espMqttClient/examples/ota-esp8266/ota-esp8266.ino b/lib/espMqttClient/examples/ota-esp8266/ota-esp8266.ino deleted file mode 100644 index 90f1326..0000000 --- a/lib/espMqttClient/examples/ota-esp8266/ota-esp8266.ino +++ /dev/null @@ -1,159 +0,0 @@ -#include -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 130, 10) -#define MQTT_PORT 1883 - -#define UPDATE_TOPIC "device/firmware/set" - -WiFiEventHandler wifiConnectHandler; -WiFiEventHandler wifiDisconnectHandler; -espMqttClient mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; -bool disconnectFlag = false; -bool restartFlag = false; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void onWiFiConnect(const WiFiEventStationModeGotIP& event) { - (void) event; - Serial.println("Connected to Wi-Fi."); - connectToMqtt(); -} - -void onWiFiDisconnect(const WiFiEventStationModeDisconnected& event) { - (void) event; - Serial.println("Disconnected from Wi-Fi."); -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe(UPDATE_TOPIC, 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (disconnectFlag) { - restartFlag = true; - return; - } - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void handleUpdate(const uint8_t* payload, size_t length, size_t index, size_t total) { - // The Updater class takes a non-const pointer to write data although it doesn't change the data - uint8_t* data = const_cast(payload); - static size_t written = 0; - Update.runAsync(true); - if (index == 0) { - if (Update.isRunning()) { - Update.end(); - Update.clearError(); - } - Update.begin(total); - written = Update.write(data, length); - Serial.printf("Updating %u/%u\n", written, Update.size()); - } else { - if (!Update.isRunning()) return; - written += Update.write(data, length); - Serial.printf("Updating %u/%u\n", written, Update.size()); - } - if (Update.isFinished()) { - if (Update.end()) { - Serial.println("Update succes"); - disconnectFlag = true; - } else { - Serial.printf("Update error: %u\n", Update.getError()); - Update.printError(Serial); - Update.clearError(); - } - } -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) properties; - if (strcmp(UPDATE_TOPIC, topic) != 0) { - Serial.println("Topic mismatch"); - return; - } - handleUpdate(payload, len, index, total); -} - -void setup() { - Serial.begin(74880); - Serial.println(); - Serial.println(); - - WiFi.setAutoConnect(false); - WiFi.setAutoReconnect(true); - wifiConnectHandler = WiFi.onStationModeGotIP(onWiFiConnect); - wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - if (restartFlag) { - Serial.println("Rebooting... See you next time!"); - Serial.flush(); - ESP.reset(); - } - - static uint32_t currentMillis = millis(); - - mqttClient.loop(); - - if (!disconnectFlag && reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } - - if (disconnectFlag) { - // it's safe to call this multiple times - mqttClient.disconnect(); - } -} \ No newline at end of file diff --git a/lib/espMqttClient/examples/simple-esp32-idf/CMakeLists.txt b/lib/espMqttClient/examples/simple-esp32-idf/CMakeLists.txt deleted file mode 100644 index e1f4c03..0000000 --- a/lib/espMqttClient/examples/simple-esp32-idf/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -# The following lines of boilerplate have to be in your project's -# CMakeLists in this exact order for cmake to work correctly -cmake_minimum_required(VERSION 3.5) - -SET(SDKCONFIG ${CMAKE_BINARY_DIR}/sdkconfig) - -include($ENV{IDF_PATH}/tools/cmake/project.cmake) -project(simple-esp32-idf) \ No newline at end of file diff --git a/lib/espMqttClient/examples/simple-esp32-idf/README.md b/lib/espMqttClient/examples/simple-esp32-idf/README.md deleted file mode 100644 index 8fd90c7..0000000 --- a/lib/espMqttClient/examples/simple-esp32-idf/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This example is for use with [Arduino as a component](https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/esp-idf_component.html) in the ESP-IDF framework. - -Be sure to follow [this section](https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/esp-idf_component.html#adding-local-library) about adding libraries to your project. diff --git a/lib/espMqttClient/examples/simple-esp32-idf/main/CMakeLists.txt b/lib/espMqttClient/examples/simple-esp32-idf/main/CMakeLists.txt deleted file mode 100644 index 475d0f7..0000000 --- a/lib/espMqttClient/examples/simple-esp32-idf/main/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -idf_component_register( - SRCS "main.cpp" - INCLUDE_DIRS "") \ No newline at end of file diff --git a/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp b/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp deleted file mode 100644 index 77c8148..0000000 --- a/lib/espMqttClient/examples/simple-esp32-idf/main/main.cpp +++ /dev/null @@ -1,142 +0,0 @@ -#include -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -espMqttClient mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void WiFiEvent(WiFiEvent_t event) { - Serial.printf("[WiFi-event] event: %d\n", event); - switch(event) { - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - connectToMqtt(); - break; - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - Serial.println("WiFi lost connection"); - break; - default: - break; - } -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("foo/bar", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("foo/bar", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("foo/bar", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("foo/bar", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.persistent(false); - WiFi.setAutoReconnect(true); - WiFi.onEvent(WiFiEvent); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} diff --git a/lib/espMqttClient/examples/simple-esp32-idf/sdkconfig.defaults b/lib/espMqttClient/examples/simple-esp32-idf/sdkconfig.defaults deleted file mode 100644 index 4661ad2..0000000 --- a/lib/espMqttClient/examples/simple-esp32-idf/sdkconfig.defaults +++ /dev/null @@ -1,39 +0,0 @@ -# -# Bootloader config -# -CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y -CONFIG_BOOTLOADER_LOG_LEVEL_NONE=y -CONFIG_BOOTLOADER_LOG_LEVEL=0 - -# -# Serial flasher config -# -CONFIG_ESPTOOLPY_FLASHMODE_DIO=y -CONFIG_ESPTOOLPY_FLASHMODE="dio" -CONFIG_ESPTOOLPY_FLASHFREQ_40M=y -CONFIG_ESPTOOLPY_FLASHFREQ="40m" -CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y -CONFIG_ESPTOOLPY_FLASHSIZE="4MB" -# -# Partition Table -# -CONFIG_PARTITION_TABLE_CUSTOM=n - -# -# Arduino Configuration -# -CONFIG_ARDUINO_VARIANT="esp32" -CONFIG_ENABLE_ARDUINO_DEPENDS=y -CONFIG_AUTOSTART_ARDUINO=y - -# -# FreeRTOS -# -# 1000 require for Arduino -CONFIG_FREERTOS_HZ=1000 - -#ASYNC_TCP -CONFIG_ASYNC_TCP_RUN_NO_AFFINITY=y - -#MBEDTLS -CONFIG_MBEDTLS_PSK_MODES=y \ No newline at end of file diff --git a/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino b/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino deleted file mode 100644 index 1a5de37..0000000 --- a/lib/espMqttClient/examples/simple-esp32/simple-esp32.ino +++ /dev/null @@ -1,141 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -espMqttClient mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void WiFiEvent(WiFiEvent_t event) { - Serial.printf("[WiFi-event] event: %d\n", event); - switch(event) { - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - connectToMqtt(); - break; - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - Serial.println("WiFi lost connection"); - break; - default: - break; - } -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("foo/bar", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("foo/bar", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("foo/bar", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("foo/bar", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.persistent(false); - WiFi.setAutoReconnect(true); - WiFi.onEvent(WiFiEvent); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} diff --git a/lib/espMqttClient/examples/simple-esp8266/simple-esp8266.ino b/lib/espMqttClient/examples/simple-esp8266/simple-esp8266.ino deleted file mode 100644 index 2d54e12..0000000 --- a/lib/espMqttClient/examples/simple-esp8266/simple-esp8266.ino +++ /dev/null @@ -1,139 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -WiFiEventHandler wifiConnectHandler; -WiFiEventHandler wifiDisconnectHandler; -espMqttClient mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void onWiFiConnect(const WiFiEventStationModeGotIP& event) { - (void) event; - Serial.println("Connected to Wi-Fi."); - connectToMqtt(); -} - -void onWiFiDisconnect(const WiFiEventStationModeDisconnected& event) { - (void) event; - Serial.println("Disconnected from Wi-Fi."); -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("test/lol", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("test/lol", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("test/lol", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.setAutoConnect(false); - WiFi.setAutoReconnect(true); - wifiConnectHandler = WiFi.onStationModeGotIP(onWiFiConnect); - wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - mqttClient.loop(); - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} \ No newline at end of file diff --git a/lib/espMqttClient/examples/simple-linux/main.cpp b/lib/espMqttClient/examples/simple-linux/main.cpp deleted file mode 100644 index 54daa86..0000000 --- a/lib/espMqttClient/examples/simple-linux/main.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include -#include -#include - -#define MQTT_HOST IPAddress(192,168,1,10) -#define MQTT_PORT 1883 - -espMqttClient mqttClient; -std::atomic_bool exitProgram(false); - -void connectToMqtt() { - std::cout << "Connecting to MQTT..." << std::endl; - mqttClient.connect(); -} - -void onMqttConnect(bool sessionPresent) { - std::cout << "Connected to MQTT." << std::endl; - std::cout << "Session present: " << sessionPresent << std::endl; - uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2); - std::cout << "Subscribing at QoS 2, packetId: " << packetIdSub << std::endl; - mqttClient.publish("test/lol", 0, true, "test 1"); - std::cout << "Publishing at QoS 0" << std::endl; - uint16_t packetIdPub1 = mqttClient.publish("test/lol", 1, true, "test 2"); - std::cout << "Publishing at QoS 1, packetId: " << packetIdPub1 << std::endl; - uint16_t packetIdPub2 = mqttClient.publish("test/lol", 2, true, "test 3"); - std::cout << "Publishing at QoS 2, packetId: " << packetIdPub2 << std::endl; -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - std::cout << "Disconnected from MQTT: %u.\n" << unsigned(static_cast(reason)) << std::endl; - exitProgram = true; -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - std::cout << "Subscribe acknowledged." << std::endl; - std::cout << " packetId: " << packetId << std::endl; - for (size_t i = 0; i < len; ++i) { - std::cout << " qos: " << unsigned(static_cast(codes[i])) << std::endl; - } -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - std::cout << "Publish received." << std::endl; - std::cout << " topic: " << topic << std::endl; - std::cout << " qos: " << unsigned(properties.qos) << std::endl; - std::cout << " dup: " << properties.dup << std::endl; - std::cout << " retain: " << properties.retain << std::endl; - std::cout << " len: " << len << std::endl; - std::cout << " index: " << index << std::endl; - std::cout << " total: " << total << std::endl; -} - -void onMqttPublish(uint16_t packetId) { - std::cout << "Publish acknowledged." << std::endl; - std::cout << " packetId: " << packetId << std::endl; -} - -void ClientLoop(void* arg) { - (void) arg; - for(;;) { - mqttClient.loop(); // includes a yield - if (exitProgram) break; - } -} - -int main() { - std::cout << "Setting up sample MQTT client" << std::endl; - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - std::cout << "Starting sample MQTT client" << std::endl; - std::thread t = std::thread(ClientLoop, nullptr); - - connectToMqtt(); - - while(1) { - if (exitProgram) break; - std::this_thread::yield(); - } - - t.join(); - return EXIT_SUCCESS; -} diff --git a/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino b/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino deleted file mode 100644 index 109bcf0..0000000 --- a/lib/espMqttClient/examples/simpleAsync-esp32/simpleAsync-esp32.ino +++ /dev/null @@ -1,141 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -espMqttClientAsync mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void WiFiEvent(WiFiEvent_t event) { - Serial.printf("[WiFi-event] event: %d\n", event); - switch(event) { - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - connectToMqtt(); - break; - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - Serial.println("WiFi lost connection"); - break; - default: - break; - } -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("foo/bar", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("foo/bar", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("foo/bar", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("foo/bar", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.persistent(false); - WiFi.setAutoReconnect(true); - WiFi.onEvent(WiFiEvent); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} diff --git a/lib/espMqttClient/examples/simpleAsync-esp8266/simpleAsync-esp8266.ino b/lib/espMqttClient/examples/simpleAsync-esp8266/simpleAsync-esp8266.ino deleted file mode 100644 index 804caa1..0000000 --- a/lib/espMqttClient/examples/simpleAsync-esp8266/simpleAsync-esp8266.ino +++ /dev/null @@ -1,138 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST IPAddress(192, 168, 1, 10) -#define MQTT_PORT 1883 - -WiFiEventHandler wifiConnectHandler; -WiFiEventHandler wifiDisconnectHandler; -espMqttClientAsync mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void onWiFiConnect(const WiFiEventStationModeGotIP& event) { - (void) event; - Serial.println("Connected to Wi-Fi."); - connectToMqtt(); -} - -void onWiFiDisconnect(const WiFiEventStationModeDisconnected& event) { - (void) event; - Serial.println("Disconnected from Wi-Fi."); -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("test/lol", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("test/lol", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("test/lol", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.setAutoConnect(false); - WiFi.setAutoReconnect(true); - wifiConnectHandler = WiFi.onStationModeGotIP(onWiFiConnect); - wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} \ No newline at end of file diff --git a/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino b/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino deleted file mode 100644 index ce75a5a..0000000 --- a/lib/espMqttClient/examples/tls-esp32/tls-esp32.ino +++ /dev/null @@ -1,170 +0,0 @@ -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST "mqtt.yourhost.com" -#define MQTT_PORT 8883 -#define MQTT_USER "username" -#define MQTT_PASS "password" - -const char rootCA[] = \ - "-----BEGIN CERTIFICATE-----\n" \ - " add your certificate here \n" \ - "-----END CERTIFICATE-----\n"; - -espMqttClientSecure mqttClient(espMqttClientTypes::UseInternalTask::NO); -static TaskHandle_t taskHandle; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void WiFiEvent(WiFiEvent_t event) { - Serial.printf("[WiFi-event] event: %d\n", event); - switch(event) { - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - connectToMqtt(); - break; - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - Serial.println("WiFi lost connection"); - break; - default: - break; - } -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - - uint16_t packetIdSub0 = mqttClient.subscribe("foo/bar/0", 0); - Serial.print("Subscribing at QoS 0, packetId: "); - Serial.println(packetIdSub0); - - uint16_t packetIdPub0 = mqttClient.publish("foo/bar/0", 0, false, "test"); - Serial.println("Publishing at QoS 0, packetId: "); - Serial.println(packetIdPub0); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void networkingTask() { - for (;;) { - mqttClient.loop(); - } -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.persistent(false); - WiFi.setAutoReconnect(true); - WiFi.onEvent(WiFiEvent); - - //mqttClient.setInsecure(); - mqttClient.setCACert(rootCA); - mqttClient.setCredentials(MQTT_USER, MQTT_PASS); - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - mqttClient.setCleanSession(true); - - xTaskCreatePinnedToCore((TaskFunction_t)networkingTask, "mqttclienttask", 5120, nullptr, 1, &taskHandle, 0); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } - - static uint32_t lastMillis = 0; - if (currentMillis - lastMillis > 5000) { - lastMillis = currentMillis; - Serial.printf("heap: %u\n", ESP.getFreeHeap()); - } - - static uint32_t millisDisconnect = 0; - if (currentMillis - millisDisconnect > 60000) { - millisDisconnect = currentMillis; - mqttClient.disconnect(); - } -} diff --git a/lib/espMqttClient/examples/tls-esp8266/tls-esp8266.ino b/lib/espMqttClient/examples/tls-esp8266/tls-esp8266.ino deleted file mode 100644 index f2cb209..0000000 --- a/lib/espMqttClient/examples/tls-esp8266/tls-esp8266.ino +++ /dev/null @@ -1,144 +0,0 @@ -#include -#include - -#include - -#define WIFI_SSID "yourSSID" -#define WIFI_PASSWORD "yourpass" - -#define MQTT_HOST "test.mosquitto.org" -#define MQTT_PORT 1883 - -// test.mosquitto.org -const uint8_t fingerprint[] = {0xee, 0xbc, 0x4b, 0xf8, 0x57, 0xe3, 0xd3, 0xe4, 0x07, 0x54, 0x23, 0x1e, 0xf0, 0xc8, 0xa1, 0x56, 0xe0, 0xd3, 0x1a, 0x1c}; - -WiFiEventHandler wifiConnectHandler; -WiFiEventHandler wifiDisconnectHandler; -espMqttClientSecure mqttClient; -bool reconnectMqtt = false; -uint32_t lastReconnect = 0; - -void connectToWiFi() { - Serial.println("Connecting to Wi-Fi..."); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - if (!mqttClient.connect()) { - reconnectMqtt = true; - lastReconnect = millis(); - Serial.println("Connecting failed."); - } else { - reconnectMqtt = false; - } -} - -void onWiFiConnect(const WiFiEventStationModeGotIP& event) { - (void) event; - Serial.println("Connected to Wi-Fi."); - connectToMqtt(); -} - -void onWiFiDisconnect(const WiFiEventStationModeDisconnected& event) { - (void) event; - Serial.println("Disconnected from Wi-Fi."); -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2); - Serial.print("Subscribing at QoS 2, packetId: "); - Serial.println(packetIdSub); - mqttClient.publish("test/lol", 0, true, "test 1"); - Serial.println("Publishing at QoS 0"); - uint16_t packetIdPub1 = mqttClient.publish("test/lol", 1, true, "test 2"); - Serial.print("Publishing at QoS 1, packetId: "); - Serial.println(packetIdPub1); - uint16_t packetIdPub2 = mqttClient.publish("test/lol", 2, true, "test 3"); - Serial.print("Publishing at QoS 2, packetId: "); - Serial.println(packetIdPub2); -} - -void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) { - Serial.printf("Disconnected from MQTT: %u.\n", static_cast(reason)); - - if (WiFi.isConnected()) { - reconnectMqtt = true; - lastReconnect = millis(); - } -} - -void onMqttSubscribe(uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* codes, size_t len) { - Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - for (size_t i = 0; i < len; ++i) { - Serial.print(" qos: "); - Serial.println(static_cast(codes[i])); - } -} - -void onMqttUnsubscribe(uint16_t packetId) { - Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void onMqttMessage(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - (void) payload; - Serial.println("Publish received."); - Serial.print(" topic: "); - Serial.println(topic); - Serial.print(" qos: "); - Serial.println(properties.qos); - Serial.print(" dup: "); - Serial.println(properties.dup); - Serial.print(" retain: "); - Serial.println(properties.retain); - Serial.print(" len: "); - Serial.println(len); - Serial.print(" index: "); - Serial.println(index); - Serial.print(" total: "); - Serial.println(total); -} - -void onMqttPublish(uint16_t packetId) { - Serial.println("Publish acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); -} - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(); - - WiFi.setAutoConnect(false); - WiFi.setAutoReconnect(true); - wifiConnectHandler = WiFi.onStationModeGotIP(onWiFiConnect); - wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - mqttClient.setFingerprint(fingerprint); - - connectToWiFi(); -} - -void loop() { - static uint32_t currentMillis = millis(); - - mqttClient.loop(); - if (reconnectMqtt && currentMillis - lastReconnect > 5000) { - connectToMqtt(); - } -} \ No newline at end of file diff --git a/lib/espMqttClient/keywords.txt b/lib/espMqttClient/keywords.txt deleted file mode 100644 index 3807482..0000000 --- a/lib/espMqttClient/keywords.txt +++ /dev/null @@ -1,61 +0,0 @@ -# Datatypes (KEYWORD1) -espMqttClient KEYWORD1 -espMqttClientSecure KEYWORD1 - -OnConnectCallback KEYWORD1 -OnDisconnectCallback KEYWORD1 -OnSubscribeCallback KEYWORD1 -OnUnsubscribeCallback KEYWORD1 -OnMessageCallback KEYWORD1 -OnPublishCallback KEYWORD1 - -# Methods and Functions (KEYWORD2) -setKeepAlive KEYWORD2 -setClientId KEYWORD2 -setCleanSession KEYWORD2 -setCredentials KEYWORD2 -setWill KEYWORD2 -setServer KEYWORD2 - -setInsecure KEYWORD2 -setCACert KEYWORD2 -setCertificate KEYWORD2 -setPrivateKey KEYWORD2 -setPreSharedKey KEYWORD2 -setFingerprint KEYWORD2 -setTrustAnchors KEYWORD2 -setClientRSACert KEYWORD2 -setClientECCert KEYWORD2 -setCertStore KEYWORD2 - -onConnect KEYWORD2 -onDisconnect KEYWORD2 -onSubscribe KEYWORD2 -onUnsubscribe KEYWORD2 -onMessage KEYWORD2 -onPublish KEYWORD2 - -connected KEYWORD2 -connect KEYWORD2 -disconnect KEYWORD2 -subscribe KEYWORD2 -unsubscribe KEYWORD2 -publish KEYWORD2 -clearQueue KEYWORD2 -loop KEYWORD2 -getClientId KEYWORD2 -queueSize KEYWORD2 - -# Structures (KEYWORD3) -espMqttClientTypes KEYWORD3 -MessageProperties KEYWORD3 -DisconnectReason KEYWORD3 - -# Constants (LITERAL1) -TCP_DISCONNECTED LITERAL1 -MQTT_UNACCEPTABLE_PROTOCOL_VERSION LITERAL1 -MQTT_IDENTIFIER_REJECTED LITERAL1 -MQTT_SERVER_UNAVAILABLE LITERAL1 -MQTT_MALFORMED_CREDENTIALS LITERAL1 -MQTT_NOT_AUTHORIZED LITERAL1 -TLS_BAD_FINGERPRINT LITERAL1 diff --git a/lib/espMqttClient/library.json b/lib/espMqttClient/library.json deleted file mode 100644 index 21c8429..0000000 --- a/lib/espMqttClient/library.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "espMqttClient", - "keywords": "iot, home, automation, mqtt, client, esp8266, esp32", - "description": "an MQTT client for the Arduino framework for ESP8266 / ESP32", - "authors": - { - "name": "Bert Melis", - "url": "https://github.com/bertmelis" - }, - "license": "MIT", - "homepage": "https://github.com/bertmelis/espMqttClient", - "repository": - { - "type": "git", - "url": "https://github.com/bertmelis/espMqttClient.git" - }, - "version": "1.7.0", - "frameworks": "arduino", - "platforms": ["espressif8266", "espressif32"], - "headers": ["espMqttClient.h", "espMqttClientAsync.h"], - "build": - { - "libLDFMode": "deep+" - } -} diff --git a/lib/espMqttClient/library.properties b/lib/espMqttClient/library.properties deleted file mode 100644 index 3b906a9..0000000 --- a/lib/espMqttClient/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=espMqttClient -version=1.7.0 -author=Bert Melis -maintainer=Bert Melis -sentence=an MQTT client for the Arduino framework for ESP8266 / ESP32 -paragraph= -category=Communication -url=https://github.com/bertmelis/espMqttClient -architectures=esp8266,esp32 \ No newline at end of file diff --git a/lib/espMqttClient/platformio.ini b/lib/espMqttClient/platformio.ini deleted file mode 100644 index 219ed3b..0000000 --- a/lib/espMqttClient/platformio.ini +++ /dev/null @@ -1,43 +0,0 @@ -; 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 = esp8266 - -[common] -build_flags = - -D DEBUG_ESP_MQTT_CLIENT=1 - -D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE - -Wall - -Wextra - -std=c++11 - -pthread - -ggdb3 - -[env:native] -platform = native -test_build_src = yes -build_flags = - ${common.build_flags} - -lgcov - --coverage - -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 = - valgrind - --leak-check=full - --show-leak-kinds=all - --track-origins=yes - --error-exitcode=1 - ${platformio.build_dir}/${this.__env__}/program diff --git a/lib/espMqttClient/scripts/get-fingerprint.py b/lib/espMqttClient/scripts/get-fingerprint.py deleted file mode 100644 index 22c078b..0000000 --- a/lib/espMqttClient/scripts/get-fingerprint.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -# https://github.com/marvinroger/async-mqtt-client/blob/develop/scripts/get-fingerprint/get-fingerprint.py - -import argparse -import ssl -import hashlib - -parser = argparse.ArgumentParser(description='Compute SSL/TLS fingerprints.') -parser.add_argument('--host', required=True) -parser.add_argument('--port', default=8883) - -args = parser.parse_args() -print(args.host) - -cert_pem = ssl.get_server_certificate((args.host, args.port)) -cert_der = ssl.PEM_cert_to_DER_cert(cert_pem) - -md5 = hashlib.md5(cert_der).hexdigest() -sha1 = hashlib.sha1(cert_der).hexdigest() -sha256 = hashlib.sha256(cert_der).hexdigest() -print("MD5: " + md5) -print("SHA1: " + sha1) -print("SHA256: " + sha256) - -print("\nSHA1 as array initializer:") -print("const uint8_t fingerprint[] = {0x" + ", 0x".join([sha1[i:i+2] for i in range(0, len(sha1), 2)]) + "};") - -print("\nSHA1 as function call:") -print("mqttClient.addServerFingerprint((const uint8_t[]){0x" + ", 0x".join([sha1[i:i+2] for i in range(0, len(sha1), 2)]) + "});") \ No newline at end of file diff --git a/lib/espMqttClient/src/Config.h b/lib/espMqttClient/src/Config.h deleted file mode 100644 index 935f7e1..0000000 --- a/lib/espMqttClient/src/Config.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright (c) 2022 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 - -#ifndef EMC_TX_TIMEOUT -#define EMC_TX_TIMEOUT 10000 -#endif - -#ifndef EMC_RX_BUFFER_SIZE -#define EMC_RX_BUFFER_SIZE 1440 -#endif - -#ifndef EMC_TX_BUFFER_SIZE -#define EMC_TX_BUFFER_SIZE 1440 -#endif - -#ifndef EMC_MAX_TOPIC_LENGTH -#define EMC_MAX_TOPIC_LENGTH 128 -#endif - -#ifndef EMC_PAYLOAD_BUFFER_SIZE -#define EMC_PAYLOAD_BUFFER_SIZE 32 -#endif - -#ifndef EMC_MIN_FREE_MEMORY -#define EMC_MIN_FREE_MEMORY 16384 -#endif - -#ifndef EMC_ESP8266_MULTITHREADING -#define EMC_ESP8266_MULTITHREADING 0 -#endif - -#ifndef EMC_ALLOW_NOT_CONNECTED_PUBLISH -#define EMC_ALLOW_NOT_CONNECTED_PUBLISH 1 -#endif - -#ifndef EMC_WAIT_FOR_CONNACK -#define EMC_WAIT_FOR_CONNACK 1 -#endif - -#ifndef EMC_CLIENTID_LENGTH -// esp8266abc123 and esp32abcdef123456 -#define EMC_CLIENTID_LENGTH 23 + 1 -#endif - -#ifndef EMC_TASK_STACK_SIZE -#define EMC_TASK_STACK_SIZE 5120 -#endif - -#ifndef EMC_MULTIPLE_CALLBACKS -#define EMC_MULTIPLE_CALLBACKS 0 -#endif - -#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/Helpers.h b/lib/espMqttClient/src/Helpers.h deleted file mode 100644 index 05ab136..0000000 --- a/lib/espMqttClient/src/Helpers.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright (c) 2022 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 - -#if defined(ARDUINO_ARCH_ESP32) - #include // millis(), ESP.getFreeHeap(); - #include "freertos/FreeRTOS.h" - #include "freertos/task.h" - #include "esp_task_wdt.h" - #define EMC_SEMAPHORE_TAKE() xSemaphoreTake(_xSemaphore, portMAX_DELAY) - #define EMC_SEMAPHORE_GIVE() xSemaphoreGive(_xSemaphore) - #define EMC_GET_FREE_MEMORY() std::max(ESP.getMaxAllocHeap(), ESP.getMaxAllocPsram()) - #define EMC_YIELD() vTaskDelay(1) - #define EMC_GENERATE_CLIENTID(x) snprintf(x, EMC_CLIENTID_LENGTH, "esp32%06llx", ESP.getEfuseMac()); -#elif defined(ARDUINO_ARCH_ESP8266) - #include // millis(), ESP.getFreeHeap(); - #if EMC_ESP8266_MULTITHREADING - // This lib doesn't run use multithreading on ESP8266 - // _xSemaphore defined as std::atomic - #define EMC_SEMAPHORE_TAKE() while (_xSemaphore) { /*ESP.wdtFeed();*/ } _xSemaphore = true - #define EMC_SEMAPHORE_GIVE() _xSemaphore = false - #else - #define EMC_SEMAPHORE_TAKE() - #define EMC_SEMAPHORE_GIVE() - #endif - #define EMC_GET_FREE_MEMORY() ESP.getMaxFreeBlockSize() - // no need to yield for ESP8266, the Arduino framework does this internally - // yielding in async is forbidden (will crash) - #define EMC_YIELD() - #define EMC_GENERATE_CLIENTID(x) snprintf(x, EMC_CLIENTID_LENGTH, "esp8266%06x", ESP.getChipId()); -#elif defined(__linux__) - #include // NOLINT [build/c++11] - #include // NOLINT [build/c++11] for yield() - #define millis() std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count() - #define EMC_GET_FREE_MEMORY() 1000000000 - #define EMC_YIELD() std::this_thread::yield() - #define EMC_GENERATE_CLIENTID(x) snprintf(x, EMC_CLIENTID_LENGTH, "Client%04d%04d%04d", rand()%10000, rand()%10000, rand()%10000) - #include // NOLINT [build/c++11] - #define EMC_SEMAPHORE_TAKE() mtx.lock(); - #define EMC_SEMAPHORE_GIVE() mtx.unlock(); -#else - #error Target platform not supported -#endif diff --git a/lib/espMqttClient/src/Logging.h b/lib/espMqttClient/src/Logging.h deleted file mode 100644 index 3ba096a..0000000 --- a/lib/espMqttClient/src/Logging.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright (c) 2022 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 - -#if defined(ARDUINO_ARCH_ESP32) - #include - #include "freertos/FreeRTOS.h" - #include "freertos/task.h" - #if defined(DEBUG_ESP_MQTT_CLIENT) - // Logging is en/disabled by Arduino framework macros - #define emc_log_i(...) log_i(__VA_ARGS__) - #define emc_log_e(...) log_e(__VA_ARGS__) - #define emc_log_w(...) log_w(__VA_ARGS__) - #else - // Logging is disabled - #define emc_log_i(...) - #define emc_log_e(...) - #define emc_log_w(...) - #endif -#elif defined(ARDUINO_ARCH_ESP8266) - #if defined(DEBUG_ESP_PORT) && defined(DEBUG_ESP_MQTT_CLIENT) - #include - #define emc_log_i(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n") - #define emc_log_e(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n") - #define emc_log_w(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n") - #else - #define emc_log_i(...) - #define emc_log_e(...) - #define emc_log_w(...) - #endif -#else - // when building for PC, always show debug statements as part of testing suite - #include - #define emc_log_i(...) std::cout << "[I] " << __FILE__ ":" << __LINE__ << ": "; printf(__VA_ARGS__); std::cout << std::endl - #define emc_log_e(...) std::cout << "[E] " << __FILE__ ":" << __LINE__ << ": "; printf(__VA_ARGS__); std::cout << std::endl - #define emc_log_w(...) std::cout << "[W] " << __FILE__ ":" << __LINE__ << ": "; printf(__VA_ARGS__); std::cout << std::endl -#endif diff --git a/lib/espMqttClient/src/MemoryPool/LICENSE b/lib/espMqttClient/src/MemoryPool/LICENSE deleted file mode 100644 index 526a0c7..0000000 --- a/lib/espMqttClient/src/MemoryPool/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 81b6fd4..0000000 --- a/lib/espMqttClient/src/MemoryPool/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# 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 deleted file mode 100644 index ef87ce2..0000000 --- a/lib/espMqttClient/src/MemoryPool/keywords.txt +++ /dev/null @@ -1,16 +0,0 @@ -# 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 deleted file mode 100644 index f9e6116..0000000 --- a/lib/espMqttClient/src/MemoryPool/library.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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 deleted file mode 100644 index a46b50f..0000000 --- a/lib/espMqttClient/src/MemoryPool/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index b68dbd1..0000000 --- a/lib/espMqttClient/src/MemoryPool/src/Fixed.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -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 deleted file mode 100644 index 5b198ea..0000000 --- a/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h +++ /dev/null @@ -1,12 +0,0 @@ -/* -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 deleted file mode 100644 index 563bf49..0000000 --- a/lib/espMqttClient/src/MemoryPool/src/Variable.h +++ /dev/null @@ -1,242 +0,0 @@ -/* -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 deleted file mode 100644 index dc21f74..0000000 --- a/lib/espMqttClient/src/MqttClient.cpp +++ /dev/null @@ -1,746 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "MqttClient.h" - -using espMqttClientInternals::Packet; -using espMqttClientInternals::PacketType; -using espMqttClientTypes::DisconnectReason; -using espMqttClientTypes::Error; - -MqttClient::MqttClient(espMqttClientTypes::UseInternalTask useInternalTask, uint8_t priority, uint8_t core) -: _useInternalTask(useInternalTask) -, _transport(nullptr) -, _onConnectCallback(nullptr) -, _onDisconnectCallback(nullptr) -, _onSubscribeCallback(nullptr) -, _onUnsubscribeCallback(nullptr) -, _onMessageCallback(nullptr) -, _onPublishCallback(nullptr) -, _onErrorCallback(nullptr) -, _clientId(nullptr) -, _ip() -, _host(nullptr) -, _port(1883) -, _useIp(false) -, _keepAlive(15000) -, _cleanSession(true) -, _username(nullptr) -, _password(nullptr) -, _willTopic(nullptr) -, _willPayload(nullptr) -, _willPayloadLength(0) -, _willQos(0) -, _willRetain(false) -, _timeout(EMC_TX_TIMEOUT) -, _state(State::disconnected) -, _generatedClientId{0} -, _packetId(0) -#if defined(ARDUINO_ARCH_ESP32) -, _xSemaphore(nullptr) -, _taskHandle(nullptr) -#endif -, _rxBuffer{0} -, _outbox() -, _bytesSent(0) -, _parser() -, _lastClientActivity(0) -, _lastServerActivity(0) -, _pingSent(false) -, _disconnectReason(DisconnectReason::TCP_DISCONNECTED) -#if defined(ARDUINO_ARCH_ESP32) && ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO -, _highWaterMark(4294967295) -#endif - { - EMC_GENERATE_CLIENTID(_generatedClientId); -#if defined(ARDUINO_ARCH_ESP32) - _xSemaphore = xSemaphoreCreateMutex(); - EMC_SEMAPHORE_GIVE(); // release before first use - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - xTaskCreatePinnedToCore((TaskFunction_t)_loop, "mqttclient", EMC_TASK_STACK_SIZE, this, priority, &_taskHandle, core); - } -#else - (void) useInternalTask; - (void) priority; - (void) core; -#endif - _clientId = _generatedClientId; -} - -MqttClient::~MqttClient() { - disconnect(true); - _clearQueue(2); -#if defined(ARDUINO_ARCH_ESP32) - vSemaphoreDelete(_xSemaphore); - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - #if EMC_USE_WATCHDOG - esp_task_wdt_delete(_taskHandle); // not sure if this is really needed - #endif - vTaskDelete(_taskHandle); - } -#endif -} - -bool MqttClient::connected() const { - if (_state == State::connected) return true; - return false; -} - -bool MqttClient::disconnected() const { - if (_state == State::disconnected) return true; - return false; -} - -bool MqttClient::connect() { - bool result = false; - if (_state == State::disconnected) { - EMC_SEMAPHORE_TAKE(); - if (_addPacketFront(_cleanSession, - _username, - _password, - _willTopic, - _willRetain, - _willQos, - _willPayload, - _willPayloadLength, - (uint16_t)(_keepAlive / 1000), // 32b to 16b doesn't overflow because it comes from 16b orignally - _clientId)) { - result = true; - _setState(State::connectingTcp1); - #if defined(ARDUINO_ARCH_ESP32) - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - vTaskResume(_taskHandle); - } - #endif - } else { - emc_log_e("Could not create CONNECT packet"); - EMC_SEMAPHORE_GIVE(); - _onError(0, Error::OUT_OF_MEMORY); - EMC_SEMAPHORE_TAKE(); - } - EMC_SEMAPHORE_GIVE(); - } - return result; -} - -bool MqttClient::disconnect(bool force) { - if (force && _state != State::disconnected && _state != State::disconnectingTcp1 && _state != State::disconnectingTcp2) { - _setState(State::disconnectingTcp1); - return true; - } - if (!force && _state == State::connected) { - _setState(State::disconnectingMqtt1); - return true; - } - return false; -} - -uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length) { - #if !EMC_ALLOW_NOT_CONNECTED_PUBLISH - if (_state != State::connected) { - #else - if (_state > State::connected) { - #endif - return 0; - } - EMC_SEMAPHORE_TAKE(); - 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(); - return packetId; -} - -uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, const char* payload) { - size_t len = strlen(payload); - return publish(topic, qos, retain, reinterpret_cast(payload), len); -} - -uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length) { - #if !EMC_ALLOW_NOT_CONNECTED_PUBLISH - if (_state != State::connected) { - #else - if (_state > State::connected) { - #endif - return 0; - } - EMC_SEMAPHORE_TAKE(); - 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(); - return packetId; -} - -void MqttClient::clearQueue(bool deleteSessionData) { - EMC_SEMAPHORE_TAKE(); - _clearQueue(deleteSessionData ? 2 : 0); - EMC_SEMAPHORE_GIVE(); -} - -const char* MqttClient::getClientId() const { - return _clientId; -} - -size_t MqttClient::queueSize() { - size_t ret = 0; - EMC_SEMAPHORE_TAKE(); - ret = _outbox.size(); - EMC_SEMAPHORE_GIVE(); - return ret; -} - -void MqttClient::loop() { - switch (_state) { - case State::disconnected: - #if defined(ARDUINO_ARCH_ESP32) - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - vTaskSuspend(_taskHandle); - } - #endif - break; - case State::connectingTcp1: - if (_useIp ? _transport->connect(_ip, _port) : _transport->connect(_host, _port)) { - _setState(State::connectingTcp2); - } else { - _setState(State::disconnectingTcp1); - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - break; - } - // Falling through to speed up connecting on blocking transport 'connect' implementations - [[fallthrough]]; - case State::connectingTcp2: - if (_transport->connected()) { - _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; - } - break; - #else - // receipt of CONNACK packet will set state to CONNECTED - // client however is allowed to send packets before CONNACK is received - // so we fall through to 'connected' - [[fallthrough]]; - #endif - case State::connected: - [[fallthrough]]; - 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; - } - break; - case State::disconnectingMqtt1: - EMC_SEMAPHORE_TAKE(); - if (_outbox.empty()) { - if (!_addPacket(PacketType.DISCONNECT)) { - EMC_SEMAPHORE_GIVE(); - emc_log_e("Could not create DISCONNECT packet"); - _onError(0, Error::OUT_OF_MEMORY); - EMC_SEMAPHORE_TAKE(); - } else { - _setState(State::disconnectingMqtt2); - } - } - _checkOutbox(); - _checkIncoming(); - _checkPing(); - _checkTimeout(); - EMC_SEMAPHORE_GIVE(); - break; - case State::disconnectingTcp1: - _transport->stop(); - _setState(State::disconnectingTcp2); - 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); - } - } - break; - // all cases covered, no default case - } - EMC_YIELD(); - #if defined(ARDUINO_ARCH_ESP32) && ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO - size_t waterMark = uxTaskGetStackHighWaterMark(NULL); - if (waterMark < _highWaterMark) { - _highWaterMark = waterMark; - emc_log_i("Stack usage: %zu/%i", EMC_TASK_STACK_SIZE - _highWaterMark, EMC_TASK_STACK_SIZE); - } - #endif -} - -#if defined(ARDUINO_ARCH_ESP32) -void MqttClient::_loop(MqttClient* c) { - #if EMC_USE_WATCHDOG - if (esp_task_wdt_add(NULL) != ESP_OK) { - emc_log_e("Failed to add async task to WDT"); - } - #endif - for (;;) { - c->loop(); - #if EMC_USE_WATCHDOG - esp_task_wdt_reset(); - #endif - } -} -#endif - -inline void MqttClient::_setState(State newState) { - emc_log_i("state %i --> %i", static_cast::type>(_state.load()), static_cast::type>(newState)); - _state = newState; -} - -uint16_t MqttClient::_getNextPacketId() { - ++_packetId; - if (_packetId == 0) ++_packetId; - return _packetId; -} - -void MqttClient::_checkOutbox() { - while (_sendPacket() > 0) { - if (!_advanceOutbox()) { - break; - } - } -} - -int MqttClient::_sendPacket() { - OutgoingPacket* packet = _outbox.getCurrent(); - - size_t written = 0; - if (packet) { - size_t wantToWrite = packet->packet.available(_bytesSent); - if (wantToWrite == 0) { - return 0; - } - written = _transport->write(packet->packet.data(_bytesSent), wantToWrite); - packet->timeSent = millis(); - _lastClientActivity = millis(); - _bytesSent += written; - emc_log_i("tx %zu/%zu (%02x)", _bytesSent, packet->packet.size(), packet->packet.packetType()); - } - return written; -} - -bool MqttClient::_advanceOutbox() { - OutgoingPacket* packet = _outbox.getCurrent(); - if (packet && _bytesSent == packet->packet.size()) { - if ((packet->packet.packetType()) == PacketType.DISCONNECT) { - _setState(State::disconnectingTcp1); - _disconnectReason = DisconnectReason::USER_OK; - } - if (packet->packet.removable()) { - _outbox.removeCurrent(); - } else { - // we already set 'dup' here, in case we have to retry - if ((packet->packet.packetType()) == PacketType.PUBLISH) packet->packet.setDup(); - _outbox.next(); - } - packet = _outbox.getCurrent(); - _bytesSent = 0; - } - return packet; -} - -void MqttClient::_checkIncoming() { - int32_t remainingBufferLength = _transport->read(_rxBuffer, EMC_RX_BUFFER_SIZE); - if (remainingBufferLength > 0) { - _lastServerActivity = millis(); - emc_log_i("rx len %i", remainingBufferLength); - size_t bytesParsed = 0; - size_t index = 0; - while (remainingBufferLength > 0) { - espMqttClientInternals::ParserResult result = _parser.parse(&_rxBuffer[index], remainingBufferLength, &bytesParsed); - if (result == espMqttClientInternals::ParserResult::packet) { - espMqttClientInternals::MQTTPacketType packetType = _parser.getPacket().fixedHeader.packetType & 0xF0; - if (_state == State::connectingMqtt && packetType != PacketType.CONNACK) { - emc_log_w("Disconnecting, expected CONNACK - protocol error"); - _setState(State::disconnectingTcp1); - return; - } - switch (packetType) { - case PacketType.CONNACK: - _onConnack(); - if (_state != State::connected) { - return; - } - break; - case PacketType.PUBLISH: - if (_state >= State::disconnectingMqtt1) break; // stop processing incoming once user has called disconnect - _onPublish(); - break; - case PacketType.PUBACK: - _onPuback(); - break; - case PacketType.PUBREC: - _onPubrec(); - break; - case PacketType.PUBREL: - _onPubrel(); - break; - case PacketType.PUBCOMP: - _onPubcomp(); - break; - case PacketType.SUBACK: - _onSuback(); - break; - case PacketType.UNSUBACK: - _onUnsuback(); - break; - case PacketType.PINGRESP: - _pingSent = false; - break; - } - } else if (result == espMqttClientInternals::ParserResult::protocolError) { - emc_log_w("Disconnecting, protocol error"); - _setState(State::disconnectingTcp1); - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - return; - } - remainingBufferLength -= bytesParsed; - index += bytesParsed; - emc_log_i("Parsed %zu - remaining %i", bytesParsed, remainingBufferLength); - bytesParsed = 0; - } - } -} - -void MqttClient::_checkPing() { - if (_keepAlive == 0) return; // keepalive is disabled - - uint32_t currentMillis = millis(); - - // disconnect when server was inactive for twice the keepalive time - if (currentMillis - _lastServerActivity > 2 * _keepAlive) { - emc_log_w("Disconnecting, server exceeded keepalive"); - _setState(State::disconnectingTcp1); - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - return; - } - - // send ping when client was inactive during the keepalive time - // or when server hasn't responded within keepalive time (typically due to QOS 0) - if (!_pingSent && - ((currentMillis - _lastClientActivity > _keepAlive) || - (currentMillis - _lastServerActivity > _keepAlive))) { - if (!_addPacket(PacketType.PINGREQ)) { - emc_log_e("Could not create PING packet"); - return; - } - _pingSent = true; - } -} - -void MqttClient::_checkTimeout() { - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - // check that we're not busy sending - // don't check when first item hasn't been sent yet - if (it && _bytesSent == 0 && it.get() != _outbox.getCurrent()) { - if (millis() - it.get()->timeSent > _timeout) { - emc_log_w("Packet ack timeout, retrying"); - _outbox.resetCurrent(); - } - } -} - -void MqttClient::_onConnack() { - if (_parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode == 0x00) { - _pingSent = false; // reset after keepalive timeout disconnect - _setState(State::connected); - _advanceOutbox(); - if (_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent == 0) { - _clearQueue(1); - } - if (_onConnectCallback) { - EMC_SEMAPHORE_GIVE(); - _onConnectCallback(_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent); - EMC_SEMAPHORE_TAKE(); - } - } else { - _setState(State::disconnectingTcp1); - // cast is safe because the parser already checked for a valid return code - _disconnectReason = static_cast(_parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode); - } -} - -void MqttClient::_onPublish() { - const espMqttClientInternals::IncomingPacket& p = _parser.getPacket(); - uint8_t qos = p.qos(); - bool retain = p.retain(); - bool dup = p.dup(); - uint16_t packetId = p.variableHeader.fixed.packetId; - bool callback = true; - if (qos == 1) { - if (p.payload.index + p.payload.length == p.payload.total) { - if (!_addPacket(PacketType.PUBACK, packetId)) { - emc_log_e("Could not create PUBACK packet"); - } - } - } else if (qos == 2) { - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - if ((it.get()->packet.packetType()) == PacketType.PUBREC && it.get()->packet.packetId() == packetId) { - callback = false; - emc_log_e("QoS2 packet previously delivered"); - break; - } - ++it; - } - if (p.payload.index + p.payload.length == p.payload.total) { - if (!_addPacket(PacketType.PUBREC, packetId)) { - emc_log_e("Could not create PUBREC packet"); - } - } - } - 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; - 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 - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBLISH) { - if (it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - emc_log_w("Received out of order PUBACK"); - break; - } - ++it; - } - if (callback) { - if (_onPublishCallback) { - EMC_SEMAPHORE_GIVE(); - _onPublishCallback(idToMatch); - EMC_SEMAPHORE_TAKE(); - } - } else { - emc_log_w("No matching PUBLISH packet found"); - } -} - -void MqttClient::_onPubrec() { - bool success = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - 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 - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBLISH) { - if (it.get()->packet.packetId() == idToMatch) { - if (!_addPacket(PacketType.PUBREL, idToMatch)) { - emc_log_e("Could not create PUBREL packet"); - } - _outbox.remove(it); - success = true; - break; - } - emc_log_w("Received out of order PUBREC"); - break; - } - ++it; - } - if (!success) { - emc_log_w("No matching PUBLISH packet found"); - } -} - -void MqttClient::_onPubrel() { - bool success = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - 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 - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBREC) { - if (it.get()->packet.packetId() == idToMatch) { - if (!_addPacket(PacketType.PUBCOMP, idToMatch)) { - emc_log_e("Could not create PUBCOMP packet"); - } - _outbox.remove(it); - success = true; - break; - } - emc_log_w("Received out of order PUBREL"); - break; - } - ++it; - } - if (!success) { - emc_log_w("No matching PUBREC packet found"); - } -} - -void MqttClient::_onPubcomp() { - bool callback = false; - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - while (it) { - // PUBCOMPs come in the order PUBRELs are sent. So we only check the first PUBREL packet in outbox - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBREL) { - if (it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - emc_log_w("Received out of order PUBCOMP"); - break; - } - ++it; - } - if (callback) { - if (_onPublishCallback) { - EMC_SEMAPHORE_GIVE(); - _onPublishCallback(idToMatch); - EMC_SEMAPHORE_TAKE(); - } - } else { - emc_log_w("No matching PUBREL packet found"); - } -} - -void MqttClient::_onSuback() { - bool callback = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - if (((it.get()->packet.packetType()) == PacketType.SUBSCRIBE) && it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - ++it; - } - if (callback) { - 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"); - } -} - -void MqttClient::_onUnsuback() { - bool callback = false; - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - while (it) { - if (it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - ++it; - } - if (callback) { - if (_onUnsubscribeCallback) { - EMC_SEMAPHORE_GIVE(); - _onUnsubscribeCallback(idToMatch); - EMC_SEMAPHORE_TAKE(); - } - } else { - emc_log_w("received UNSUBACK without UNSUB"); - } -} - -void MqttClient::_clearQueue(int clearData) { - emc_log_i("clearing queue (clear session: %d)", clearData); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - if (clearData == 0) { - // keep PUB (qos > 0, aka packetID != 0), PUBREC and PUBREL - // Spec only mentions PUB and PUBREL but this lib implements method B from point 4.3.3 (Fig. 4.3) - // and stores the packet id in the PUBREC packet. So we also must keep PUBREC. - while (it) { - espMqttClientInternals::MQTTPacketType type = it.get()->packet.packetType(); - if (type == PacketType.PUBREC || - type == PacketType.PUBREL || - (type == PacketType.PUBLISH && it.get()->packet.packetId() != 0)) { - ++it; - } else { - _outbox.remove(it); - } - } - } else if (clearData == 1) { - // keep PUB - while (it) { - if (it.get()->packet.packetType() == PacketType.PUBLISH) { - ++it; - } else { - _outbox.remove(it); - } - } - } else { // clearData == 2 - while (it) { - _outbox.remove(it); - } - } -} - -void MqttClient::_onError(uint16_t packetId, espMqttClientTypes::Error error) { - if (_onErrorCallback) { - _onErrorCallback(packetId, error); - } -} diff --git a/lib/espMqttClient/src/MqttClient.h b/lib/espMqttClient/src/MqttClient.h deleted file mode 100644 index eaf9d2d..0000000 --- a/lib/espMqttClient/src/MqttClient.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -API is based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#include -#include - -#include "Helpers.h" -#include "Config.h" -#include "TypeDefs.h" -#include "Logging.h" -#include "Outbox.h" -#include "Packets/Packet.h" -#include "Packets/Parser.h" -#include "Transport/Transport.h" - -class MqttClient { - public: - virtual ~MqttClient(); - bool connected() const; - bool disconnected() const; - bool connect(); - bool disconnect(bool force = false); - template - uint16_t subscribe(const char* topic, uint8_t qos, Args&&... args) { - uint16_t packetId = 0; - if (_state != State::connected) { - 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; - } - EMC_SEMAPHORE_GIVE(); - } - return packetId; - } - template - uint16_t unsubscribe(const char* topic, Args&&... args) { - uint16_t packetId = 0; - if (_state != State::connected) { - 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; - } - EMC_SEMAPHORE_GIVE(); - } - return packetId; - } - uint16_t publish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length); - uint16_t publish(const char* topic, uint8_t qos, bool retain, const char* payload); - uint16_t publish(const char* topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length); - void clearQueue(bool deleteSessionData = false); // Not MQTT compliant and may cause unpredictable results when `deleteSessionData` = true! - const char* getClientId() const; - size_t queueSize(); // No const because of mutex - void loop(); - - protected: - explicit MqttClient(espMqttClientTypes::UseInternalTask useInternalTask, uint8_t priority = 1, uint8_t core = 1); - espMqttClientTypes::UseInternalTask _useInternalTask; - espMqttClientInternals::Transport* _transport; - - espMqttClientTypes::OnConnectCallback _onConnectCallback; - espMqttClientTypes::OnDisconnectCallback _onDisconnectCallback; - espMqttClientTypes::OnSubscribeCallback _onSubscribeCallback; - espMqttClientTypes::OnUnsubscribeCallback _onUnsubscribeCallback; - espMqttClientTypes::OnMessageCallback _onMessageCallback; - espMqttClientTypes::OnPublishCallback _onPublishCallback; - espMqttClientTypes::OnErrorCallback _onErrorCallback; - typedef void(*mqttClientHook)(void*); - const char* _clientId; - IPAddress _ip; - const char* _host; - uint16_t _port; - bool _useIp; - uint32_t _keepAlive; - bool _cleanSession; - const char* _username; - const char* _password; - const char* _willTopic; - const uint8_t* _willPayload; - uint16_t _willPayloadLength; - uint8_t _willQos; - bool _willRetain; - uint32_t _timeout; - - // state is protected to allow state changes by the transport system, defined in child classes - // eg. to allow AsyncTCP - enum class State { - disconnected = 0, - connectingTcp1 = 1, - connectingTcp2 = 2, - connectingMqtt = 3, - connected = 4, - disconnectingMqtt1 = 5, - disconnectingMqtt2 = 6, - disconnectingTcp1 = 7, - disconnectingTcp2 = 8 - }; - std::atomic _state; - inline void _setState(State newState); - - private: - char _generatedClientId[EMC_CLIENTID_LENGTH]; - uint16_t _packetId; - -#if defined(ARDUINO_ARCH_ESP32) - SemaphoreHandle_t _xSemaphore; - TaskHandle_t _taskHandle; - static void _loop(MqttClient* c); -#elif defined(ARDUINO_ARCH_ESP8266) && EMC_ESP8266_MULTITHREADING - std::atomic _xSemaphore = false; -#elif defined(__linux__) - std::mutex mtx; -#endif - - uint8_t _rxBuffer[EMC_RX_BUFFER_SIZE]; - struct OutgoingPacket { - uint32_t timeSent; - espMqttClientInternals::Packet packet; - template - OutgoingPacket(uint32_t t, espMqttClientTypes::Error& error, Args&&... args) : // NOLINT(runtime/references) - timeSent(t), - packet(error, std::forward(args) ...) {} - }; - espMqttClientInternals::Outbox _outbox; - size_t _bytesSent; - espMqttClientInternals::Parser _parser; - uint32_t _lastClientActivity; - uint32_t _lastServerActivity; - bool _pingSent; - espMqttClientTypes::DisconnectReason _disconnectReason; - - uint16_t _getNextPacketId(); - - template - bool _addPacket(Args&&... args) { - espMqttClientTypes::Error error(espMqttClientTypes::Error::SUCCESS); - espMqttClientInternals::Outbox::Iterator it = _outbox.emplace(0, error, std::forward(args) ...); - if (it && error == espMqttClientTypes::Error::SUCCESS) { - return true; - } else { - if (it) _outbox.remove(it); - return false; - } - } - - template - bool _addPacketFront(Args&&... args) { - espMqttClientTypes::Error error(espMqttClientTypes::Error::SUCCESS); - espMqttClientInternals::Outbox::Iterator it = _outbox.emplaceFront(0, error, std::forward(args) ...); - if (it && error == espMqttClientTypes::Error::SUCCESS) { - return true; - } else { - if (it) _outbox.remove(it); - return false; - } - } - - void _checkOutbox(); - int _sendPacket(); - bool _advanceOutbox(); - void _checkIncoming(); - void _checkPing(); - void _checkTimeout(); - - void _onConnack(); - void _onPublish(); - void _onPuback(); - void _onPubrec(); - void _onPubrel(); - void _onPubcomp(); - void _onSuback(); - void _onUnsuback(); - - void _clearQueue(int clearData); // 0: keep session, - // 1: keep only PUBLISH qos > 0 - // 2: delete all - void _onError(uint16_t packetId, espMqttClientTypes::Error error); - - #if defined(ARDUINO_ARCH_ESP32) - #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO - size_t _highWaterMark; - #endif - #endif -}; diff --git a/lib/espMqttClient/src/MqttClientSetup.h b/lib/espMqttClient/src/MqttClientSetup.h deleted file mode 100644 index 4ef7307..0000000 --- a/lib/espMqttClient/src/MqttClientSetup.h +++ /dev/null @@ -1,245 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -API is based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#include "MqttClient.h" - -#if EMC_MULTIPLE_CALLBACKS -#include -#include -#endif - -template -class MqttClientSetup : public MqttClient { - public: - T& setKeepAlive(uint16_t keepAlive) { - _keepAlive = keepAlive * 1000; // s to ms conversion, will also do 16 to 32 bit conversion - return static_cast(*this); - } - - T& setClientId(const char* clientId) { - _clientId = clientId; - return static_cast(*this); - } - - T& setCleanSession(bool cleanSession) { - _cleanSession = cleanSession; - return static_cast(*this); - } - - T& setCredentials(const char* username, const char* password) { - _username = username; - _password = password; - return static_cast(*this); - } - - T& setWill(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length) { - _willTopic = topic; - _willQos = qos; - _willRetain = retain; - _willPayload = payload; - if (!_willPayload) { - _willPayloadLength = 0; - } else { - _willPayloadLength = length; - } - return static_cast(*this); - } - - T& setWill(const char* topic, uint8_t qos, bool retain, const char* payload) { - return setWill(topic, qos, retain, reinterpret_cast(payload), strlen(payload)); - } - - T& setServer(IPAddress ip, uint16_t port) { - _ip = ip; - _port = port; - _useIp = true; - return static_cast(*this); - } - - T& setServer(const char* host, uint16_t port) { - _host = host; - _port = port; - _useIp = false; - return static_cast(*this); - } - - T& setTimeout(uint16_t timeout) { - _timeout = timeout * 1000; // s to ms conversion, will also do 16 to 32 bit conversion - return static_cast(*this); - } - - T& onConnect(espMqttClientTypes::OnConnectCallback callback, uint32_t id = 0) { - #if EMC_MULTIPLE_CALLBACKS - _onConnectCallbacks.emplace_back(callback, id); - #else - (void) id; - _onConnectCallback = callback; - #endif - return static_cast(*this); - } - - T& onDisconnect(espMqttClientTypes::OnDisconnectCallback callback, uint32_t id = 0) { - #if EMC_MULTIPLE_CALLBACKS - _onDisconnectCallbacks.emplace_back(callback, id); - #else - (void) id; - _onDisconnectCallback = callback; - #endif - return static_cast(*this); - } - - T& onSubscribe(espMqttClientTypes::OnSubscribeCallback callback, uint32_t id = 0) { - #if EMC_MULTIPLE_CALLBACKS - _onSubscribeCallbacks.emplace_back(callback, id); - #else - (void) id; - _onSubscribeCallback = callback; - #endif - return static_cast(*this); - } - - T& onUnsubscribe(espMqttClientTypes::OnUnsubscribeCallback callback, uint32_t id = 0) { - #if EMC_MULTIPLE_CALLBACKS - _onUnsubscribeCallbacks.emplace_back(callback, id); - #else - (void) id; - _onUnsubscribeCallback = callback; - #endif - return static_cast(*this); - } - - T& onMessage(espMqttClientTypes::OnMessageCallback callback, uint32_t id = 0) { - #if EMC_MULTIPLE_CALLBACKS - _onMessageCallbacks.emplace_back(callback, id); - #else - (void) id; - _onMessageCallback = callback; - #endif - return static_cast(*this); - } - - T& onPublish(espMqttClientTypes::OnPublishCallback callback, uint32_t id = 0) { - #if EMC_MULTIPLE_CALLBACKS - _onPublishCallbacks.emplace_back(callback, id); - #else - (void) id; - _onPublishCallback = callback; - #endif - return static_cast(*this); - } - - #if EMC_MULTIPLE_CALLBACKS - T& removeOnConnect(uint32_t id) { - for (auto it = _onConnectCallbacks.begin(); it != _onConnectCallbacks.end(); ++it) { - if (it->second == id) { - _onConnectCallbacks.erase(it); - break; - } - } - return static_cast(*this); - } - - T& removeOnDisconnect(uint32_t id) { - for (auto it = _onDisconnectCallbacks.begin(); it != _onDisconnectCallbacks.end(); ++it) { - if (it->second == id) { - _onDisconnectCallbacks.erase(it); - break; - } - } - return static_cast(*this); - } - - T& removeOnSubscribe(uint32_t id) { - for (auto it = _onSubscribeCallbacks.begin(); it != _onSubscribeCallbacks.end(); ++it) { - if (it->second == id) { - _onSubscribeCallbacks.erase(it); - break; - } - } - return static_cast(*this); - } - - T& removeOnUnsubscribe(uint32_t id) { - for (auto it = _onUnsubscribeCallbacks.begin(); it != _onUnsubscribeCallbacks.end(); ++it) { - if (it->second == id) { - _onUnsubscribeCallbacks.erase(it); - break; - } - } - return static_cast(*this); - } - - T& removeOnMessage(uint32_t id) { - for (auto it = _onMessageCallbacks.begin(); it != _onMessageCallbacks.end(); ++it) { - if (it->second == id) { - _onMessageCallbacks.erase(it); - break; - } - } - return static_cast(*this); - } - - T& removeOnPublish(uint32_t id) { - for (auto it = _onPublishCallbacks.begin(); it != _onPublishCallbacks.end(); ++it) { - if (it->second == id) { - _onPublishCallbacks.erase(it); - break; - } - } - return static_cast(*this); - } - #endif - - /* - T& onError(espMqttClientTypes::OnErrorCallback callback) { - _onErrorCallback = callback; - return static_cast(*this); - } - */ - - protected: - explicit MqttClientSetup(espMqttClientTypes::UseInternalTask useInternalTask, uint8_t priority = 1, uint8_t core = 1) - : MqttClient(useInternalTask, priority, core) { - #if EMC_MULTIPLE_CALLBACKS - _onConnectCallback = [this](bool sessionPresent) { - for (auto callback : _onConnectCallbacks) if (callback.first) callback.first(sessionPresent); - }; - _onDisconnectCallback = [this](espMqttClientTypes::DisconnectReason reason) { - for (auto callback : _onDisconnectCallbacks) if (callback.first) callback.first(reason); - }; - _onSubscribeCallback = [this](uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* returncodes, size_t len) { - for (auto callback : _onSubscribeCallbacks) if (callback.first) callback.first(packetId, returncodes, len); - }; - _onUnsubscribeCallback = [this](int16_t packetId) { - for (auto callback : _onUnsubscribeCallbacks) if (callback.first) callback.first(packetId); - }; - _onMessageCallback = [this](const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) { - for (auto callback : _onMessageCallbacks) if (callback.first) callback.first(properties, topic, payload, len, index, total); - }; - _onPublishCallback = [this](uint16_t packetId) { - for (auto callback : _onPublishCallbacks) if (callback.first) callback.first(packetId); - }; - #else - // empty - #endif - } - - #if EMC_MULTIPLE_CALLBACKS - std::list> _onConnectCallbacks; - std::list> _onDisconnectCallbacks; - std::list> _onSubscribeCallbacks; - std::list> _onUnsubscribeCallbacks; - std::list> _onMessageCallbacks; - std::list> _onPublishCallbacks; - #endif -}; diff --git a/lib/espMqttClient/src/Outbox.h b/lib/espMqttClient/src/Outbox.h deleted file mode 100644 index 4f9971c..0000000 --- a/lib/espMqttClient/src/Outbox.h +++ /dev/null @@ -1,255 +0,0 @@ - -/* -Copyright (c) 2022 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 - -#if EMC_USE_MEMPOOL - #include "MemoryPool/src/MemoryPool.h" - #include "Config.h" -#else - #include // new (std::nothrow) -#endif -#include // std::forward - -namespace espMqttClientInternals { - -/** - * @brief Singly linked queue with builtin non-invalidating forward iterator - * - * Queue items can only be emplaced, at front and back of the queue. - * Remove items using an iterator or the builtin iterator. - */ - -template -class Outbox { - public: - Outbox() - : _first(nullptr) - , _last(nullptr) - , _current(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; - } - } - - struct Node { - public: - template - explicit Node(Args&&... args) - : data(std::forward(args) ...) - , next(nullptr) { - // empty - } - - T data; - Node* next; - }; - - class Iterator { - friend class Outbox; - public: - void operator++() { - if (_node) { - _prev = _node; - _node = _node->next; - } - } - - explicit operator bool() const { - if (_node) return true; - return false; - } - - T* get() const { - if (_node) return &(_node->data); - return nullptr; - } - - private: - Node* _node = nullptr; - Node* _prev = nullptr; - }; - - // add node to back, advance current to new if applicable - template - Iterator emplace(Args&&... args) { - Iterator it; - #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 - _first = _current = node; - } else { - // queue has at least one item - _last->next = node; - it._prev = _last; - } - _last = node; - it._node = node; - // point current to newly created if applicable - if (!_current) { - _current = _last; - } - } - return it; - } - - // add item to front, current points to newly created front. - template - Iterator emplaceFront(Args&&... args) { - Iterator it; - #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 - _last = node; - } else { - // queue has at least one item - node->next = _first; - } - _current = _first = node; - _prev = nullptr; - it._node = node; - } - return it; - } - - // remove node at iterator, iterator points to next - void remove(Iterator& it) { // NOLINT(runtime/references) - if (!it) return; - Node* node = it._node; - Node* prev = it._prev; - ++it; - _remove(prev, node); - } - - // remove current node, current points to next - void removeCurrent() { - _remove(_prev, _current); - } - - // Get current item or return nullptr - T* getCurrent() const { - if (_current) return &(_current->data); - return nullptr; - } - - void resetCurrent() { - _current = _first; - } - - Iterator front() const { - Iterator it; - it._node = _first; - return it; - } - - // Advance current item - void next() { - if (_current) { - _prev = _current; - _current = _current->next; - } - } - - // Outbox is empty - bool empty() { - if (!_first) return true; - return false; - } - - size_t size() const { - Node* n = _first; - size_t count = 0; - while (n) { - n = n->next; - ++count; - } - return count; - } - - private: - Node* _first; - 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; - - // set current to next, node->next may be nullptr - if (_current == node) { - _current = node->next; - } - - if (_prev == node) { - _prev = prev; - } - - // only one element in outbox - if (_first == _last) { - _first = _last = nullptr; - - // delete first el in longer outbox - } else if (_first == node) { - _first = node->next; - - // delete last in longer outbox - } else if (_last == node) { - _last = prev; - _last->next = nullptr; - - // delete somewhere in the middle - } else { - prev->next = node->next; - } - - // finally, delete the node - #if EMC_USE_MEMPOOL - node->~Node(); - _memPool.free(node); - #else - delete node; - #endif - } -}; - -} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/Constants.h b/lib/espMqttClient/src/Packets/Constants.h deleted file mode 100644 index ee92e31..0000000 --- a/lib/espMqttClient/src/Packets/Constants.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -Parts are based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#include - -namespace espMqttClientInternals { - -constexpr const char PROTOCOL[] = "MQTT"; -constexpr const uint8_t PROTOCOL_LEVEL = 0b00000100; - -typedef uint8_t MQTTPacketType; - -constexpr struct { - const uint8_t RESERVED1 = 0; - const uint8_t CONNECT = 1 << 4; - const uint8_t CONNACK = 2 << 4; - const uint8_t PUBLISH = 3 << 4; - const uint8_t PUBACK = 4 << 4; - const uint8_t PUBREC = 5 << 4; - const uint8_t PUBREL = 6 << 4; - const uint8_t PUBCOMP = 7 << 4; - const uint8_t SUBSCRIBE = 8 << 4; - const uint8_t SUBACK = 9 << 4; - const uint8_t UNSUBSCRIBE = 10 << 4; - const uint8_t UNSUBACK = 11 << 4; - const uint8_t PINGREQ = 12 << 4; - const uint8_t PINGRESP = 13 << 4; - const uint8_t DISCONNECT = 14 << 4; - const uint8_t RESERVED2 = 1 << 4; -} PacketType; - -constexpr struct { - const uint8_t CONNECT_RESERVED = 0x00; - const uint8_t CONNACK_RESERVED = 0x00; - const uint8_t PUBLISH_DUP = 0x08; - const uint8_t PUBLISH_QOS0 = 0x00; - const uint8_t PUBLISH_QOS1 = 0x02; - const uint8_t PUBLISH_QOS2 = 0x04; - const uint8_t PUBLISH_QOSRESERVED = 0x06; - const uint8_t PUBLISH_RETAIN = 0x01; - const uint8_t PUBACK_RESERVED = 0x00; - const uint8_t PUBREC_RESERVED = 0x00; - const uint8_t PUBREL_RESERVED = 0x02; - const uint8_t PUBCOMP_RESERVED = 0x00; - const uint8_t SUBSCRIBE_RESERVED = 0x02; - const uint8_t SUBACK_RESERVED = 0x00; - const uint8_t UNSUBSCRIBE_RESERVED = 0x02; - const uint8_t UNSUBACK_RESERVED = 0x00; - const uint8_t PINGREQ_RESERVED = 0x00; - const uint8_t PINGRESP_RESERVED = 0x00; - const uint8_t DISCONNECT_RESERVED = 0x00; - const uint8_t RESERVED2_RESERVED = 0x00; -} HeaderFlag; - -constexpr struct { - const uint8_t USERNAME = 0x80; - const uint8_t PASSWORD = 0x40; - const uint8_t WILL_RETAIN = 0x20; - const uint8_t WILL_QOS0 = 0x00; - const uint8_t WILL_QOS1 = 0x08; - const uint8_t WILL_QOS2 = 0x10; - const uint8_t WILL = 0x04; - const uint8_t CLEAN_SESSION = 0x02; - const uint8_t RESERVED = 0x00; -} ConnectFlag; - -} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/Packet.cpp b/lib/espMqttClient/src/Packets/Packet.cpp deleted file mode 100644 index 14d241b..0000000 --- a/lib/espMqttClient/src/Packets/Packet.cpp +++ /dev/null @@ -1,454 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "Packet.h" - -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) { - if (index >= _size) return 0; - if (!_getPayload) return _size - index; - return _chunkedAvailable(index); -} - -const uint8_t* Packet::data(size_t index) const { - if (!_getPayload) { - if (!_data) return nullptr; - if (index >= _size) return nullptr; - return &_data[index]; - } - return _chunkedData(index); -} - -size_t Packet::size() const { - return _size; -} - -void Packet::setDup() { - if (!_data) return; - if (packetType() != PacketType.PUBLISH) return; - if (_packetId == 0) return; - _data[0] |= 0x08; -} - -uint16_t Packet::packetId() const { - return _packetId; -} - -MQTTPacketType Packet::packetType() const { - if (_data) return static_cast(_data[0] & 0xF0); - return static_cast(0); -} - -bool Packet::removable() const { - if (_packetId == 0) return true; - if ((packetType() == PacketType.PUBACK) || (packetType() == PacketType.PUBCOMP)) return true; - return false; -} - -Packet::Packet(espMqttClientTypes::Error& error, - bool cleanSession, - const char* username, - const char* password, - const char* willTopic, - bool willRetain, - uint8_t willQos, - const uint8_t* willPayload, - uint16_t willPayloadLength, - uint16_t keepAlive, - const char* clientId) -: _packetId(0) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(nullptr) { - if (willPayload && willPayloadLength == 0) { - size_t length = strlen(reinterpret_cast(willPayload)); - if (length > UINT16_MAX) { - emc_log_w("Payload length truncated (l:%zu)", length); - willPayloadLength = UINT16_MAX; - } else { - willPayloadLength = length; - } - } - if (!clientId || strlen(clientId) == 0) { - emc_log_w("clientId not set error"); - error = espMqttClientTypes::Error::MALFORMED_PARAMETER; - return; - } - - // Calculate size - size_t remainingLength = - 6 + // protocol - 1 + // protocol level - 1 + // connect flags - 2 + // keepalive - 2 + strlen(clientId) + - (willTopic ? 2 + strlen(willTopic) + 2 + willPayloadLength : 0) + - (username ? 2 + strlen(username) : 0) + - (password ? 2 + strlen(password) : 0); - - // allocate memory - if (!_allocate(remainingLength, false)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - // serialize - size_t pos = 0; - - // FIXED HEADER - _data[pos++] = PacketType.CONNECT | HeaderFlag.CONNECT_RESERVED; - pos += encodeRemainingLength(remainingLength, &_data[pos]); - pos += encodeString(PROTOCOL, &_data[pos]); - _data[pos++] = PROTOCOL_LEVEL; - uint8_t connectFlags = 0; - if (cleanSession) connectFlags |= espMqttClientInternals::ConnectFlag.CLEAN_SESSION; - if (username != nullptr) connectFlags |= espMqttClientInternals::ConnectFlag.USERNAME; - if (password != nullptr) connectFlags |= espMqttClientInternals::ConnectFlag.PASSWORD; - if (willTopic != nullptr) { - connectFlags |= espMqttClientInternals::ConnectFlag.WILL; - if (willRetain) connectFlags |= espMqttClientInternals::ConnectFlag.WILL_RETAIN; - switch (willQos) { - case 0: - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS0; - break; - case 1: - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS1; - break; - case 2: - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS2; - break; - } - } - _data[pos++] = connectFlags; - _data[pos++] = keepAlive >> 8; - _data[pos++] = keepAlive & 0xFF; - - // PAYLOAD - // client ID - pos += encodeString(clientId, &_data[pos]); - // will - if (willTopic != nullptr && willPayload != nullptr) { - pos += encodeString(willTopic, &_data[pos]); - _data[pos++] = willPayloadLength >> 8; - _data[pos++] = willPayloadLength & 0xFF; - memcpy(&_data[pos], willPayload, willPayloadLength); - pos += willPayloadLength; - } - // credentials - if (username != nullptr) pos += encodeString(username, &_data[pos]); - if (password != nullptr) encodeString(password, &_data[pos]); - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error& error, - uint16_t packetId, - const char* topic, - const uint8_t* payload, - size_t payloadLength, - uint8_t qos, - bool retain) -: _packetId(packetId) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(nullptr) { - size_t remainingLength = - 2 + strlen(topic) + // topic length + topic - 2 + // packet ID - payloadLength; - - if (qos == 0) { - remainingLength -= 2; - _packetId = 0; - } - - if (!_allocate(remainingLength, true)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - size_t pos = _fillPublishHeader(packetId, topic, remainingLength, qos, retain); - - // PAYLOAD - memcpy(&_data[pos], payload, payloadLength); - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error& error, - uint16_t packetId, - const char* topic, - espMqttClientTypes::PayloadCallback payloadCallback, - size_t payloadLength, - uint8_t qos, - bool retain) -: _packetId(packetId) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(payloadCallback) { - size_t remainingLength = - 2 + strlen(topic) + // topic length + topic - 2 + // packet ID - payloadLength; - - if (qos == 0) { - remainingLength -= 2; - _packetId = 0; - } - - if (!_allocate(remainingLength - payloadLength + std::min(payloadLength, static_cast(EMC_RX_BUFFER_SIZE)), true)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - size_t pos = _fillPublishHeader(packetId, topic, remainingLength, qos, retain); - - // payload will be added by 'Packet::available' - _size = pos + payloadLength; - _payloadIndex = pos; - _payloadStartIndex = _payloadIndex; - _payloadEndIndex = _payloadIndex; - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error& error, uint16_t packetId, const char* topic, uint8_t qos) -: _packetId(packetId) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(nullptr) { - SubscribeItem list[1] = {topic, qos}; - _createSubscribe(error, list, 1); -} - -Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type, uint16_t packetId) -: _packetId(packetId) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(nullptr) { - if (!_allocate(2, true)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - size_t pos = 0; - _data[pos] = type; - if (type == PacketType.PUBREL) { - _data[pos++] |= HeaderFlag.PUBREL_RESERVED; - } else { - pos++; - } - pos += encodeRemainingLength(2, &_data[pos]); - _data[pos++] = packetId >> 8; - _data[pos] = packetId & 0xFF; - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error& error, uint16_t packetId, const char* topic) -: _packetId(packetId) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(nullptr) { - const char* list[1] = {topic}; - _createUnsubscribe(error, list, 1); -} - -Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type) -: _packetId(0) -, _data(nullptr) -, _size(0) -, _payloadIndex(0) -, _payloadStartIndex(0) -, _payloadEndIndex(0) -, _getPayload(nullptr) { - if (!_allocate(0, true)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - _data[0] |= type; - - error = espMqttClientTypes::Error::SUCCESS; -} - - -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); - return false; - } - emc_log_i("Alloc (l:%zu)", _size); - memset(_data, 0, _size); - return true; -} - -size_t Packet::_fillPublishHeader(uint16_t packetId, - const char* topic, - size_t remainingLength, - uint8_t qos, - bool retain) { - size_t index = 0; - - // FIXED HEADER - _data[index] = PacketType.PUBLISH; - if (retain) _data[index] |= HeaderFlag.PUBLISH_RETAIN; - if (qos == 0) { - _data[index++] |= HeaderFlag.PUBLISH_QOS0; - } else if (qos == 1) { - _data[index++] |= HeaderFlag.PUBLISH_QOS1; - } else if (qos == 2) { - _data[index++] |= HeaderFlag.PUBLISH_QOS2; - } - index += encodeRemainingLength(remainingLength, &_data[index]); - - // VARIABLE HEADER - index += encodeString(topic, &_data[index]); - if (qos > 0) { - _data[index++] = packetId >> 8; - _data[index++] = packetId & 0xFF; - } - - return index; -} - -void Packet::_createSubscribe(espMqttClientTypes::Error& error, - SubscribeItem* list, - size_t numberTopics) { - // Calculate size - size_t payload = 0; - for (size_t i = 0; i < numberTopics; ++i) { - payload += 2 + strlen(list[i].topic) + 1; // length bytes, string, qos - } - size_t remainingLength = 2 + payload; // packetId + payload - - // allocate memory - if (!_allocate(remainingLength, true)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - // serialize - size_t pos = 0; - _data[pos++] = PacketType.SUBSCRIBE | HeaderFlag.SUBSCRIBE_RESERVED; - pos += encodeRemainingLength(remainingLength, &_data[pos]); - _data[pos++] = _packetId >> 8; - _data[pos++] = _packetId & 0xFF; - for (size_t i = 0; i < numberTopics; ++i) { - pos += encodeString(list[i].topic, &_data[pos]); - _data[pos++] = list[i].qos; - } - - error = espMqttClientTypes::Error::SUCCESS; -} - -void Packet::_createUnsubscribe(espMqttClientTypes::Error& error, - const char** list, - size_t numberTopics) { - // Calculate size - size_t payload = 0; - for (size_t i = 0; i < numberTopics; ++i) { - payload += 2 + strlen(list[i]); // length bytes, string - } - size_t remainingLength = 2 + payload; // packetId + payload - - // allocate memory - if (!_allocate(remainingLength, true)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - // serialize - size_t pos = 0; - _data[pos++] = PacketType.UNSUBSCRIBE | HeaderFlag.UNSUBSCRIBE_RESERVED; - pos += encodeRemainingLength(remainingLength, &_data[pos]); - _data[pos++] = _packetId >> 8; - _data[pos++] = _packetId & 0xFF; - for (size_t i = 0; i < numberTopics; ++i) { - pos += encodeString(list[i], &_data[pos]); - } - - error = espMqttClientTypes::Error::SUCCESS; -} - -size_t Packet::_chunkedAvailable(size_t index) { - // index vs size check done in 'available(index)' - - // index points to header or first payload byte - if (index < _payloadIndex) { - if (_size > _payloadIndex && _payloadEndIndex != 0) { - size_t copied = _getPayload(&_data[_payloadIndex], std::min(static_cast(EMC_TX_BUFFER_SIZE), _size - _payloadStartIndex), index); - _payloadStartIndex = _payloadIndex; - _payloadEndIndex = _payloadStartIndex + copied - 1; - } - - // index points to payload unavailable - } else if (index > _payloadEndIndex || _payloadStartIndex > index) { - _payloadStartIndex = index; - size_t copied = _getPayload(&_data[_payloadIndex], std::min(static_cast(EMC_TX_BUFFER_SIZE), _size - _payloadStartIndex), index); - _payloadEndIndex = _payloadStartIndex + copied - 1; - } - - // now index points to header or payload available - return _payloadEndIndex - index + 1; -} - -const uint8_t* Packet::_chunkedData(size_t index) const { - // CAUTION!! available(index) has to be called first to check available data and possibly fill payloadbuffer - if (index < _payloadIndex) { - return &_data[index]; - } - return &_data[index - _payloadStartIndex + _payloadIndex]; -} - -} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/Packet.h b/lib/espMqttClient/src/Packets/Packet.h deleted file mode 100644 index 5d0b67b..0000000 --- a/lib/espMqttClient/src/Packets/Packet.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -Copyright (c) 2022 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 -#include - -#include "Constants.h" -#include "../Config.h" -#include "../TypeDefs.h" -#include "../Helpers.h" -#include "../Logging.h" -#include "RemainingLength.h" -#include "StringUtil.h" - -#if EMC_USE_MEMPOOL - #include "MemoryPool/src/MemoryPool.h" -#endif - -namespace espMqttClientInternals { - -class Packet { - public: - ~Packet(); - size_t available(size_t index); - const uint8_t* data(size_t index) const; - - size_t size() const; - void setDup(); - uint16_t packetId() const; - MQTTPacketType packetType() const; - bool removable() const; - - protected: - uint16_t _packetId; // save as separate variable: will be accessed frequently - uint8_t* _data; - size_t _size; - - // variables for chunked payload handling - size_t _payloadIndex; - size_t _payloadStartIndex; - size_t _payloadEndIndex; - espMqttClientTypes::PayloadCallback _getPayload; - - struct SubscribeItem { - const char* topic; - uint8_t qos; - }; - - public: - // CONNECT - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - bool cleanSession, - const char* username, - const char* password, - const char* willTopic, - bool willRetain, - uint8_t willQos, - const uint8_t* willPayload, - uint16_t willPayloadLength, - uint16_t keepAlive, - const char* clientId); - // PUBLISH - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - uint16_t packetId, - const char* topic, - const uint8_t* payload, - size_t payloadLength, - uint8_t qos, - bool retain); - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - uint16_t packetId, - const char* topic, - espMqttClientTypes::PayloadCallback payloadCallback, - size_t payloadLength, - uint8_t qos, - bool retain); - // SUBSCRIBE - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - uint16_t packetId, - const char* topic, - uint8_t qos); - template - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - uint16_t packetId, - const char* topic1, - uint8_t qos1, - const char* topic2, - uint8_t qos2, - Args&& ... args) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - static_assert(sizeof...(Args) % 2 == 0, "Subscribe should be in topic/qos pairs"); - size_t numberTopics = 2 + (sizeof...(Args) / 2); - SubscribeItem list[numberTopics] = {topic1, qos1, topic2, qos2, args...}; - _createSubscribe(error, list, numberTopics); - } - // UNSUBSCRIBE - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - uint16_t packetId, - const char* topic); - template - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - uint16_t packetId, - const char* topic1, - const char* topic2, - Args&& ... args) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - size_t numberTopics = 2 + sizeof...(Args); - const char* list[numberTopics] = {topic1, topic2, args...}; - _createUnsubscribe(error, list, numberTopics); - } - // PUBACK, PUBREC, PUBREL, PUBCOMP - Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - MQTTPacketType type, - uint16_t packetId); - // PING, DISCONN - explicit Packet(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - MQTTPacketType type); - - private: - // pass remainingLength = total size - header - remainingLengthLength! - bool _allocate(size_t remainingLength, bool check); - - // fills header and returns index of next available byte in buffer - size_t _fillPublishHeader(uint16_t packetId, - const char* topic, - size_t remainingLength, - uint8_t qos, - bool retain); - void _createSubscribe(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - SubscribeItem* list, - size_t numberTopics); - void _createUnsubscribe(espMqttClientTypes::Error& error, // NOLINT(runtime/references) - const char** list, - size_t numberTopics); - - 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/src/Packets/Parser.cpp b/lib/espMqttClient/src/Packets/Parser.cpp deleted file mode 100644 index 07998a3..0000000 --- a/lib/espMqttClient/src/Packets/Parser.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "Parser.h" - -namespace espMqttClientInternals { - -uint8_t IncomingPacket::qos() const { - if ((fixedHeader.packetType & 0xF0) != PacketType.PUBLISH) return 0; - return (fixedHeader.packetType & 0x06) >> 1; // mask 0x00000110 -} - -bool IncomingPacket::retain() const { - if ((fixedHeader.packetType & 0xF0) != PacketType.PUBLISH) return 0; - return fixedHeader.packetType & 0x01; // mask 0x00000001 -} - -bool IncomingPacket::dup() const { - if ((fixedHeader.packetType & 0xF0) != PacketType.PUBLISH) return 0; - return fixedHeader.packetType & 0x08; // mask 0x00001000 -} - -void IncomingPacket::reset() { - fixedHeader.packetType = 0; - variableHeader.topicLength = 0; - variableHeader.fixed.packetId = 0; - payload.index = 0; - payload.length = 0; -} - -Parser::Parser() -: _data(nullptr) -, _len(0) -, _bytesRead(0) -, _bytePos(0) -, _parse(_fixedHeader) -, _packet() -, _payloadBuffer{0} { - // empty -} - -ParserResult Parser::parse(const uint8_t* data, size_t len, size_t* bytesRead) { - _data = data; - _len = len; - _bytesRead = 0; - ParserResult result = ParserResult::awaitData; - while (result == ParserResult::awaitData && _bytesRead < _len) { - result = _parse(this); - ++_bytesRead; - } - (*bytesRead) += _bytesRead; - return result; -} - -const IncomingPacket& Parser::getPacket() const { - return _packet; -} - -void Parser::reset() { - _parse = _fixedHeader; - _bytesRead = 0; - _bytePos = 0; - _packet.reset(); -} - -ParserResult Parser::_fixedHeader(Parser* p) { - p->_packet.reset(); - p->_packet.fixedHeader.packetType = p->_data[p->_bytesRead]; - - // keep PUBLISH out of the switch and handle in separate if/else - if ((p->_packet.fixedHeader.packetType & 0xF0) == PacketType.PUBLISH) { - uint8_t headerFlags = p->_packet.fixedHeader.packetType & 0x0F; - /* flags can be: 0b0000 --> no dup, qos 0, no retain - 0x0001 --> no dup, qos 0, retain - 0x0010 --> no dup, qos 1, no retain - 0x0011 --> no dup, qos 1, retain - 0x0100 --> no dup, qos 2, no retain - 0x0101 --> no dup, qos 2, retain - 0x1010 --> dup, qos 1, no retain - 0x1011 --> dup, qos 1, retain - 0x1100 --> dup, qos 2, no retain - 0x1101 --> dup, qos 2, retain - */ - if (headerFlags <= 0x05 || headerFlags >= 0x0A) { - p->_parse = _remainingLengthVariable; - p->_bytePos = 0; - } else { - emc_log_w("Invalid packet header: 0x%02x", p->_packet.fixedHeader.packetType); - return ParserResult::protocolError; - } - } else { - switch (p->_packet.fixedHeader.packetType) { - case PacketType.CONNACK | HeaderFlag.CONNACK_RESERVED: - case PacketType.PUBACK | HeaderFlag.PUBACK_RESERVED: - case PacketType.PUBREC | HeaderFlag.PUBREC_RESERVED: - case PacketType.PUBREL | HeaderFlag.PUBREL_RESERVED: - case PacketType.PUBCOMP | HeaderFlag.PUBCOMP_RESERVED: - case PacketType.UNSUBACK | HeaderFlag.UNSUBACK_RESERVED: - p->_parse = _remainingLengthFixed; - break; - case PacketType.SUBACK | HeaderFlag.SUBACK_RESERVED: - p->_parse = _remainingLengthVariable; - p->_bytePos = 0; - break; - case PacketType.PINGRESP | HeaderFlag.PINGRESP_RESERVED: - p->_parse = _remainingLengthNone; - break; - default: - emc_log_w("Invalid packet header: 0x%02x", p->_packet.fixedHeader.packetType); - return ParserResult::protocolError; - } - } - emc_log_i("Packet type: 0x%02x", p->_packet.fixedHeader.packetType); - return ParserResult::awaitData; -} - -ParserResult Parser::_remainingLengthFixed(Parser* p) { - p->_packet.fixedHeader.remainingLength.remainingLength = p->_data[p->_bytesRead]; - - if (p->_packet.fixedHeader.remainingLength.remainingLength == 2) { // variable header is 2 bytes long - if ((p->_packet.fixedHeader.packetType & 0xF0) != PacketType.CONNACK) { - p->_parse = _varHeaderPacketId1; - } else { - p->_parse = _varHeaderConnack1; - } - emc_log_i("Remaining length: %zu", p->_packet.fixedHeader.remainingLength.remainingLength); - return ParserResult::awaitData; - } - p->_parse = _fixedHeader; - emc_log_w("Invalid remaining length (fixed): %zu", p->_packet.fixedHeader.remainingLength.remainingLength); - return ParserResult::protocolError; -} - -ParserResult Parser::_remainingLengthVariable(Parser* p) { - p->_packet.fixedHeader.remainingLength.remainingLengthRaw[p->_bytePos] = p->_data[p->_bytesRead]; - if (p->_packet.fixedHeader.remainingLength.remainingLengthRaw[p->_bytePos] & 0x80) { - p->_bytePos++; - if (p->_bytePos == 4) { - emc_log_w("Invalid remaining length (variable)"); - return ParserResult::protocolError; - } else { - return ParserResult::awaitData; - } - } - - // no need to check for negative decoded length, check is already done - p->_packet.fixedHeader.remainingLength.remainingLength = decodeRemainingLength(p->_packet.fixedHeader.remainingLength.remainingLengthRaw); - - if ((p->_packet.fixedHeader.packetType & 0xF0) == PacketType.PUBLISH) { - p->_parse = _varHeaderTopicLength1; - emc_log_i("Remaining length: %zu", p->_packet.fixedHeader.remainingLength.remainingLength); - return ParserResult::awaitData; - } else { - int32_t payloadSize = p->_packet.fixedHeader.remainingLength.remainingLength - 2; // total - packet ID - if (0 < payloadSize && payloadSize < EMC_PAYLOAD_BUFFER_SIZE) { - p->_bytePos = 0; - p->_packet.payload.data = p->_payloadBuffer; - p->_packet.payload.index = 0; - p->_packet.payload.length = payloadSize; - p->_packet.payload.total = payloadSize; - p->_parse = _varHeaderPacketId1; - emc_log_i("Remaining length: %zu", p->_packet.fixedHeader.remainingLength.remainingLength); - return ParserResult::awaitData; - } else { - emc_log_w("Invalid payload length"); - } - } - p->_parse = _fixedHeader; - return ParserResult::protocolError; -} - -ParserResult Parser::_remainingLengthNone(Parser* p) { - p->_packet.fixedHeader.remainingLength.remainingLength = p->_data[p->_bytesRead]; - p->_parse = _fixedHeader; - if (p->_packet.fixedHeader.remainingLength.remainingLength == 0) { - emc_log_i("Remaining length: %zu", p->_packet.fixedHeader.remainingLength.remainingLength); - return ParserResult::packet; - } - emc_log_w("Invalid remaining length (none)"); - return ParserResult::protocolError; -} - -ParserResult Parser::_varHeaderConnack1(Parser* p) { - uint8_t data = p->_data[p->_bytesRead]; - if (data < 2) { // session present flag: equal to 0 or 1 - p->_packet.variableHeader.fixed.connackVarHeader.sessionPresent = data; - p->_parse = _varHeaderConnack2; - return ParserResult::awaitData; - } - p->_parse = _fixedHeader; - emc_log_w("Invalid session flags"); - return ParserResult::protocolError; -} - -ParserResult Parser::_varHeaderConnack2(Parser* p) { - uint8_t data = p->_data[p->_bytesRead]; - p->_parse = _fixedHeader; - if (data <= 5) { // connect return code max is 5 - p->_packet.variableHeader.fixed.connackVarHeader.returnCode = data; - emc_log_i("Packet complete"); - return ParserResult::packet; - } - emc_log_w("Invalid connack return code"); - return ParserResult::protocolError; -} - -ParserResult Parser::_varHeaderPacketId1(Parser* p) { - p->_packet.variableHeader.fixed.packetId |= p->_data[p->_bytesRead] << 8; - p->_parse = _varHeaderPacketId2; - return ParserResult::awaitData; -} - -ParserResult Parser::_varHeaderPacketId2(Parser* p) { - p->_packet.variableHeader.fixed.packetId |= p->_data[p->_bytesRead]; - p->_parse = _fixedHeader; - if (p->_packet.variableHeader.fixed.packetId != 0) { - emc_log_i("Packet variable header complete"); - if ((p->_packet.fixedHeader.packetType & 0xF0) == PacketType.SUBACK) { - p->_parse = _payloadSuback; - return ParserResult::awaitData; - } else if ((p->_packet.fixedHeader.packetType & 0xF0) == PacketType.PUBLISH) { - p->_packet.payload.total -= 2; // substract packet id length from payload - if (p->_packet.payload.total == 0) { - p->_parse = _fixedHeader; - return ParserResult::packet; - } else { - p->_parse = _payloadPublish; - } - return ParserResult::awaitData; - } else { - return ParserResult::packet; - } - } else { - emc_log_w("Invalid packet id"); - return ParserResult::protocolError; - } -} - -ParserResult Parser::_varHeaderTopicLength1(Parser* p) { - p->_packet.variableHeader.topicLength = p->_data[p->_bytesRead] << 8; - p->_parse = _varHeaderTopicLength2; - return ParserResult::awaitData; -} - -ParserResult Parser::_varHeaderTopicLength2(Parser* p) { - p->_packet.variableHeader.topicLength |= p->_data[p->_bytesRead]; - size_t maxTopicLength = - p->_packet.fixedHeader.remainingLength.remainingLength - - 2 // topic length bytes - - ((p->_packet.fixedHeader.packetType & (HeaderFlag.PUBLISH_QOS1 | HeaderFlag.PUBLISH_QOS2)) ? 2 : 0); - if (p->_packet.variableHeader.topicLength <= maxTopicLength) { - p->_parse = _varHeaderTopic; - p->_bytePos = 0; - p->_packet.payload.total = p->_packet.fixedHeader.remainingLength.remainingLength - 2 - p->_packet.variableHeader.topicLength; - return ParserResult::awaitData; - } - emc_log_w("Invalid topic length: %u > %zu", p->_packet.variableHeader.topicLength, maxTopicLength); - p->_parse = _fixedHeader; - return ParserResult::protocolError; -} - -ParserResult Parser::_varHeaderTopic(Parser* p) { - // no checking for character [MQTT-3.3.2-1] [MQTT-3.3.2-2] - p->_packet.variableHeader.topic[p->_bytePos] = static_cast(p->_data[p->_bytesRead]); - p->_bytePos++; - if (p->_bytePos == p->_packet.variableHeader.topicLength || p->_bytePos == EMC_MAX_TOPIC_LENGTH) { - p->_packet.variableHeader.topic[p->_bytePos] = 0x00; // add c-string delimiter - emc_log_i("Packet variable header topic complete"); - if (p->_packet.fixedHeader.packetType & (HeaderFlag.PUBLISH_QOS1 | HeaderFlag.PUBLISH_QOS2)) { - p->_parse = _varHeaderPacketId1; - } else if (p->_packet.payload.total == 0) { - p->_parse = _fixedHeader; - return ParserResult::packet; - } else { - p->_parse = _payloadPublish; - } - } - return ParserResult::awaitData; -} - -ParserResult Parser::_payloadSuback(Parser* p) { - uint8_t data = p->_data[p->_bytesRead]; - if (data < 0x03 || data == 0x80) { - p->_payloadBuffer[p->_bytePos] = data; - p->_bytePos++; - } else { - p->_parse = _fixedHeader; - emc_log_w("Invalid suback return code"); - return ParserResult::protocolError; - } - if (p->_bytePos == p->_packet.payload.total) { - p->_parse = _fixedHeader; - emc_log_i("Packet complete"); - return ParserResult::packet; - } - return ParserResult::awaitData; -} - -ParserResult Parser::_payloadPublish(Parser* p) { - p->_packet.payload.index += p->_packet.payload.length; - p->_packet.payload.data = &p->_data[p->_bytesRead]; - emc_log_i("payload: index %zu, total %zu, avail %zu/%zu", p->_packet.payload.index, p->_packet.payload.total, p->_len - p->_bytesRead, p->_len); - p->_packet.payload.length = std::min(p->_len - p->_bytesRead, p->_packet.payload.total - p->_packet.payload.index); - p->_bytesRead += p->_packet.payload.length - 1; // compensate for increment in _parse-loop - if (p->_packet.payload.index + p->_packet.payload.length == p->_packet.payload.total) { - p->_parse = _fixedHeader; - } - return ParserResult::packet; -} - -} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/Parser.h b/lib/espMqttClient/src/Packets/Parser.h deleted file mode 100644 index 2f6334e..0000000 --- a/lib/espMqttClient/src/Packets/Parser.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright (c) 2022 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 -#include -#include - -#include "../Config.h" -#include "Constants.h" -#include "../Logging.h" -#include "RemainingLength.h" - -namespace espMqttClientInternals { - -struct IncomingPacket { - struct __attribute__((__packed__)) { - MQTTPacketType packetType; - union { - size_t remainingLength; - uint8_t remainingLengthRaw[4]; - } remainingLength; - } fixedHeader; - struct __attribute__((__packed__)) { - uint16_t topicLength; - char topic[EMC_MAX_TOPIC_LENGTH + 1]; // + 1 for c-string delimiter - union { - struct { - uint8_t sessionPresent; - uint8_t returnCode; - } connackVarHeader; - uint16_t packetId; - } fixed; - } variableHeader; - struct { - const uint8_t* data; - size_t length; - size_t index; - size_t total; - } payload; - - uint8_t qos() const; - bool retain() const; - bool dup() const; - void reset(); -}; - -enum class ParserResult : uint8_t { - awaitData, - packet, - protocolError -}; - -class Parser; -typedef ParserResult(*ParserFunc)(Parser*); - -class Parser { - public: - Parser(); - ParserResult parse(const uint8_t* data, size_t len, size_t* bytesRead); - const IncomingPacket& getPacket() const; - void reset(); - - private: - // keep data variables in class to avoid copying on every iteration of the parser - const uint8_t* _data; - size_t _len; - size_t _bytesRead; - size_t _bytePos; - ParserFunc _parse; - IncomingPacket _packet; - uint8_t _payloadBuffer[EMC_PAYLOAD_BUFFER_SIZE]; - - static ParserResult _fixedHeader(Parser* p); - static ParserResult _remainingLengthFixed(Parser* p); - static ParserResult _remainingLengthNone(Parser* p); - static ParserResult _remainingLengthVariable(Parser* p); - - - static ParserResult _varHeaderConnack1(Parser* p); - static ParserResult _varHeaderConnack2(Parser* p); - - static ParserResult _varHeaderPacketId1(Parser* p); - static ParserResult _varHeaderPacketId2(Parser* p); - - static ParserResult _varHeaderTopicLength1(Parser* p); - static ParserResult _varHeaderTopicLength2(Parser* p); - static ParserResult _varHeaderTopic(Parser* p); - - static ParserResult _payloadSuback(Parser* p); - static ParserResult _payloadPublish(Parser* p); -}; - -} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/RemainingLength.cpp b/lib/espMqttClient/src/Packets/RemainingLength.cpp deleted file mode 100644 index d8644a3..0000000 --- a/lib/espMqttClient/src/Packets/RemainingLength.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "RemainingLength.h" - -namespace espMqttClientInternals { - -int32_t decodeRemainingLength(const uint8_t* stream) { - uint32_t multiplier = 1; - int32_t remainingLength = 0; - uint8_t currentByte = 0; - uint8_t encodedByte; - - do { - encodedByte = stream[currentByte++]; - remainingLength += (encodedByte & 127) * multiplier; - if (multiplier > 128 * 128 * 128) { - emc_log_e("Malformed Remaining Length"); - return -1; - } - multiplier *= 128; - } while ((encodedByte & 128) != 0); - - return remainingLength; -} - -uint8_t remainingLengthLength(uint32_t remainingLength) { - if (remainingLength < 128) return 1; - if (remainingLength < 16384) return 2; - if (remainingLength < 2097152) return 3; - if (remainingLength > 268435455) return 0; - return 4; -} - -uint8_t encodeRemainingLength(uint32_t remainingLength, uint8_t* destination) { - uint8_t currentByte = 0; - uint8_t bytesNeeded = 0; - - do { - uint8_t encodedByte = remainingLength % 128; - remainingLength /= 128; - if (remainingLength > 0) { - encodedByte = encodedByte | 128; - } - destination[currentByte++] = encodedByte; - bytesNeeded++; - } while (remainingLength > 0); - - return bytesNeeded; -} - -} // namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/RemainingLength.h b/lib/espMqttClient/src/Packets/RemainingLength.h deleted file mode 100644 index 0b84e23..0000000 --- a/lib/espMqttClient/src/Packets/RemainingLength.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright (c) 2022 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 - -#include "../Logging.h" - -namespace espMqttClientInternals { - -// Calculations are based on non normative comment in section 2.2.3 Remaining Length of the MQTT specification - -// returns decoded length based on input stream -// stream is expected to contain full encoded remaining length -// return -1 on error. -int32_t decodeRemainingLength(const uint8_t* stream); - - -// returns the number of bytes needed to encode the remaining length -uint8_t remainingLengthLength(uint32_t remainingLength); - -// encodes the given remaining length to destination and returns number of bytes used -// destination is expected to be large enough to hold the number of bytes needed -uint8_t encodeRemainingLength(uint32_t remainingLength, uint8_t* destination); - -} // namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/StringUtil.cpp b/lib/espMqttClient/src/Packets/StringUtil.cpp deleted file mode 100644 index 7cd3dd8..0000000 --- a/lib/espMqttClient/src/Packets/StringUtil.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "StringUtil.h" - -namespace espMqttClientInternals { - -size_t encodeString(const char* source, uint8_t* dest) { - size_t length = strlen(source); - if (length > 65535) { - emc_log_e("String length error"); - return 0; - } - - dest[0] = static_cast(length) >> 8; - dest[1] = static_cast(length) & 0xFF; - memcpy(&dest[2], source, length); - return 2 + length; -} - -} // namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/StringUtil.h b/lib/espMqttClient/src/Packets/StringUtil.h deleted file mode 100644 index 7f1e1e8..0000000 --- a/lib/espMqttClient/src/Packets/StringUtil.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (c) 2022 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 -#include // memcpy - -#include "../Logging.h" - -namespace espMqttClientInternals { - -// encodes the given source string into destination and returns number of bytes used -// destination is expected to be large enough to hold the number of bytes needed -size_t encodeString(const char* source, uint8_t* dest); - -} // namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Transport/ClientAsync.cpp b/lib/espMqttClient/src/Transport/ClientAsync.cpp deleted file mode 100644 index 4f8d69e..0000000 --- a/lib/espMqttClient/src/Transport/ClientAsync.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include "ClientAsync.h" - -namespace espMqttClientInternals { - -ClientAsync::ClientAsync() -: client() -, availableData(0) -, bufData(nullptr) { - // empty -} - -bool ClientAsync::connect(IPAddress ip, uint16_t port) { - return client.connect(ip, port); -} - -bool ClientAsync::connect(const char* host, uint16_t port) { - return client.connect(host, port); -} - -size_t ClientAsync::write(const uint8_t* buf, size_t size) { - return client.write(reinterpret_cast(buf), size); -} - -int ClientAsync::read(uint8_t* buf, size_t size) { - size_t willRead = std::min(size, availableData); - memcpy(buf, bufData, std::min(size, availableData)); - if (availableData > size) { - emc_log_w("Buffer is smaller than available data: %zu - %zu", size, availableData); - } - availableData = 0; - return willRead; -} - -void ClientAsync::stop() { - client.close(false); -} - -bool ClientAsync::connected() { - return client.connected(); -} - -bool ClientAsync::disconnected() { - return client.disconnected(); -} - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientAsync.h b/lib/espMqttClient/src/Transport/ClientAsync.h deleted file mode 100644 index c3ddd03..0000000 --- a/lib/espMqttClient/src/Transport/ClientAsync.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#pragma once - -#if defined(ARDUINO_ARCH_ESP32) - #include "freertos/FreeRTOS.h" - #include -#elif defined(ARDUINO_ARCH_ESP8266) - #include -#endif - -#include "Transport.h" -#include "../Config.h" -#include "../Logging.h" - -namespace espMqttClientInternals { - -class ClientAsync : public Transport { - public: - ClientAsync(); - bool connect(IPAddress ip, uint16_t port) override; - bool connect(const char* host, uint16_t port) override; - size_t write(const uint8_t* buf, size_t size) override; - int read(uint8_t* buf, size_t size) override; - void stop() override; - bool connected() override; - bool disconnected() override; - - AsyncClient client; - size_t availableData; - uint8_t* bufData; -}; - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientPosix.cpp b/lib/espMqttClient/src/Transport/ClientPosix.cpp deleted file mode 100644 index 4b086d1..0000000 --- a/lib/espMqttClient/src/Transport/ClientPosix.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "ClientPosix.h" - -#if defined(__linux__) - -namespace espMqttClientInternals { - -ClientPosix::ClientPosix() -: _sockfd(-1) -, _host() { - // empty -} - -ClientPosix::~ClientPosix() { - ClientPosix::stop(); -} - -bool ClientPosix::connect(IPAddress ip, uint16_t port) { - if (connected()) stop(); - - _sockfd = ::socket(AF_INET, SOCK_STREAM, 0); - if (_sockfd < 0) { - emc_log_e("Error %d: \"%s\" opening socket", errno, strerror(errno)); - } - - int flag = 1; - if (setsockopt(_sockfd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int)) < 0) { - emc_log_e("Error %d: \"%s\" disabling nagle", errno, strerror(errno)); - } - - memset(&_host, 0, sizeof(_host)); - _host.sin_family = AF_INET; - _host.sin_addr.s_addr = htonl(uint32_t(ip)); - _host.sin_port = ::htons(port); - - int ret = ::connect(_sockfd, reinterpret_cast(&_host), sizeof(_host)); - - if (ret < 0) { - emc_log_e("Error connecting: %d - (%d) %s", ret, errno, strerror(errno)); - return false; - } - - emc_log_i("Socket connected"); - return true; -} - -bool ClientPosix::connect(const char* hostname, uint16_t port) { - IPAddress ipAddress = _hostToIP(hostname); - if (ipAddress == IPAddress(0)) { - emc_log_e("No such host '%s'", hostname); - return false; - } - return connect(ipAddress, port); -} - -size_t ClientPosix::write(const uint8_t* buf, size_t size) { - return ::send(_sockfd, buf, size, 0); -} - -int ClientPosix::read(uint8_t* buf, size_t size) { - int ret = ::recv(_sockfd, buf, size, MSG_DONTWAIT); - /* - if (ret < 0) { - emc_log_e("Error reading: %s", strerror(errno)); - } - */ - return ret; -} - -void ClientPosix::stop() { - if (_sockfd >= 0) { - ::close(_sockfd); - _sockfd = -1; - } -} - -bool ClientPosix::connected() { - return _sockfd >= 0; -} - -bool ClientPosix::disconnected() { - return _sockfd < 0; -} - -IPAddress ClientPosix::_hostToIP(const char* hostname) { - IPAddress returnIP(0); - struct addrinfo hints, *servinfo, *p; - struct sockaddr_in *h; - int rv; - -// Set up request addrinfo struct - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - - emc_log_i("Looking for '%s'", hostname); - -// ask for host data - if ((rv = getaddrinfo(hostname, NULL, &hints, &servinfo)) != 0) { - emc_log_e("getaddrinfo: %s", gai_strerror(rv)); - return returnIP; - } - - // loop through all the results and connect to the first we can - for (p = servinfo; p != NULL; p = p->ai_next) { - h = (struct sockaddr_in *)p->ai_addr; - returnIP = ::htonl(h->sin_addr.s_addr); - if (returnIP != IPAddress(0)) break; - } - // Release allocated memory - freeaddrinfo(servinfo); - - if (returnIP != IPAddress(0)) { - emc_log_i("Host '%s' = %u", hostname, (uint32_t)returnIP); - } else { - emc_log_e("No IP for '%s' found", hostname); - } - return returnIP; -} - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientPosix.h b/lib/espMqttClient/src/Transport/ClientPosix.h deleted file mode 100644 index adffaa1..0000000 --- a/lib/espMqttClient/src/Transport/ClientPosix.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright (c) 2022 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 - -#if defined(__linux__) - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Transport.h" // includes IPAddress -#include "../Logging.h" - -#ifndef EMC_POSIX_PEEK_SIZE -#define EMC_POSIX_PEEK_SIZE 1500 -#endif - -namespace espMqttClientInternals { - -class ClientPosix : public Transport { - public: - ClientPosix(); - ~ClientPosix(); - bool connect(IPAddress ip, uint16_t port) override; - bool connect(const char* hostname, uint16_t port) override; - size_t write(const uint8_t* buf, size_t size) override; - int read(uint8_t* buf, size_t size) override; - void stop() override; - bool connected() override; - bool disconnected() override; - - protected: - int _sockfd; - sockaddr_in _host; - - IPAddress _hostToIP(const char* hostname); -}; - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientPosixIPAddress.cpp b/lib/espMqttClient/src/Transport/ClientPosixIPAddress.cpp deleted file mode 100644 index c6a78fc..0000000 --- a/lib/espMqttClient/src/Transport/ClientPosixIPAddress.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#if defined(__linux__) - -#include "ClientPosixIPAddress.h" - -IPAddress::IPAddress() -: _address(0) { - // empty -} - -IPAddress::IPAddress(uint8_t p0, uint8_t p1, uint8_t p2, uint8_t p3) -: _address(0) { - _address = (uint32_t)p0 << 24 | (uint32_t)p1 << 16 | (uint32_t)p2 << 8 | p3; -} - -IPAddress::IPAddress(uint32_t address) -: _address(address) { - // empty -} - -IPAddress::operator uint32_t() { - return _address; -} - -bool IPAddress::operator==(IPAddress other) { - return _address == other._address; -} - -bool IPAddress::operator!=(IPAddress other) { - return _address != other._address; -} - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientPosixIPAddress.h b/lib/espMqttClient/src/Transport/ClientPosixIPAddress.h deleted file mode 100644 index 9941ec5..0000000 --- a/lib/espMqttClient/src/Transport/ClientPosixIPAddress.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright (c) 2022 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 - -#if defined(ARDUINO) - #include -#else - -#include - -class IPAddress { - public: - IPAddress(); - IPAddress(uint8_t p0, uint8_t p1, uint8_t p2, uint8_t p3); - IPAddress(uint32_t address); // NOLINT(runtime/explicit) - operator uint32_t(); - bool operator==(IPAddress other); - bool operator!=(IPAddress other); - - protected: - uint32_t _address; -}; - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientSecureSync.cpp b/lib/espMqttClient/src/Transport/ClientSecureSync.cpp deleted file mode 100644 index 36288c6..0000000 --- a/lib/espMqttClient/src/Transport/ClientSecureSync.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include "ClientSecureSync.h" -#include // socket options - -namespace espMqttClientInternals { - -ClientSecureSync::ClientSecureSync() -: client() { - // empty -} - -bool ClientSecureSync::connect(IPAddress ip, uint16_t port) { - bool ret = client.connect(ip, port); // implicit conversion of return code int --> bool - if (ret) { - #if defined(ARDUINO_ARCH_ESP8266) - client.setNoDelay(true); - #elif defined(ARDUINO_ARCH_ESP32) - // Set TCP option directly to bypass lack of working setNoDelay for WiFiClientSecure - int val = true; - client.setSocketOption(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(int)); - #endif - } - return ret; -} - -bool ClientSecureSync::connect(const char* host, uint16_t port) { - bool ret = client.connect(host, port); // implicit conversion of return code int --> bool - if (ret) { - #if defined(ARDUINO_ARCH_ESP8266) - client.setNoDelay(true); - #elif defined(ARDUINO_ARCH_ESP32) - // Set TCP option directly to bypass lack of working setNoDelay for WiFiClientSecure - int val = true; - client.setSocketOption(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(int)); - #endif - } - return ret; -} - -size_t ClientSecureSync::write(const uint8_t* buf, size_t size) { - return client.write(buf, size); -} - -int ClientSecureSync::read(uint8_t* buf, size_t size) { - return client.read(buf, size); -} - -void ClientSecureSync::stop() { - client.stop(); -} - -bool ClientSecureSync::connected() { - return client.connected(); -} - -bool ClientSecureSync::disconnected() { - return !client.connected(); -} - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientSecureSync.h b/lib/espMqttClient/src/Transport/ClientSecureSync.h deleted file mode 100644 index b81681e..0000000 --- a/lib/espMqttClient/src/Transport/ClientSecureSync.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright (c) 2022 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 - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include // includes IPAddress - -#include "Transport.h" - -namespace espMqttClientInternals { - -class ClientSecureSync : public Transport { - public: - ClientSecureSync(); - bool connect(IPAddress ip, uint16_t port) override; - bool connect(const char* host, uint16_t port) override; - size_t write(const uint8_t* buf, size_t size) override; - int read(uint8_t* buf, size_t size) override; - void stop() override; - bool connected() override; - bool disconnected() override; - WiFiClientSecure client; -}; - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientSync.cpp b/lib/espMqttClient/src/Transport/ClientSync.cpp deleted file mode 100644 index b2c4045..0000000 --- a/lib/espMqttClient/src/Transport/ClientSync.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include "ClientSync.h" -#include // socket options - -namespace espMqttClientInternals { - -ClientSync::ClientSync() -: client() { - // empty -} - -bool ClientSync::connect(IPAddress ip, uint16_t port) { - bool ret = client.connect(ip, port); // implicit conversion of return code int --> bool - if (ret) { - #if defined(ARDUINO_ARCH_ESP8266) - client.setNoDelay(true); - #elif defined(ARDUINO_ARCH_ESP32) - // Set TCP option directly to bypass lack of working setNoDelay for WiFiClientSecure (for consistency also here) - int val = true; - client.setSocketOption(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(int)); - #endif - } - return ret; -} - -bool ClientSync::connect(const char* host, uint16_t port) { - bool ret = client.connect(host, port); // implicit conversion of return code int --> bool - if (ret) { - #if defined(ARDUINO_ARCH_ESP8266) - client.setNoDelay(true); - #elif defined(ARDUINO_ARCH_ESP32) - // Set TCP option directly to bypass lack of working setNoDelay for WiFiClientSecure (for consistency also here) - int val = true; - client.setSocketOption(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(int)); - #endif - } - return ret; -} - -size_t ClientSync::write(const uint8_t* buf, size_t size) { - return client.write(buf, size); -} - -int ClientSync::read(uint8_t* buf, size_t size) { - return client.read(buf, size); -} - -void ClientSync::stop() { - client.stop(); -} - -bool ClientSync::connected() { - return client.connected(); -} - -bool ClientSync::disconnected() { - return !client.connected(); -} - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/ClientSync.h b/lib/espMqttClient/src/Transport/ClientSync.h deleted file mode 100644 index ccfbdba..0000000 --- a/lib/espMqttClient/src/Transport/ClientSync.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright (c) 2022 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 - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include // includes IPAddress - -#include "Transport.h" - -namespace espMqttClientInternals { - -class ClientSync : public Transport { - public: - ClientSync(); - bool connect(IPAddress ip, uint16_t port) override; - bool connect(const char* host, uint16_t port) override; - size_t write(const uint8_t* buf, size_t size) override; - int read(uint8_t* buf, size_t size) override; - void stop() override; - bool connected() override; - bool disconnected() override; - WiFiClient client; -}; - -} // namespace espMqttClientInternals - -#endif diff --git a/lib/espMqttClient/src/Transport/Transport.h b/lib/espMqttClient/src/Transport/Transport.h deleted file mode 100644 index d368d01..0000000 --- a/lib/espMqttClient/src/Transport/Transport.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (c) 2022 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 // size_t - -#include "ClientPosixIPAddress.h" - -namespace espMqttClientInternals { - -class Transport { - public: - virtual bool connect(IPAddress ip, uint16_t port) = 0; - virtual bool connect(const char* host, uint16_t port) = 0; - virtual size_t write(const uint8_t* buf, size_t size) = 0; - virtual int read(uint8_t* buf, size_t size) = 0; - virtual void stop() = 0; - virtual bool connected() = 0; - virtual bool disconnected() = 0; -}; - -} // namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/TypeDefs.cpp b/lib/espMqttClient/src/TypeDefs.cpp deleted file mode 100644 index 4f92c1f..0000000 --- a/lib/espMqttClient/src/TypeDefs.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -Parts are based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "TypeDefs.h" - -namespace espMqttClientTypes { - -const char* disconnectReasonToString(DisconnectReason reason) { - switch (reason) { - case DisconnectReason::USER_OK: return "No error"; - case DisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION: return "Unacceptable protocol version"; - case DisconnectReason::MQTT_IDENTIFIER_REJECTED: return "Identified rejected"; - case DisconnectReason::MQTT_SERVER_UNAVAILABLE: return "Server unavailable"; - case DisconnectReason::MQTT_MALFORMED_CREDENTIALS: return "Malformed credentials"; - case DisconnectReason::MQTT_NOT_AUTHORIZED: return "Not authorized"; - case DisconnectReason::TLS_BAD_FINGERPRINT: return "Bad fingerprint"; - case DisconnectReason::TCP_DISCONNECTED: return "TCP disconnected"; - default: return ""; - } -} - -const char* subscribeReturncodeToString(SubscribeReturncode returnCode) { - switch (returnCode) { - case SubscribeReturncode::QOS0: return "QoS 0"; - case SubscribeReturncode::QOS1: return "QoS 1"; - case SubscribeReturncode::QOS2: return "QoS 2"; - case SubscribeReturncode::FAIL: return "Failed"; - default: return ""; - } -} - -const char* errorToString(Error error) { - switch (error) { - case Error::SUCCESS: return "Success"; - case Error::OUT_OF_MEMORY: return "Out of memory"; - case Error::MAX_RETRIES: return "Maximum retries exceeded"; - case Error::MALFORMED_PARAMETER: return "Malformed parameters"; - case Error::MISC_ERROR: return "Misc error"; - default: return ""; - } -} - -} // end namespace espMqttClientTypes diff --git a/lib/espMqttClient/src/TypeDefs.h b/lib/espMqttClient/src/TypeDefs.h deleted file mode 100644 index 0f15360..0000000 --- a/lib/espMqttClient/src/TypeDefs.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -Parts are based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#include -#include -#include - -namespace espMqttClientTypes { - -enum class DisconnectReason : uint8_t { - USER_OK = 0, - MQTT_UNACCEPTABLE_PROTOCOL_VERSION = 1, - MQTT_IDENTIFIER_REJECTED = 2, - MQTT_SERVER_UNAVAILABLE = 3, - MQTT_MALFORMED_CREDENTIALS = 4, - MQTT_NOT_AUTHORIZED = 5, - TLS_BAD_FINGERPRINT = 6, - TCP_DISCONNECTED = 7 -}; - -const char* disconnectReasonToString(DisconnectReason reason); - -enum class SubscribeReturncode : uint8_t { - QOS0 = 0x00, - QOS1 = 0x01, - QOS2 = 0x02, - FAIL = 0X80 -}; - -const char* subscribeReturncodeToString(SubscribeReturncode returnCode); - -enum class Error : uint8_t { - SUCCESS = 0, - OUT_OF_MEMORY = 1, - MAX_RETRIES = 2, - MALFORMED_PARAMETER = 3, - MISC_ERROR = 4 -}; - -const char* errorToString(Error error); - -struct MessageProperties { - uint8_t qos; - bool dup; - bool retain; - uint16_t packetId; -}; - -typedef std::function OnConnectCallback; -typedef std::function OnDisconnectCallback; -typedef std::function OnSubscribeCallback; -typedef std::function OnUnsubscribeCallback; -typedef std::function OnMessageCallback; -typedef std::function OnPublishCallback; -typedef std::function PayloadCallback; -typedef std::function OnErrorCallback; - -enum class UseInternalTask { - NO = 0, - YES = 1, -}; - -} // end namespace espMqttClientTypes diff --git a/lib/espMqttClient/src/espMqttClient.cpp b/lib/espMqttClient/src/espMqttClient.cpp deleted file mode 100644 index 833ece1..0000000 --- a/lib/espMqttClient/src/espMqttClient.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#include "espMqttClient.h" - -#if defined(ARDUINO_ARCH_ESP8266) -espMqttClient::espMqttClient() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _client() { - _transport = &_client; -} - -espMqttClientSecure::espMqttClientSecure() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _client() { - _transport = &_client; -} - -espMqttClientSecure& espMqttClientSecure::setInsecure() { - _client.client.setInsecure(); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setFingerprint(const uint8_t fingerprint[20]) { - _client.client.setFingerprint(fingerprint); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setTrustAnchors(const X509List *ta) { - _client.client.setTrustAnchors(ta); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setClientRSACert(const X509List *cert, const PrivateKey *sk) { - _client.client.setClientRSACert(cert, sk); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setClientECCert(const X509List *cert, const PrivateKey *sk, unsigned allowed_usages, unsigned cert_issuer_key_type) { - _client.client.setClientECCert(cert, sk, allowed_usages, cert_issuer_key_type); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setCertStore(CertStoreBase *certStore) { - _client.client.setCertStore(certStore); - return *this; -} -#endif - -#if defined(ARDUINO_ARCH_ESP32) -espMqttClient::espMqttClient(espMqttClientTypes::UseInternalTask useInternalTask) -: MqttClientSetup(useInternalTask) -, _client() { - _transport = &_client; -} - -espMqttClient::espMqttClient(uint8_t priority, uint8_t core) -: MqttClientSetup(espMqttClientTypes::UseInternalTask::YES, priority, core) -, _client() { - _transport = &_client; -} - -espMqttClientSecure::espMqttClientSecure(espMqttClientTypes::UseInternalTask useInternalTask) -: MqttClientSetup(useInternalTask) -, _client() { - _transport = &_client; -} - -espMqttClientSecure::espMqttClientSecure(uint8_t priority, uint8_t core) -: MqttClientSetup(espMqttClientTypes::UseInternalTask::YES, priority, core) -, _client() { - _transport = &_client; -} - -espMqttClientSecure& espMqttClientSecure::setInsecure() { - _client.client.setInsecure(); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setCACert(const char* rootCA) { - _client.client.setCACert(rootCA); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setCertificate(const char* clientCa) { - _client.client.setCertificate(clientCa); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setPrivateKey(const char* privateKey) { - _client.client.setPrivateKey(privateKey); - return *this; -} - -espMqttClientSecure& espMqttClientSecure::setPreSharedKey(const char* pskIdent, const char* psKey) { - _client.client.setPreSharedKey(pskIdent, psKey); - return *this; -} - -#endif - -#if defined(__linux__) -espMqttClient::espMqttClient() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _client() { - _transport = &_client; -} -#endif diff --git a/lib/espMqttClient/src/espMqttClient.h b/lib/espMqttClient/src/espMqttClient.h deleted file mode 100644 index 4e44801..0000000 --- a/lib/espMqttClient/src/espMqttClient.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -API is based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) -#include "Transport/ClientSync.h" -#include "Transport/ClientSecureSync.h" -#elif defined(__linux__) -#include "Transport/ClientPosix.h" -#endif - -#include "MqttClientSetup.h" - -#if defined(ARDUINO_ARCH_ESP8266) -class espMqttClient : public MqttClientSetup { - public: - espMqttClient(); - - protected: - espMqttClientInternals::ClientSync _client; -}; - -class espMqttClientSecure : public MqttClientSetup { - public: - espMqttClientSecure(); - espMqttClientSecure& setInsecure(); - espMqttClientSecure& setFingerprint(const uint8_t fingerprint[20]); - espMqttClientSecure& setTrustAnchors(const X509List *ta); - espMqttClientSecure& setClientRSACert(const X509List *cert, const PrivateKey *sk); - espMqttClientSecure& setClientECCert(const X509List *cert, const PrivateKey *sk, unsigned allowed_usages, unsigned cert_issuer_key_type); - espMqttClientSecure& setCertStore(CertStoreBase *certStore); - - protected: - espMqttClientInternals::ClientSecureSync _client; -}; -#endif - -#if defined(ARDUINO_ARCH_ESP32) -class espMqttClient : public MqttClientSetup { - public: - explicit espMqttClient(espMqttClientTypes::UseInternalTask useInternalTask); - explicit espMqttClient(uint8_t priority = 1, uint8_t core = 1); - - protected: - espMqttClientInternals::ClientSync _client; -}; - -class espMqttClientSecure : public MqttClientSetup { - public: - explicit espMqttClientSecure(espMqttClientTypes::UseInternalTask useInternalTask); - explicit espMqttClientSecure(uint8_t priority = 1, uint8_t core = 1); - espMqttClientSecure& setInsecure(); - espMqttClientSecure& setCACert(const char* rootCA); - espMqttClientSecure& setCertificate(const char* clientCa); - espMqttClientSecure& setPrivateKey(const char* privateKey); - espMqttClientSecure& setPreSharedKey(const char* pskIdent, const char* psKey); - - protected: - espMqttClientInternals::ClientSecureSync _client; -}; -#endif - -#if defined(__linux__) -class espMqttClient : public MqttClientSetup { - public: - espMqttClient(); - - protected: - espMqttClientInternals::ClientPosix _client; -}; -#endif diff --git a/lib/espMqttClient/src/espMqttClientAsync.cpp b/lib/espMqttClient/src/espMqttClientAsync.cpp deleted file mode 100644 index 98b7f15..0000000 --- a/lib/espMqttClient/src/espMqttClientAsync.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include "espMqttClientAsync.h" - -espMqttClientAsync::espMqttClientAsync() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _clientAsync() { - _transport = &_clientAsync; - _clientAsync.client.onConnect(onConnectCb, this); - _clientAsync.client.onDisconnect(onDisconnectCb, this); - _clientAsync.client.onData(onDataCb, this); - _clientAsync.client.onPoll(onPollCb, this); -} - -bool espMqttClientAsync::connect() { - bool ret = MqttClient::connect(); - loop(); - return ret; -} - -void espMqttClientAsync::_setupClient(espMqttClientAsync* c) { - (void)c; -} - -void espMqttClientAsync::onConnectCb(void* a, AsyncClient* c) { - c->setNoDelay(true); - espMqttClientAsync* client = reinterpret_cast(a); - client->_state = MqttClient::State::connectingTcp2; - client->loop(); -} - -void espMqttClientAsync::onDataCb(void* a, AsyncClient* c, void* data, size_t len) { - (void)c; - espMqttClientAsync* client = reinterpret_cast(a); - client->_clientAsync.bufData = reinterpret_cast(data); - client->_clientAsync.availableData = len; - client->loop(); -} - -void espMqttClientAsync::onDisconnectCb(void* a, AsyncClient* c) { - (void)c; - espMqttClientAsync* client = reinterpret_cast(a); - client->_state = MqttClient::State::disconnectingTcp2; - client->loop(); -} - -void espMqttClientAsync::onPollCb(void* a, AsyncClient* c) { - (void)c; - espMqttClientAsync* client = reinterpret_cast(a); - client->loop(); -} - -#endif diff --git a/lib/espMqttClient/src/espMqttClientAsync.h b/lib/espMqttClient/src/espMqttClientAsync.h deleted file mode 100644 index 1b9ed8b..0000000 --- a/lib/espMqttClient/src/espMqttClientAsync.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -API is based on the original work of Marvin Roger: -https://github.com/marvinroger/async-mqtt-client - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - -#include "Transport/ClientAsync.h" - -#include "MqttClientSetup.h" - -class espMqttClientAsync : public MqttClientSetup { - public: - espMqttClientAsync(); - bool connect(); - - protected: - espMqttClientInternals::ClientAsync _clientAsync; - static void _setupClient(espMqttClientAsync* c); - static void _disconnectClient(espMqttClientAsync* c); - - static void onConnectCb(void* a, AsyncClient* c); - static void onDataCb(void* a, AsyncClient* c, void* data, size_t len); - static void onDisconnectCb(void* a, AsyncClient* c); - static void onPollCb(void* a, AsyncClient* c); -}; - -#endif diff --git a/lib/espMqttClient/test-coverage.py b/lib/espMqttClient/test-coverage.py deleted file mode 100644 index 0d83301..0000000 --- a/lib/espMqttClient/test-coverage.py +++ /dev/null @@ -1,22 +0,0 @@ -import os - -Import("env", "projenv") - -# Dump build environment (for debug purpose) -print(env.Dump()) - -# access to global build environment -print(env) - -# access to the project build environment -# (used for source files located in the "src" folder) -print(projenv) - -def generateCoverageInfo(source, target, env): - for file in os.listdir("test"): - os.system(".pio/build/native/program test/"+file) - os.system("lcov -d .pio/build/native/ -c -o lcov.info") - os.system("lcov --remove lcov.info '*Unity*' '*unity*' '/usr/include/*' '*/test/*' -o filtered_lcov.info") - os.system("genhtml -o cov/ --demangle-cpp filtered_lcov.info") - -env.AddPostAction(".pio/build/native/program", generateCoverageInfo) \ No newline at end of file diff --git a/lib/espMqttClient/test/test_client_native/test_client_native.cpp b/lib/espMqttClient/test/test_client_native/test_client_native.cpp deleted file mode 100644 index d2eef9d..0000000 --- a/lib/espMqttClient/test/test_client_native/test_client_native.cpp +++ /dev/null @@ -1,405 +0,0 @@ -#include -#include -#include -#include // espMqttClient for Linux also defines millis() - -void setUp() {} -void tearDown() {} - -espMqttClient mqttClient; -uint32_t onConnectCbId = 1; -uint32_t onDisconnectCbId = 2; -uint32_t onSubscribeCbId = 3; -uint32_t onUnsubscribeCbId = 4; -uint32_t onMessageCbId = 5; -uint32_t onPublishCbId = 6; -std::atomic_bool exitProgram(false); -std::thread t; - -//const IPAddress broker(127,0,0,1); -const char* broker = "mqtt"; -//const char* broker = "test.mosquitto.org"; -const uint16_t broker_port = 1883; - -/* - -- setup the client with basic settings -- connect to the broker -- successfully connect - -*/ -void test_connect() { - std::atomic onConnectCalledTest(false); - bool sessionPresentTest = true; - mqttClient.setServer(broker, broker_port) - .setCleanSession(true) - .setKeepAlive(5) - .onConnect([&](bool sessionPresent) mutable { - sessionPresentTest = sessionPresent; - onConnectCalledTest = true; - }, onConnectCbId); - mqttClient.connect(); - uint32_t start = millis(); - while (millis() - start < 2000) { - if (onConnectCalledTest) { - break; - } - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_TRUE(onConnectCalledTest); - TEST_ASSERT_FALSE(sessionPresentTest); - - mqttClient.removeOnConnect(onConnectCbId); -} - -/* - -- keepalive is set at 5 seconds in previous test -- client should stay connected during 2x keepalive period - -*/ - -void test_ping() { - bool pingTest = true; - uint32_t start = millis(); - while (millis() - start < 11000) { - if (mqttClient.disconnected()) { - pingTest = false; - break; - } - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_TRUE(pingTest); -} - -/* - -- client subscribes to topic -- ack is received from broker - -*/ - -void test_subscribe() { - std::atomic subscribeTest(false); - mqttClient.onSubscribe([&](uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* returncodes, size_t len) mutable { - (void) packetId; - if (len == 1 && returncodes[0] == espMqttClientTypes::SubscribeReturncode::QOS0) { - subscribeTest = true; - } - }, onSubscribeCbId); - mqttClient.subscribe("test/test", 0); - uint32_t start = millis(); - while (millis() - start < 2000) { - if (subscribeTest) { - break; - } - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_TRUE(subscribeTest); - - mqttClient.removeOnSubscribe(onSubscribeCbId); -} - -/* - -- client publishes using all three qos levels -- all publish get packetID returned > 0 (equal to 1 for qos 0) -- 2 pubacks are received - -*/ - -void test_publish() { - std::atomic publishSendTest(0); - mqttClient.onPublish([&](uint16_t packetId) mutable { - (void) packetId; - publishSendTest++; - }, onPublishCbId); - std::atomic publishReceiveTest(0); - mqttClient.onMessage([&](const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) mutable { - (void) properties; - (void) topic; - (void) payload; - (void) len; - (void) index; - (void) total; - publishReceiveTest++; - }, onMessageCbId); - uint16_t sendQos0Test = mqttClient.publish("test/test", 0, false, "test0"); - uint16_t sendQos1Test = mqttClient.publish("test/test", 1, false, "test1"); - uint16_t sendQos2Test = mqttClient.publish("test/test", 2, false, "test2"); - uint32_t start = millis(); - while (millis() - start < 6000) { - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_EQUAL_UINT16(1, sendQos0Test); - TEST_ASSERT_GREATER_THAN_UINT16(0, sendQos1Test); - TEST_ASSERT_GREATER_THAN_UINT16(0, sendQos2Test); - TEST_ASSERT_EQUAL_INT(2, publishSendTest); - TEST_ASSERT_EQUAL_INT(3, publishReceiveTest); - - mqttClient.removeOnPublish(onPublishCbId); - mqttClient.removeOnMessage(onMessageCbId); -} - -void test_publish_empty() { - std::atomic publishSendEmptyTest(0); - mqttClient.onPublish([&](uint16_t packetId) mutable { - (void) packetId; - publishSendEmptyTest++; - }, onPublishCbId); - std::atomic publishReceiveEmptyTest(0); - mqttClient.onMessage([&](const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) mutable { - (void) properties; - (void) topic; - (void) payload; - (void) len; - (void) index; - (void) total; - publishReceiveEmptyTest++; - }, onMessageCbId); - uint16_t sendQos0Test = mqttClient.publish("test/test", 0, false, nullptr, 0); - uint16_t sendQos1Test = mqttClient.publish("test/test", 1, false, nullptr, 0); - uint16_t sendQos2Test = mqttClient.publish("test/test", 2, false, nullptr, 0); - uint32_t start = millis(); - while (millis() - start < 6000) { - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_EQUAL_UINT16(1, sendQos0Test); - TEST_ASSERT_GREATER_THAN_UINT16(0, sendQos1Test); - TEST_ASSERT_GREATER_THAN_UINT16(0, sendQos2Test); - TEST_ASSERT_EQUAL_INT(2, publishSendEmptyTest); - TEST_ASSERT_EQUAL_INT(3, publishReceiveEmptyTest); - - mqttClient.removeOnPublish(onPublishCbId); - mqttClient.removeOnMessage(onMessageCbId); -} - -/* - -- subscribe to test/test, qos 1 -- send to test/test, qos 1 -- check if message is received at least once. - -*/ - -void test_receive1() { - std::atomic publishReceive1Test(0); - mqttClient.onMessage([&](const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) mutable { - (void) properties; - (void) topic; - (void) payload; - (void) len; - (void) index; - (void) total; - publishReceive1Test++; - }, onMessageCbId); - mqttClient.onSubscribe([&](uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* returncodes, size_t len) mutable { - (void) packetId; - if (len == 1 && returncodes[0] == espMqttClientTypes::SubscribeReturncode::QOS1) { - mqttClient.publish("test/test", 1, false, ""); - } - }, onSubscribeCbId); - mqttClient.subscribe("test/test", 1); - uint32_t start = millis(); - while (millis() - start < 6000) { - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_GREATER_THAN_INT(0, publishReceive1Test); - - mqttClient.removeOnMessage(onMessageCbId); - mqttClient.removeOnSubscribe(onSubscribeCbId); -} - -/* - -- subscribe to test/test, qos 2 -- send to test/test, qos 2 -- check if message is received exactly once. - -*/ - -void test_receive2() { - std::atomic publishReceive2Test(0); - mqttClient.onMessage([&](const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) mutable { - (void) properties; - (void) topic; - (void) payload; - (void) len; - (void) index; - (void) total; - publishReceive2Test++; - }, onMessageCbId); - mqttClient.onSubscribe([&](uint16_t packetId, const espMqttClientTypes::SubscribeReturncode* returncodes, size_t len) mutable { - (void) packetId; - if (len == 1 && returncodes[0] == espMqttClientTypes::SubscribeReturncode::QOS2) { - mqttClient.publish("test/test", 2, false, ""); - } - }, onSubscribeCbId); - mqttClient.subscribe("test/test", 2); - uint32_t start = millis(); - while (millis() - start < 6000) { - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_EQUAL_INT(1, publishReceive2Test); - - mqttClient.removeOnMessage(onMessageCbId); - mqttClient.removeOnSubscribe(onSubscribeCbId); -} - - -/* - -- client unsibscribes from topic - -*/ - -void test_unsubscribe() { - std::atomic unsubscribeTest(false); - mqttClient.onUnsubscribe([&](uint16_t packetId) mutable { - (void) packetId; - unsubscribeTest = true; - }, onUnsubscribeCbId); - mqttClient.unsubscribe("test/test"); - uint32_t start = millis(); - while (millis() - start < 2000) { - if (unsubscribeTest) { - break; - } - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_TRUE(unsubscribeTest); - - mqttClient.removeOnUnsubscribe(onUnsubscribeCbId); -} - -/* - -- client disconnects cleanly - -*/ - -void test_disconnect() { - std::atomic onDisconnectCalled(false); - espMqttClientTypes::DisconnectReason reasonTest = espMqttClientTypes::DisconnectReason::TCP_DISCONNECTED; - mqttClient.onDisconnect([&](espMqttClientTypes::DisconnectReason reason) mutable { - reasonTest = reason; - onDisconnectCalled = true; - }, onDisconnectCbId); - mqttClient.disconnect(); - uint32_t start = millis(); - while (millis() - start < 2000) { - if (onDisconnectCalled) { - break; - } - std::this_thread::yield(); - } - - TEST_ASSERT_TRUE(onDisconnectCalled); - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::DisconnectReason::USER_OK, reasonTest); - TEST_ASSERT_TRUE(mqttClient.disconnected()); - - mqttClient.removeOnDisconnect(onDisconnectCbId); -} - -void test_pub_before_connect() { - std::atomic onConnectCalledTest(false); - std::atomic publishSendTest(0); - bool sessionPresentTest = true; - mqttClient.setServer(broker, broker_port) - .setCleanSession(true) - .setKeepAlive(5) - .onConnect([&](bool sessionPresent) mutable { - sessionPresentTest = sessionPresent; - onConnectCalledTest = true; - }, onConnectCbId) - .onPublish([&](uint16_t packetId) mutable { - (void) packetId; - publishSendTest++; - }, onPublishCbId); - uint16_t sendQos0Test = mqttClient.publish("test/test", 0, false, "test0"); - uint16_t sendQos1Test = mqttClient.publish("test/test", 1, false, "test1"); - uint16_t sendQos2Test = mqttClient.publish("test/test", 2, false, "test2"); - mqttClient.connect(); - uint32_t start = millis(); - while (millis() - start < 2000) { - if (onConnectCalledTest) { - break; - } - std::this_thread::yield(); - } - TEST_ASSERT_TRUE(mqttClient.connected()); - TEST_ASSERT_TRUE(onConnectCalledTest); - TEST_ASSERT_FALSE(sessionPresentTest); - start = millis(); - while (millis() - start < 10000) { - std::this_thread::yield(); - } - - TEST_ASSERT_EQUAL_UINT16(1, sendQos0Test); - TEST_ASSERT_GREATER_THAN_UINT16(0, sendQos1Test); - TEST_ASSERT_GREATER_THAN_UINT16(0, sendQos2Test); - TEST_ASSERT_EQUAL_INT(2, publishSendTest); - - mqttClient.removeOnConnect(onConnectCbId); - mqttClient.removeOnPublish(onPublishCbId); -} - -void final_disconnect() { - std::atomic onDisconnectCalled(false); - mqttClient.onDisconnect([&](espMqttClientTypes::DisconnectReason reason) mutable { - (void) reason; - onDisconnectCalled = true; - }, onDisconnectCbId); - mqttClient.disconnect(); - uint32_t start = millis(); - while (millis() - start < 2000) { - if (onDisconnectCalled) { - break; - } - std::this_thread::yield(); - } - if (mqttClient.connected()) { - mqttClient.disconnect(true); - } - mqttClient.removeOnDisconnect(onDisconnectCbId); -} - -int main() { - UNITY_BEGIN(); - t = std::thread([] { - while (1) { - mqttClient.loop(); - if (exitProgram) break; - } - }); - RUN_TEST(test_connect); - RUN_TEST(test_ping); - RUN_TEST(test_subscribe); - RUN_TEST(test_publish); - RUN_TEST(test_publish_empty); - RUN_TEST(test_receive1); - RUN_TEST(test_receive2); - RUN_TEST(test_unsubscribe); - RUN_TEST(test_disconnect); - RUN_TEST(test_pub_before_connect); - final_disconnect(); - exitProgram = true; - t.join(); - return UNITY_END(); -} diff --git a/lib/espMqttClient/test/test_outbox/test_outbox.cpp b/lib/espMqttClient/test/test_outbox/test_outbox.cpp deleted file mode 100644 index 0a6a3ef..0000000 --- a/lib/espMqttClient/test/test_outbox/test_outbox.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include - -#include - -using espMqttClientInternals::Outbox; - -void setUp() {} -void tearDown() {} - -void test_outbox_create() { - Outbox outbox; - Outbox::Iterator it = outbox.front(); - TEST_ASSERT_NULL(outbox.getCurrent()); - TEST_ASSERT_NULL(it.get()); - TEST_ASSERT_TRUE(outbox.empty()); -} - -void test_outbox_emplace() { - Outbox outbox; - outbox.emplace(523); - // 523, current points to 523 - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(523, *(outbox.getCurrent())); - TEST_ASSERT_FALSE(outbox.empty()); - - outbox.next(); - // 523, current points to nullptr - TEST_ASSERT_NULL(outbox.getCurrent()); - - outbox.emplace(286); - // 523 286, current points to 286 - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(286, *(outbox.getCurrent())); - - outbox.emplace(364); - // 523 286 364, current points to 286 - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(286, *(outbox.getCurrent())); -} - -void test_outbox_emplaceFront() { - Outbox outbox; - outbox.emplaceFront(1); - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(1, *(outbox.getCurrent())); - - outbox.emplaceFront(2); - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(2, *(outbox.getCurrent())); -} - -void test_outbox_remove1() { - Outbox outbox; - Outbox::Iterator it; - outbox.emplace(1); - outbox.emplace(2); - outbox.emplace(3); - outbox.emplace(4); - outbox.next(); - outbox.next(); - it = outbox.front(); - ++it; - ++it; - ++it; - ++it; - outbox.remove(it); - // 1 2 3 4, it points to nullptr, current points to 3 - TEST_ASSERT_NULL(it.get()); - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(3, *(outbox.getCurrent())); - - it = outbox.front(); - ++it; - ++it; - ++it; - outbox.remove(it); - // 1 2 3, it points to nullptr, current points to 3 - TEST_ASSERT_NULL(it.get()); - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(3, *(outbox.getCurrent())); - - - it = outbox.front(); - outbox.remove(it); - // 2 3, it points to 2, current points to 3 - TEST_ASSERT_NOT_NULL(it.get()); - TEST_ASSERT_EQUAL_UINT32(2, *(it.get())); - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(3, *(outbox.getCurrent())); - - it = outbox.front(); - outbox.remove(it); - // 3, it points to 3, current points to 3 - TEST_ASSERT_NOT_NULL(it.get()); - TEST_ASSERT_EQUAL_UINT32(3, *(it.get())); - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(3, *(outbox.getCurrent())); - - it = outbox.front(); - outbox.remove(it); - TEST_ASSERT_NULL(it.get()); - TEST_ASSERT_NULL(outbox.getCurrent()); -} - -void test_outbox_remove2() { - Outbox outbox; - Outbox::Iterator it; - outbox.emplace(1); - outbox.emplace(2); - outbox.next(); - outbox.next(); - it = outbox.front(); - // 1 2, current points to nullptr - TEST_ASSERT_NULL(outbox.getCurrent()); - TEST_ASSERT_NOT_NULL(it.get()); - TEST_ASSERT_EQUAL_UINT32(1, *(it.get())); - - ++it; - // 1 2, current points to nullptr - TEST_ASSERT_NOT_NULL(it.get()); - TEST_ASSERT_EQUAL_UINT32(2, *(it.get())); - - outbox.remove(it); - // 1, current points to nullptr - TEST_ASSERT_NULL(outbox.getCurrent()); - TEST_ASSERT_NULL(it.get()); - - it = outbox.front(); - TEST_ASSERT_NOT_NULL(it.get()); - TEST_ASSERT_EQUAL_UINT32(1, *(it.get())); - - outbox.remove(it); - TEST_ASSERT_NULL(it.get()); - TEST_ASSERT_TRUE(outbox.empty()); -} - -void test_outbox_removeCurrent() { - Outbox outbox; - outbox.emplace(1); - outbox.emplace(2); - outbox.emplace(3); - outbox.emplace(4); - outbox.removeCurrent(); - // 2 3 4, current points to 2 - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(2, *(outbox.getCurrent())); - - outbox.next(); - outbox.removeCurrent(); - // 2 4, current points to 4 - TEST_ASSERT_NOT_NULL(outbox.getCurrent()); - TEST_ASSERT_EQUAL_UINT32(4, *(outbox.getCurrent())); - - outbox.removeCurrent(); - // 4, current points to nullptr - TEST_ASSERT_NULL(outbox.getCurrent()); - - // outbox will go out of scope and destructor will be called - // Valgrind should not detect a leak here -} - -int main() { - UNITY_BEGIN(); - RUN_TEST(test_outbox_create); - RUN_TEST(test_outbox_emplace); - RUN_TEST(test_outbox_emplaceFront); - RUN_TEST(test_outbox_remove1); - RUN_TEST(test_outbox_remove2); - RUN_TEST(test_outbox_removeCurrent); - return UNITY_END(); -} diff --git a/lib/espMqttClient/test/test_packets/test_packets.cpp b/lib/espMqttClient/test/test_packets/test_packets.cpp deleted file mode 100644 index 3e4c108..0000000 --- a/lib/espMqttClient/test/test_packets/test_packets.cpp +++ /dev/null @@ -1,714 +0,0 @@ -#include - -#include - -using espMqttClientInternals::Packet; -using espMqttClientInternals::PacketType; - -void setUp() {} -void tearDown() {} - -void test_encodeConnect0() { - const uint8_t check[] = { - 0b00010000, // header - 0x0F, // remaining length - 0x00,0x04,'M','Q','T','T', // protocol - 0b00000100, // protocol level - 0b00000010, // connect flags - 0x00,0x10, // keepalive (16) - 0x00,0x03,'c','l','i' // client id - }; - const uint32_t length = 17; - - bool cleanSession = true; - const char* username = nullptr; - const char* password = nullptr; - const char* willTopic = nullptr; - bool willRemain = false; - uint8_t willQoS = 0; - const uint8_t* willPayload = nullptr; - uint16_t willPayloadLength = 0; - uint16_t keepalive = 16; - const char* clientId = "cli"; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - cleanSession, - username, - password, - willTopic, - willRemain, - willQoS, - willPayload, - willPayloadLength, - keepalive, - clientId); - - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.CONNECT, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(0, packet.packetId()); -} - -void test_encodeConnect1() { - const uint8_t check[] = { - 0b00010000, // header - 0x20, // remaining length - 0x00,0x04,'M','Q','T','T', // protocol - 0b00000100, // protocol level - 0b11101110, // connect flags - 0x00,0x10, // keepalive (16) - 0x00,0x03,'c','l','i', // client id - 0x00,0x03,'t','o','p', // will topic - 0x00,0x02,'p','l', // will payload - 0x00,0x02,'u','n', // username - 0x00,0x02,'p','a' // password - }; - const uint32_t length = 34; - - bool cleanSession = true; - const char* username = "un"; - const char* password = "pa"; - const char* willTopic = "top"; - bool willRemain = true; - uint8_t willQoS = 1; - const uint8_t willPayload[] = {'p', 'l'}; - uint16_t willPayloadLength = 2; - uint16_t keepalive = 16; - const char* clientId = "cli"; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - cleanSession, - username, - password, - willTopic, - willRemain, - willQoS, - willPayload, - willPayloadLength, - keepalive, - clientId); - - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.CONNECT, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(0, packet.packetId()); -} - -void test_encodeConnect2() { - const uint8_t check[] = { - 0b00010000, // header - 0x20, // remaining length - 0x00,0x04,'M','Q','T','T', // protocol - 0b00000100, // protocol level - 0b11110110, // connect flags - 0x00,0x10, // keepalive (16) - 0x00,0x03,'c','l','i', // client id - 0x00,0x03,'t','o','p', // will topic - 0x00,0x02,'p','l', // will payload - 0x00,0x02,'u','n', // username - 0x00,0x02,'p','a' // password - }; - const uint32_t length = 34; - - bool cleanSession = true; - const char* username = "un"; - const char* password = "pa"; - const char* willTopic = "top"; - bool willRemain = true; - uint8_t willQoS = 2; - const uint8_t willPayload[] = {'p', 'l', '\0'}; - uint16_t willPayloadLength = 0; - uint16_t keepalive = 16; - const char* clientId = "cli"; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - cleanSession, - username, - password, - willTopic, - willRemain, - willQoS, - willPayload, - willPayloadLength, - keepalive, - clientId); - - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.CONNECT, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(0, packet.packetId()); -} - -void test_encodeConnectFail0() { - bool cleanSession = true; - const char* username = nullptr; - const char* password = nullptr; - const char* willTopic = nullptr; - bool willRemain = false; - uint8_t willQoS = 0; - const uint8_t* willPayload = nullptr; - uint16_t willPayloadLength = 0; - uint16_t keepalive = 16; - const char* clientId = ""; - espMqttClientTypes::Error error = espMqttClientTypes::Error::SUCCESS; - - Packet packet(error, - cleanSession, - username, - password, - willTopic, - willRemain, - willQoS, - willPayload, - willPayloadLength, - keepalive, - clientId); - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::MALFORMED_PARAMETER, error); -} - -void test_encodePublish0() { - const uint8_t check[] = { - 0b00110000, // header, dup, qos, retain - 0x09, - 0x00,0x03,'t','o','p', // topic - 0x01,0x02,0x03,0x04 // payload - }; - const uint32_t length = 11; - - const char* topic = "top"; - uint8_t qos = 0; - bool retain = false; - const uint8_t payload[] = {0x01, 0x02, 0x03, 0x04}; - uint16_t payloadLength = 4; - uint16_t packetId = 22; // any value except 0 for testing - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - packetId, - topic, - payload, - payloadLength, - qos, - retain); - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBLISH, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(0, packet.packetId()); - - packet.setDup(); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); -} - -void test_encodePublish1() { - const uint8_t check[] = { - 0b00110011, // header, dup, qos, retain - 0x0B, - 0x00,0x03,'t','o','p', // topic - 0x00,0x16, // packet Id - 0x01,0x02,0x03,0x04 // payload - }; - const uint32_t length = 13; - - const char* topic = "top"; - uint8_t qos = 1; - bool retain = true; - const uint8_t payload[] = {0x01, 0x02, 0x03, 0x04}; - uint16_t payloadLength = 4; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - packetId, - topic, - payload, - payloadLength, - qos, - retain); - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBLISH, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); - - const uint8_t checkDup[] = { - 0b00111011, // header, dup, qos, retain - 0x0B, - 0x00,0x03,'t','o','p', // topic - 0x00,0x16, // packet Id - 0x01,0x02,0x03,0x04 // payload - }; - - packet.setDup(); - TEST_ASSERT_EQUAL_UINT8_ARRAY(checkDup, packet.data(0), length); -} - -void test_encodePublish2() { - const uint8_t check[] = { - 0b00110101, // header, dup, qos, retain - 0x0B, - 0x00,0x03,'t','o','p', // topic - 0x00,0x16, // packet Id - 0x01,0x02,0x03,0x04 // payload - }; - const uint32_t length = 13; - - const char* topic = "top"; - uint8_t qos = 2; - bool retain = true; - const uint8_t payload[] = {0x01, 0x02, 0x03, 0x04}; - uint16_t payloadLength = 4; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - packetId, - topic, - payload, - payloadLength, - qos, - retain); - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBLISH, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); - - const uint8_t checkDup[] = { - 0b00111101, // header, dup, qos, retain - 0x0B, - 0x00,0x03,'t','o','p', // topic - 0x00,0x16, // packet Id - 0x01,0x02,0x03,0x04 // payload - }; - - packet.setDup(); - TEST_ASSERT_EQUAL_UINT8_ARRAY(checkDup, packet.data(0), length); -} - -void test_encodePubAck() { - const uint8_t check[] = { - 0b01000000, // header - 0x02, - 0x00,0x16, // packet Id - }; - const uint32_t length = 4; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, PacketType.PUBACK, packetId); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBACK, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodePubRec() { - const uint8_t check[] = { - 0b01010000, // header - 0x02, - 0x00,0x16, // packet Id - }; - const uint32_t length = 4; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, PacketType.PUBREC, packetId); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBREC, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodePubRel() { - const uint8_t check[] = { - 0b01100010, // header - 0x02, - 0x00,0x16, // packet Id - }; - const uint32_t length = 4; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, PacketType.PUBREL, packetId); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBREL, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodePubComp() { - const uint8_t check[] = { - 0b01110000, // header - 0x02, // remaining length - 0x00,0x16, // packet Id - }; - const uint32_t length = 4; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, PacketType.PUBCOMP, packetId); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PUBCOMP, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodeSubscribe() { - const uint8_t check[] = { - 0b10000010, // header - 0x08, // remaining length - 0x00,0x16, // packet Id - 0x00, 0x03, 'a', '/', 'b', // topic - 0x02 // qos - }; - const uint32_t length = 10; - const char* topic = "a/b"; - uint8_t qos = 2; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, packetId, topic, qos); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.SUBSCRIBE, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodeMultiSubscribe2() { - const uint8_t check[] = { - 0b10000010, // header - 0x0E, // remaining length - 0x00,0x16, // packet Id - 0x00, 0x03, 'a', '/', 'b', // topic1 - 0x01, // qos1 - 0x00, 0x03, 'c', '/', 'd', // topic2 - 0x02 // qos2 - }; - const uint32_t length = 16; - const char* topic1 = "a/b"; - const char* topic2 = "c/d"; - uint8_t qos1 = 1; - uint8_t qos2 = 2; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, packetId, topic1, qos1, topic2, qos2); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.SUBSCRIBE, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodeMultiSubscribe3() { - const uint8_t check[] = { - 0b10000010, // header - 0x14, // remaining length - 0x00,0x16, // packet Id - 0x00, 0x03, 'a', '/', 'b', // topic1 - 0x01, // qos1 - 0x00, 0x03, 'c', '/', 'd', // topic2 - 0x02, // qos2 - 0x00, 0x03, 'e', '/', 'f', // topic3 - 0x00 // qos3 - }; - const uint32_t length = 22; - const char* topic1 = "a/b"; - const char* topic2 = "c/d"; - const char* topic3 = "e/f"; - uint8_t qos1 = 1; - uint8_t qos2 = 2; - uint8_t qos3 = 0; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, packetId, topic1, qos1, topic2, qos2, topic3, qos3); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.SUBSCRIBE, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodeUnsubscribe() { - const uint8_t check[] = { - 0b10100010, // header - 0x07, // remaining length - 0x00,0x16, // packet Id - 0x00, 0x03, 'a', '/', 'b', // topic - }; - const uint32_t length = 9; - const char* topic = "a/b"; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, packetId, topic); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.UNSUBSCRIBE, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodeMultiUnsubscribe2() { - const uint8_t check[] = { - 0b10100010, // header - 0x0C, // remaining length - 0x00,0x16, // packet Id - 0x00, 0x03, 'a', '/', 'b', // topic1 - 0x00, 0x03, 'c', '/', 'd' // topic2 - }; - const uint32_t length = 14; - const char* topic1 = "a/b"; - const char* topic2 = "c/d"; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, packetId, topic1, topic2); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.UNSUBSCRIBE, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodeMultiUnsubscribe3() { - const uint8_t check[] = { - 0b10100010, // header - 0x11, // remaining length - 0x00,0x16, // packet Id - 0x00, 0x03, 'a', '/', 'b', // topic1 - 0x00, 0x03, 'c', '/', 'd', // topic2 - 0x00, 0x03, 'e', '/', 'f', // topic3 - }; - const uint32_t length = 19; - const char* topic1 = "a/b"; - const char* topic2 = "c/d"; - const char* topic3 = "e/f"; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, packetId, topic1, topic2, topic3); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.UNSUBSCRIBE, packet.packetType()); - TEST_ASSERT_FALSE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); -} - -void test_encodePingReq() { - const uint8_t check[] = { - 0b11000000, // header - 0x00 - }; - const uint32_t length = 2; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, PacketType.PINGREQ); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.PINGREQ, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(0, packet.packetId()); -} - -void test_encodeDisconnect() { - const uint8_t check[] = { - 0b11100000, // header - 0x00 - }; - const uint32_t length = 2; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, PacketType.DISCONNECT); - packet.setDup(); // no effect - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(length, packet.size()); - TEST_ASSERT_EQUAL_UINT8(PacketType.DISCONNECT, packet.packetType()); - TEST_ASSERT_TRUE(packet.removable()); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(0), length); - TEST_ASSERT_EQUAL_UINT16(0, packet.packetId()); -} - -size_t getData(uint8_t* dest, size_t len, size_t index) { - (void) index; - static uint8_t i = 1; - memset(dest, i, len); - ++i; - return len; -} - -void test_encodeChunkedPublish() { - const uint8_t check[] = { - 0b00110011, // header, dup, qos, retain - 0xCF, 0x01, // 7 + 200 = (0x4F * 1) & 0x40 + (0x01 * 128) - 0x00,0x03,'t','o','p', // topic - 0x00,0x16 // packet Id - }; - uint8_t payloadChunk[EMC_TX_BUFFER_SIZE] = {}; - memset(payloadChunk, 0x01, EMC_TX_BUFFER_SIZE); - const char* topic = "top"; - uint8_t qos = 1; - bool retain = true; - size_t headerLength = 10; - size_t payloadLength = 200; - size_t size = headerLength + payloadLength; - uint16_t packetId = 22; - espMqttClientTypes::Error error = espMqttClientTypes::Error::MISC_ERROR; - - Packet packet(error, - packetId, - topic, - getData, - payloadLength, - qos, - retain); - - TEST_ASSERT_EQUAL_UINT8(espMqttClientTypes::Error::SUCCESS, error); - TEST_ASSERT_EQUAL_UINT32(size, packet.size()); - TEST_ASSERT_EQUAL_UINT16(packetId, packet.packetId()); - - size_t available = 0; - size_t index = 0; - - // call 'available' before 'data' - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(headerLength + EMC_TX_BUFFER_SIZE, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, packet.data(index), headerLength); - - // index == first payload byte - index = headerLength; - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(EMC_TX_BUFFER_SIZE, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(payloadChunk, packet.data(index), available); - - // index == first payload byte - index = headerLength + 4; - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(EMC_TX_BUFFER_SIZE - 4, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(payloadChunk, packet.data(index), available); - - // index == last payload byte in first chunk - index = headerLength + EMC_TX_BUFFER_SIZE - 1; - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(1, available); - - // index == first payloadbyte in second chunk - memset(payloadChunk, 0x02, EMC_TX_BUFFER_SIZE); - index = headerLength + EMC_TX_BUFFER_SIZE; - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(EMC_TX_BUFFER_SIZE, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(payloadChunk, packet.data(index), available); - - memset(payloadChunk, 0x03, EMC_TX_BUFFER_SIZE); - index = headerLength + EMC_TX_BUFFER_SIZE + EMC_TX_BUFFER_SIZE + 10; - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(EMC_TX_BUFFER_SIZE, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(payloadChunk, packet.data(index), available); - - const uint8_t checkDup[] = { - 0b00111011, // header, dup, qos, retain - 0xCF, 0x01, // 7 + 200 = (0x4F * 0) + (0x01 * 128) - 0x00,0x03,'t','o','p', // topic - 0x00,0x16, // packet Id - }; - - index = 0; - packet.setDup(); - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(headerLength + EMC_TX_BUFFER_SIZE, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(checkDup, packet.data(index), headerLength); - - memset(payloadChunk, 0x04, EMC_TX_BUFFER_SIZE); - index = headerLength; - available = packet.available(index); - TEST_ASSERT_EQUAL_UINT32(EMC_TX_BUFFER_SIZE, available); - TEST_ASSERT_EQUAL_UINT8_ARRAY(payloadChunk, packet.data(index), available); -} - -int main() { - UNITY_BEGIN(); - RUN_TEST(test_encodeConnect0); - RUN_TEST(test_encodeConnect1); - RUN_TEST(test_encodeConnect2); - RUN_TEST(test_encodeConnectFail0); - RUN_TEST(test_encodePublish0); - RUN_TEST(test_encodePublish1); - RUN_TEST(test_encodePublish2); - RUN_TEST(test_encodePubAck); - RUN_TEST(test_encodePubRec); - RUN_TEST(test_encodePubRel); - RUN_TEST(test_encodePubComp); - RUN_TEST(test_encodeSubscribe); - RUN_TEST(test_encodeMultiSubscribe2); - RUN_TEST(test_encodeMultiSubscribe3); - RUN_TEST(test_encodeUnsubscribe); - RUN_TEST(test_encodeMultiUnsubscribe2); - RUN_TEST(test_encodeMultiUnsubscribe3); - RUN_TEST(test_encodePingReq); - RUN_TEST(test_encodeDisconnect); - RUN_TEST(test_encodeChunkedPublish); - return UNITY_END(); -} diff --git a/lib/espMqttClient/test/test_parser/test_parser.cpp b/lib/espMqttClient/test/test_parser/test_parser.cpp deleted file mode 100644 index ed51f92..0000000 --- a/lib/espMqttClient/test/test_parser/test_parser.cpp +++ /dev/null @@ -1,355 +0,0 @@ -#include - -#include - -using espMqttClientInternals::Parser; -using espMqttClientInternals::ParserResult; -using espMqttClientInternals::IncomingPacket; - -void setUp() {} -void tearDown() {} - -Parser parser; - -void test_Connack() { - const uint8_t stream[] = { - 0b00100000, // header - 0b00000010, // flags - 0b00000001, // session present - 0b00000000 // reserved - }; - const size_t length = 4; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(4, bytesRead); - TEST_ASSERT_EQUAL_UINT8(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT8(1, parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_Empty() { - const uint8_t stream[] = { - 0x00 - }; - const size_t length = 0; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_UINT8(ParserResult::awaitData, result); - TEST_ASSERT_EQUAL_INT32(0, bytesRead); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_Header() { - const uint8_t stream[] = { - 0x12, - 0x13, - 0x14 - }; - const size_t length = 3; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::protocolError, result); - TEST_ASSERT_EQUAL_UINT32(1, bytesRead); -} - -void test_Publish() { - uint8_t stream[] = { - 0b00110010, // header - 0x0B, // remaining length - 0x00, 0x03, 'a', '/', 'b', // topic - 0x00, 0x0A, // packet id - 0x01, 0x02 // payload - }; - size_t length = 11; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBLISH, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_STRING("a/b", parser.getPacket().variableHeader.topic); - TEST_ASSERT_EQUAL_UINT16(10, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.index); - TEST_ASSERT_EQUAL_UINT32(2, parser.getPacket().payload.length); - TEST_ASSERT_EQUAL_UINT32(4, parser.getPacket().payload.total); - TEST_ASSERT_EQUAL_UINT8(1, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); - - stream[0] = 0x03; - stream[1] = 0x04; - length = 2; - - bytesRead = 0; - result = parser.parse(stream, length, &bytesRead); - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_STRING("a/b", parser.getPacket().variableHeader.topic); - TEST_ASSERT_EQUAL_UINT16(10, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT32(2, parser.getPacket().payload.index); - TEST_ASSERT_EQUAL_UINT32(2, parser.getPacket().payload.length); - TEST_ASSERT_EQUAL_UINT32(4, parser.getPacket().payload.total); - TEST_ASSERT_EQUAL_UINT8(1, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_Publish_empty() { - uint8_t stream0[] = { - 0b00110000, // header - 0x05, // remaining length - 0x00, 0x03, 'a', '/', 'b', // topic - }; - size_t length0 = 7; - - size_t bytesRead0 = 0; - ParserResult result0 = parser.parse(stream0, length0, &bytesRead0); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result0); - TEST_ASSERT_EQUAL_UINT32(length0, bytesRead0); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBLISH, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_STRING("a/b", parser.getPacket().variableHeader.topic); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.index); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.length); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.total); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); - - uint8_t stream1[] = { - 0b00110000, // header - 0x05, // remaining length - 0x00, 0x03, 'a', '/', 'b', // topic - }; - size_t length1 = 7; - - size_t bytesRead1 = 0; - ParserResult result1 = parser.parse(stream1, length1, &bytesRead1); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result1); - TEST_ASSERT_EQUAL_UINT32(length1, bytesRead1); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBLISH, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_STRING("a/b", parser.getPacket().variableHeader.topic); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.index); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.length); - TEST_ASSERT_EQUAL_UINT32(0, parser.getPacket().payload.total); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); - -} - -void test_PubAck() { - const uint8_t stream[] = { - 0b01000000, - 0b00000010, - 0x12, - 0x34 - }; - const size_t length = 4; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBACK, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT16(4660, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_PubRec() { - const uint8_t stream[] = { - 0b01010000, - 0b00000010, - 0x56, - 0x78 - }; - const size_t length = 4; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_BITS(0xF0, espMqttClientInternals::PacketType.PUBREC, parser.getPacket().fixedHeader.packetType); - TEST_ASSERT_EQUAL_UINT16(22136, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_PubRel() { - const uint8_t stream[] = { - 0b01100010, - 0b00000010, - 0x9A, - 0xBC - }; - const size_t length = 4; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBREL, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT16(0x9ABC, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_PubComp() { - const uint8_t stream[] = { - 0b01110000, - 0b00000010, - 0xDE, - 0xF0 - }; - const size_t length = 4; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBCOMP, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT16(0xDEF0, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_SubAck() { - const uint8_t stream[] = { - 0b10010000, - 0b00000100, - 0x00, - 0x0A, - 0x02, - 0x01 - }; - const size_t length = 6; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.SUBACK, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT16(10, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT8_ARRAY(&stream[4], parser.getPacket().payload.data,2); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_UnsubAck() { - const uint8_t stream[] = { - 0b10110000, - 0b00000010, - 0x00, - 0x0A - }; - const size_t length = 4; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.UNSUBACK, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT16(10, parser.getPacket().variableHeader.fixed.packetId); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - - -void test_PingResp() { - const uint8_t stream[] = { - 0b11010000, - 0x00 - }; - const size_t length = 2; - - size_t bytesRead = 0; - ParserResult result = parser.parse(stream, length, &bytesRead); - - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT32(length, bytesRead); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PINGRESP, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -void test_longStream() { - const uint8_t stream[] = { - 0x90, 0x03, 0x00, 0x01, 0x00, 0x31, 0x0F, 0x00, 0x09, 0x66, 0x6F, 0x6F, 0x2F, 0x62, 0x61, 0x72, - 0x2F, 0x30, 0x74, 0x65, 0x73, 0x74, 0x90, 0x03, 0x00, 0x02, 0x01, 0x33, 0x11, 0x00, 0x09, 0x66, - 0x6F, 0x6F, 0x2F, 0x62, 0x61, 0x72, 0x2F, 0x31, 0x00, 0x01, 0x74, 0x65, 0x73, 0x74, 0x90, 0x03, - 0x00, 0x03, 0x02, 0x30, 0x0F, 0x00, 0x09, 0x66, 0x6F, 0x6F, 0x2F, 0x62, 0x61, 0x72, 0x2F, 0x30, - 0x74, 0x65, 0x73, 0x74, 0x32, 0x11, 0x00, 0x09, 0x66, 0x6F, 0x6F, 0x2F, 0x62, 0x61, 0x72, 0x2F, - 0x31, 0x00, 0x02, 0x74, 0x65, 0x73, 0x74, 0x40, 0x02, 0x00, 0x04, 0x50, 0x02, 0x00, 0x05 - }; - const size_t length = 94; - - size_t bytesRead = 0; - ParserResult result = parser.parse(&stream[bytesRead], length - bytesRead, &bytesRead); - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.SUBACK, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT32(5, bytesRead); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); - - result = parser.parse(&stream[bytesRead], length - bytesRead, &bytesRead); - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.PUBLISH, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT32(5 + 17, bytesRead); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_TRUE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); - - result = parser.parse(&stream[bytesRead], length - bytesRead, &bytesRead); - TEST_ASSERT_EQUAL_INT32(ParserResult::packet, result); - TEST_ASSERT_EQUAL_UINT8(espMqttClientInternals::PacketType.SUBACK, parser.getPacket().fixedHeader.packetType & 0xF0); - TEST_ASSERT_EQUAL_UINT32(5 + 17 + 5, bytesRead); - TEST_ASSERT_EQUAL_UINT8(0, parser.getPacket().qos()); - TEST_ASSERT_FALSE(parser.getPacket().retain()); - TEST_ASSERT_FALSE(parser.getPacket().dup()); -} - -int main() { - UNITY_BEGIN(); - RUN_TEST(test_Connack); - RUN_TEST(test_Empty); - RUN_TEST(test_Header); - RUN_TEST(test_Publish); - RUN_TEST(test_Publish_empty); - RUN_TEST(test_PubAck); - RUN_TEST(test_PubRec); - RUN_TEST(test_PubRel); - RUN_TEST(test_PubComp); - RUN_TEST(test_SubAck); - RUN_TEST(test_UnsubAck); - RUN_TEST(test_PingResp); - RUN_TEST(test_longStream); - return UNITY_END(); -} diff --git a/lib/espMqttClient/test/test_remainingLength/test_remainingLength.cpp b/lib/espMqttClient/test/test_remainingLength/test_remainingLength.cpp deleted file mode 100644 index d422b25..0000000 --- a/lib/espMqttClient/test/test_remainingLength/test_remainingLength.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include - -#include - -#include - -void setUp() {} -void tearDown() {} - -// Examples takes from MQTT specification -uint8_t bytes1[] = {0x40}; -uint8_t size1 = 1; -uint32_t length1 = 64; - -uint8_t bytes2[] = {193, 2}; -uint8_t size2 = 2; -uint32_t length2 = 321; - -uint8_t bytes3[] = {0xff, 0xff, 0xff, 0x7f}; -uint8_t size3 = 4; -uint32_t length3 = 268435455; - -void test_remainingLengthDecode() { - TEST_ASSERT_EQUAL_INT32(length1, espMqttClientInternals::decodeRemainingLength(bytes1)); - TEST_ASSERT_EQUAL_INT32(length2, espMqttClientInternals::decodeRemainingLength(bytes2)); - - uint8_t stream[] = {0x80, 0x80, 0x80, 0x01}; - TEST_ASSERT_EQUAL_INT32(2097152 , espMqttClientInternals::decodeRemainingLength(stream)); - - TEST_ASSERT_EQUAL_INT32(length3, espMqttClientInternals::decodeRemainingLength(bytes3)); -} - -void test_remainingLengthEncode() { - uint8_t bytes[4]; - - TEST_ASSERT_EQUAL_UINT8(1, espMqttClientInternals::remainingLengthLength(0)); - - TEST_ASSERT_EQUAL_UINT8(size1, espMqttClientInternals::remainingLengthLength(length1)); - TEST_ASSERT_EQUAL_UINT8(size1, espMqttClientInternals::encodeRemainingLength(length1, bytes)); - TEST_ASSERT_EQUAL_UINT8_ARRAY(bytes1, bytes, size1); - TEST_ASSERT_EQUAL_UINT8(size2, espMqttClientInternals::remainingLengthLength(length2)); - TEST_ASSERT_EQUAL_UINT8(size2, espMqttClientInternals::encodeRemainingLength(length2, bytes)); - TEST_ASSERT_EQUAL_UINT8_ARRAY(bytes2, bytes, size2); - TEST_ASSERT_EQUAL_UINT8(size3, espMqttClientInternals::remainingLengthLength(length3)); - TEST_ASSERT_EQUAL_UINT8(size3, espMqttClientInternals::encodeRemainingLength(length3, bytes)); - TEST_ASSERT_EQUAL_UINT8_ARRAY(bytes3, bytes, size3); -} - -void test_remainingLengthError() { - uint8_t bytes[] = {0xff, 0xff, 0xff, 0x80}; // high bit of last byte is 1 - // this indicates a next byte is coming - // which is a violation of the spec - TEST_ASSERT_EQUAL_UINT8(0, espMqttClientInternals::remainingLengthLength(268435456)); - TEST_ASSERT_EQUAL_INT32(-1, espMqttClientInternals::decodeRemainingLength(bytes)); -} - -int main() { - UNITY_BEGIN(); - RUN_TEST(test_remainingLengthDecode); - RUN_TEST(test_remainingLengthEncode); - RUN_TEST(test_remainingLengthError); - return UNITY_END(); -} diff --git a/lib/espMqttClient/test/test_string/test_string.cpp b/lib/espMqttClient/test/test_string/test_string.cpp deleted file mode 100644 index f171d77..0000000 --- a/lib/espMqttClient/test/test_string/test_string.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include - -#include - -#include - -void setUp() {} -void tearDown() {} - -void test_encodeString() { - const char test[] = "abcd"; - uint8_t buffer[6]; - const uint8_t check[] = {0x00, 0x04, 'a', 'b', 'c', 'd'}; - const uint32_t length = 6; - - TEST_ASSERT_EQUAL_UINT32(length, espMqttClientInternals::encodeString(test, buffer)); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, buffer, length); -} - -void test_emtpyString() { - const char test[] = ""; - uint8_t buffer[2]; - const uint8_t check[] = {0x00, 0x00}; - const uint32_t length = 2; - - TEST_ASSERT_EQUAL_UINT32(length, espMqttClientInternals::encodeString(test, buffer)); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, buffer, length); -} - -void test_longString() { - const size_t maxSize = 65535; - char test[maxSize + 1]; - test[maxSize] = '\0'; - memset(test, 'a', maxSize); - uint8_t buffer[maxSize + 3]; - uint8_t check[maxSize + 2]; - check[0] = 0xFF; - check[1] = 0xFF; - memset(&check[2], 'a', maxSize); - const uint32_t length = 2 + maxSize; - - TEST_ASSERT_EQUAL_UINT32(length, espMqttClientInternals::encodeString(test, buffer)); - TEST_ASSERT_EQUAL_UINT8_ARRAY(check, buffer, length); -} - -void test_tooLongString() { - const size_t maxSize = 65535; - char test[maxSize + 2]; - test[maxSize + 1] = '\0'; - memset(test, 'a', maxSize + 1); - uint8_t buffer[maxSize + 4]; // extra 4 bytes for headroom: test progam, don't test test - const uint32_t length = 0; - - TEST_ASSERT_EQUAL_UINT32(length, espMqttClientInternals::encodeString(test, buffer)); -} - -int main() { - UNITY_BEGIN(); - RUN_TEST(test_encodeString); - RUN_TEST(test_emtpyString); - RUN_TEST(test_longString); - RUN_TEST(test_tooLongString); - return UNITY_END(); -} diff --git a/platformio.ini b/platformio.ini index 2e5acd5..a357b42 100644 --- a/platformio.ini +++ b/platformio.ini @@ -27,6 +27,7 @@ board_build.partitions = partitions.csv build_unflags = -DCONFIG_BT_NIMBLE_LOG_LEVEL -DCONFIG_BTDM_BLE_SCAN_DUPL + -DESP32 -Werror=all -Wall build_flags = @@ -143,6 +144,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB + -DWM_DEBUG_LEVEL=4 -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND -DDEBUG_NUKI_CONNECT @@ -164,6 +166,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB + -DWM_DEBUG_LEVEL=4 -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND -DDEBUG_NUKI_CONNECT @@ -185,6 +188,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB + -DWM_DEBUG_LEVEL=4 -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND -DDEBUG_NUKI_CONNECT @@ -207,6 +211,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB + -DWM_DEBUG_LEVEL=4 -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND -DDEBUG_NUKI_CONNECT @@ -249,6 +254,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB + -DWM_DEBUG_LEVEL=4 -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND -DDEBUG_NUKI_CONNECT @@ -270,6 +276,7 @@ build_flags = -DCONFIG_NIMBLE_CPP_LOG_LEVEL=0 -DCONFIG_BT_NIMBLE_LOG_LEVEL=0 -DDEBUG_NUKIHUB + -DWM_DEBUG_LEVEL=4 -DDEBUG_SENSE_NUKI -DDEBUG_NUKI_COMMAND -DDEBUG_NUKI_CONNECT diff --git a/resources/ota_manifest.py b/resources/ota_manifest.py index 3e02fff..73eb0db 100644 --- a/resources/ota_manifest.py +++ b/resources/ota_manifest.py @@ -26,7 +26,7 @@ with open('ota/manifest.json', 'r+') as json_file: data[args.ota_type]['version'] = "No beta available" data[args.ota_type]['fullversion'] = "No beta available" data[args.ota_type]['build'] = "" - del(data[args.ota_type]['number']) + data[args.ota_type]['number'] = "0" else: if ("number" not in data[args.ota_type]): data[args.ota_type]['number'] = 1 diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 780d167..89c8474 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -82,4 +82,13 @@ CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE=y CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE=y -CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH="resources/github_root_ca.pem" \ No newline at end of file +CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH="resources/github_root_ca.pem" +CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH=y +CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024 +CONFIG_HTTPD_MAX_URI_LEN=512 +CONFIG_HTTPD_ERR_RESP_NO_DELAY=y +CONFIG_HTTPD_PURGE_BUF_LEN=32 +CONFIG_HTTPD_WS_SUPPORT=y +CONFIG_ESP_HTTPS_SERVER_ENABLE=y \ No newline at end of file diff --git a/src/Config.h b/src/Config.h index c90f772..ef6633d 100644 --- a/src/Config.h +++ b/src/Config.h @@ -4,7 +4,7 @@ #define NUKI_HUB_VERSION "9.02" #define NUKI_HUB_BUILD "unknownbuildnr" -#define NUKI_HUB_DATE "2024-10-15" +#define NUKI_HUB_DATE "2024-10-20" #define GITHUB_LATEST_RELEASE_URL (char*)"https://github.com/technyon/nuki_hub/releases/latest" #define GITHUB_OTA_MANIFEST_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/manifest.json" diff --git a/src/EspMillis.h b/src/EspMillis.h new file mode 100644 index 0000000..95c7c0e --- /dev/null +++ b/src/EspMillis.h @@ -0,0 +1,7 @@ +#pragma once +#include + +inline int64_t espMillis() +{ + return esp_timer_get_time() / 1000; +} \ No newline at end of file diff --git a/src/Gpio.cpp b/src/Gpio.cpp index eca41c2..8bf9f9e 100644 --- a/src/Gpio.cpp +++ b/src/Gpio.cpp @@ -10,10 +10,9 @@ #include "networkDevices/W5500Definitions.h" Gpio* Gpio::_inst = nullptr; -const uint Gpio::_debounceTime = GPIO_DEBOUNCE_TIME; Gpio::Gpio(Preferences* preferences) -: _preferences(preferences) + : _preferences(preferences) { _inst = this; loadPinConfiguration(); @@ -29,42 +28,50 @@ Gpio::Gpio(Preferences* preferences) bool Gpio::isTriggered(const PinEntry& entry) { +// Log->println(" ------------ "); + const int threshold = 3; - int state = digitalRead(entry.pin); + uint8_t state = digitalRead(entry.pin); + uint8_t lastState = (_triggerState[entry.pin] & 0x80) >> 7; - if(entry.role == PinRole::GeneralInputPullDown) + uint8_t pinState = _triggerState[entry.pin] & 0x7f; + pinState = pinState << 1 | state; + _triggerState[entry.pin] = (pinState & 0x7f) | lastState << 7; +// Log->print("Trigger state: "); +// Log->println(_triggerState[entry.pin], 2); + + pinState = pinState & 0x07; +// Log->print("Val: "); +// Log->println(pinState); + + + if(pinState != 0x00 && pinState != 0x07) { - state = 1 - state; + return false; } +// Log->print("Last State: "); +// Log->println(lastState); +// Log->print("State: "); +// Log->println(state); - if(state == LOW) + if(state != lastState) { - if (_triggerCount[entry.pin] >= 0) - { - _triggerCount[entry.pin]++; - } - - if (_triggerCount[entry.pin] >= threshold) - { - _triggerCount[entry.pin] = -1; - return true; - } +// Log->print("State changed: "); +// Log->println(state); + _triggerState[entry.pin] = (pinState & 0x7f) | state << 7; } else { - if (_triggerCount[entry.pin] < 0) - { - _triggerCount[entry.pin]--; - - if(_triggerCount[entry.pin] <= -threshold) - { - _triggerCount[entry.pin] = 0; - } - } + return false; } - return false; + if(entry.role == PinRole::GeneralInputPullDown || entry.role == PinRole::GeneralInputPullUp) + { + return true; + } + + return state == LOW; } void Gpio::onTimer() @@ -73,35 +80,35 @@ void Gpio::onTimer() { switch(entry.role) { - case PinRole::InputLock: - case PinRole::InputUnlock: - case PinRole::InputUnlatch: - case PinRole::InputLockNgo: - case PinRole::InputLockNgoUnlatch: - case PinRole::InputElectricStrikeActuation: - case PinRole::InputActivateRTO: - case PinRole::InputActivateCM: - case PinRole::InputDeactivateRtoCm: - case PinRole::InputDeactivateRTO: - case PinRole::InputDeactivateCM: - case PinRole::GeneralInputPullDown: - case PinRole::GeneralInputPullUp: - if(isTriggered(entry)) - { - _inst->notify(getGpioAction(entry.role), entry.pin); - } - break; - case PinRole::OutputHighLocked: - case PinRole::OutputHighUnlocked: - case PinRole::OutputHighMotorBlocked: - case PinRole::OutputHighRtoActive: - case PinRole::OutputHighCmActive: - case PinRole::OutputHighRtoOrCmActive: - case PinRole::GeneralOutput: - case PinRole::Ethernet: - // ignore. This case should not occur since pins are configured as output - default: - break; + case PinRole::InputLock: + case PinRole::InputUnlock: + case PinRole::InputUnlatch: + case PinRole::InputLockNgo: + case PinRole::InputLockNgoUnlatch: + case PinRole::InputElectricStrikeActuation: + case PinRole::InputActivateRTO: + case PinRole::InputActivateCM: + case PinRole::InputDeactivateRtoCm: + case PinRole::InputDeactivateRTO: + case PinRole::InputDeactivateCM: + case PinRole::GeneralInputPullDown: + case PinRole::GeneralInputPullUp: + if(isTriggered(entry)) + { + _inst->notify(getGpioAction(entry.role), entry.pin); + } + break; + case PinRole::OutputHighLocked: + case PinRole::OutputHighUnlocked: + case PinRole::OutputHighMotorBlocked: + case PinRole::OutputHighRtoActive: + case PinRole::OutputHighCmActive: + case PinRole::OutputHighRtoOrCmActive: + case PinRole::GeneralOutput: + case PinRole::Ethernet: + // ignore. This case should not occur since pins are configured as output + default: + break; } } } @@ -113,10 +120,10 @@ void Gpio::isrOnTimer() void Gpio::init() { - _inst->_triggerCount.reserve(_inst->availablePins().size()); + _inst->_triggerState.reserve(_inst->availablePins().size()); for(int i=0; i<_inst->availablePins().size(); i++) { - _inst->_triggerCount.push_back(0); + _inst->_triggerState.push_back(0); } bool hasInputPin = false; @@ -132,37 +139,37 @@ void Gpio::init() switch(entry.role) { - case PinRole::InputLock: - case PinRole::InputUnlock: - case PinRole::InputUnlatch: - case PinRole::InputLockNgo: - case PinRole::InputLockNgoUnlatch: - case PinRole::InputElectricStrikeActuation: - case PinRole::InputActivateRTO: - case PinRole::InputActivateCM: - case PinRole::InputDeactivateRtoCm: - case PinRole::InputDeactivateRTO: - case PinRole::InputDeactivateCM: - case PinRole::GeneralInputPullUp: - pinMode(entry.pin, INPUT_PULLUP); - hasInputPin = true; - break; - case PinRole::GeneralInputPullDown: - pinMode(entry.pin, INPUT_PULLDOWN); - hasInputPin = true; - break; - case PinRole::OutputHighLocked: - case PinRole::OutputHighUnlocked: - case PinRole::OutputHighMotorBlocked: - case PinRole::OutputHighRtoActive: - case PinRole::OutputHighCmActive: - case PinRole::OutputHighRtoOrCmActive: - case PinRole::GeneralOutput: - pinMode(entry.pin, OUTPUT); - break; - case PinRole::Ethernet: - default: - break; + case PinRole::InputLock: + case PinRole::InputUnlock: + case PinRole::InputUnlatch: + case PinRole::InputLockNgo: + case PinRole::InputLockNgoUnlatch: + case PinRole::InputElectricStrikeActuation: + case PinRole::InputActivateRTO: + case PinRole::InputActivateCM: + case PinRole::InputDeactivateRtoCm: + case PinRole::InputDeactivateRTO: + case PinRole::InputDeactivateCM: + case PinRole::GeneralInputPullUp: + pinMode(entry.pin, INPUT_PULLUP); + hasInputPin = true; + break; + case PinRole::GeneralInputPullDown: + pinMode(entry.pin, INPUT_PULLDOWN); + hasInputPin = true; + break; + case PinRole::OutputHighLocked: + case PinRole::OutputHighUnlocked: + case PinRole::OutputHighMotorBlocked: + case PinRole::OutputHighRtoActive: + case PinRole::OutputHighCmActive: + case PinRole::OutputHighRtoOrCmActive: + case PinRole::GeneralOutput: + pinMode(entry.pin, OUTPUT); + break; + case PinRole::Ethernet: + default: + break; } } @@ -214,7 +221,10 @@ void Gpio::loadPinConfiguration() if(std::find(disabledPins.begin(), disabledPins.end(), entry.pin) == disabledPins.end()) { - if(entry.role == PinRole::Ethernet) entry.role = PinRole::Disabled; + if(entry.role == PinRole::Ethernet) + { + entry.role = PinRole::Disabled; + } entry.role = (PinRole) serialized[(i * 2 + 1)]; Log->println("Not found in Ethernet disabled pins"); Log->print(F("Role: ")); @@ -227,7 +237,10 @@ void Gpio::loadPinConfiguration() Log->print(F("Role: ")); Log->println(getRoleDescription(entry.role)); } - if(entry.role != PinRole::Disabled) _pinConfiguration.push_back(entry); + if(entry.role != PinRole::Disabled) + { + _pinConfiguration.push_back(entry); + } } } @@ -237,90 +250,94 @@ const std::vector Gpio::getDisabledPins() const switch(_preferences->getInt(preference_network_hardware, 0)) { - case 2: - disabledPins.push_back(ETH_PHY_CS_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_IRQ_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_RST_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_SPI_MISO_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_SPI_MOSI_GENERIC_W5500); - break; - case 3: - disabledPins.push_back(ETH_PHY_CS_M5_W5500); - disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); - disabledPins.push_back(ETH_PHY_RST_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); - break; - case 10: - disabledPins.push_back(ETH_PHY_CS_M5_W5500_S3); - disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); - disabledPins.push_back(ETH_PHY_RST_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500_S3); - disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500_S3); - disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500_S3); - break; - case 9: - disabledPins.push_back(ETH_PHY_CS_ETH01EVO); - disabledPins.push_back(ETH_PHY_IRQ_ETH01EVO); - disabledPins.push_back(ETH_PHY_RST_ETH01EVO); - disabledPins.push_back(ETH_PHY_SPI_SCK_ETH01EVO); - disabledPins.push_back(ETH_PHY_SPI_MISO_ETH01EVO); - disabledPins.push_back(ETH_PHY_SPI_MOSI_ETH01EVO); - break; - case 6: - disabledPins.push_back(ETH_PHY_CS_M5_W5500); - disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); - disabledPins.push_back(ETH_PHY_RST_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); - break; - case 11: - disabledPins.push_back(_preferences->getInt(preference_network_custom_cs, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_irq, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_rst, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_sck, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_miso, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_mosi, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_pwr, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_mdc, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_mdio, -1)); - break; - #if defined(CONFIG_IDF_TARGET_ESP32) - case 4: - disabledPins.push_back(12); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - case 5: - disabledPins.push_back(16); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - case 8: - disabledPins.push_back(5); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - case 7: - disabledPins.push_back(-1); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - #endif - default: - break; + case 2: + disabledPins.push_back(ETH_PHY_CS_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_IRQ_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_RST_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_SPI_MISO_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_SPI_MOSI_GENERIC_W5500); + break; + case 3: + disabledPins.push_back(ETH_PHY_CS_M5_W5500); + disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); + disabledPins.push_back(ETH_PHY_RST_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); + break; + case 10: + disabledPins.push_back(ETH_PHY_CS_M5_W5500_S3); + disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); + disabledPins.push_back(ETH_PHY_RST_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500_S3); + disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500_S3); + disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500_S3); + break; + case 9: + disabledPins.push_back(ETH_PHY_CS_ETH01EVO); + disabledPins.push_back(ETH_PHY_IRQ_ETH01EVO); + disabledPins.push_back(ETH_PHY_RST_ETH01EVO); + disabledPins.push_back(ETH_PHY_SPI_SCK_ETH01EVO); + disabledPins.push_back(ETH_PHY_SPI_MISO_ETH01EVO); + disabledPins.push_back(ETH_PHY_SPI_MOSI_ETH01EVO); + break; + case 6: + disabledPins.push_back(ETH_PHY_CS_M5_W5500); + disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); + disabledPins.push_back(ETH_PHY_RST_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); + break; + case 11: + disabledPins.push_back(_preferences->getInt(preference_network_custom_cs, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_irq, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_rst, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_sck, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_miso, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_mosi, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_pwr, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_mdc, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_mdio, -1)); + break; +#if defined(CONFIG_IDF_TARGET_ESP32) + case 4: + disabledPins.push_back(12); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; + case 5: + disabledPins.push_back(16); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; + case 8: + disabledPins.push_back(5); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; + case 7: + disabledPins.push_back(-1); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; +#endif + default: + break; } Log->print(F("GPIO Ethernet disabled pins:")); for_each_n(disabledPins.begin(), disabledPins.size(), - [](int x) { Log->print(" "); Log->print(x); }); + [](int x) + { + Log->print(" "); + Log->print(x); + }); Log->println(); return disabledPins; } @@ -386,52 +403,52 @@ String Gpio::getRoleDescription(const PinRole& role) const { switch(role) { - case PinRole::Disabled: - return "Disabled"; - case PinRole::InputLock: - return "Input: Lock"; - case PinRole::InputUnlock: - return "Input: Unlock"; - case PinRole::InputUnlatch: - return "Input: Unlatch"; - case PinRole::InputLockNgo: - return "Input: Lock n Go"; - case PinRole::InputLockNgoUnlatch: - return "Input: Lock n Go and unlatch"; - case PinRole::InputElectricStrikeActuation: - return "Input: Electric strike actuation"; - case PinRole::InputActivateRTO: - return "Input: Activate RTO"; - case PinRole::InputActivateCM: - return "Input: Activate CM"; - case PinRole::InputDeactivateRtoCm: - return "Input: Deactivate RTO/CM"; - case PinRole::InputDeactivateRTO: - return "Input: Deactivate RTO"; - case PinRole::InputDeactivateCM: - return "Input: Deactivate CM"; - case PinRole::OutputHighLocked: - return "Output: High when locked"; - case PinRole::OutputHighUnlocked: - return "Output: High when unlocked"; - case PinRole::OutputHighMotorBlocked: - return "Output: High when motor blocked"; - case PinRole::OutputHighRtoActive: - return "Output: High when RTO active"; - case PinRole::OutputHighCmActive: - return "Output: High when CM active"; - case PinRole::OutputHighRtoOrCmActive: - return "Output: High when RTO or CM active"; - case PinRole::GeneralOutput: - return "General output"; - case PinRole::GeneralInputPullDown: - return "General input (Pull-down)"; - case PinRole::GeneralInputPullUp: - return "General input (Pull-up)"; - case PinRole::Ethernet: - return "Ethernet"; - default: - return "Unknown"; + case PinRole::Disabled: + return "Disabled"; + case PinRole::InputLock: + return "Input: Lock"; + case PinRole::InputUnlock: + return "Input: Unlock"; + case PinRole::InputUnlatch: + return "Input: Unlatch"; + case PinRole::InputLockNgo: + return "Input: Lock n Go"; + case PinRole::InputLockNgoUnlatch: + return "Input: Lock n Go and unlatch"; + case PinRole::InputElectricStrikeActuation: + return "Input: Electric strike actuation"; + case PinRole::InputActivateRTO: + return "Input: Activate RTO"; + case PinRole::InputActivateCM: + return "Input: Activate CM"; + case PinRole::InputDeactivateRtoCm: + return "Input: Deactivate RTO/CM"; + case PinRole::InputDeactivateRTO: + return "Input: Deactivate RTO"; + case PinRole::InputDeactivateCM: + return "Input: Deactivate CM"; + case PinRole::OutputHighLocked: + return "Output: High when locked"; + case PinRole::OutputHighUnlocked: + return "Output: High when unlocked"; + case PinRole::OutputHighMotorBlocked: + return "Output: High when motor blocked"; + case PinRole::OutputHighRtoActive: + return "Output: High when RTO active"; + case PinRole::OutputHighCmActive: + return "Output: High when CM active"; + case PinRole::OutputHighRtoOrCmActive: + return "Output: High when RTO or CM active"; + case PinRole::GeneralOutput: + return "General output"; + case PinRole::GeneralInputPullDown: + return "General input (Pull-down)"; + case PinRole::GeneralInputPullUp: + return "General input (Pull-up)"; + case PinRole::Ethernet: + return "Ethernet"; + default: + return "Unknown"; } } @@ -440,46 +457,47 @@ GpioAction Gpio::getGpioAction(const PinRole &role) const { switch(role) { - case PinRole::Disabled: - return GpioAction::None; - case PinRole::InputLock: - return GpioAction::Lock; - case PinRole::InputUnlock: - return GpioAction::Unlock; - case PinRole::InputUnlatch: - return GpioAction::Unlatch; - case PinRole::InputLockNgo: - return GpioAction::LockNgo; - case PinRole::InputLockNgoUnlatch: - return GpioAction::LockNgoUnlatch; - case PinRole::InputElectricStrikeActuation: - return GpioAction::ElectricStrikeActuation; - case PinRole::InputActivateRTO: - return GpioAction::ActivateRTO; - case PinRole::InputActivateCM: - return GpioAction::ActivateCM; - case PinRole::InputDeactivateRtoCm: - return GpioAction::DeactivateRtoCm; - case PinRole::InputDeactivateRTO: - return GpioAction::DeactivateRTO; - case PinRole::InputDeactivateCM: - return GpioAction::DeactivateCM; + case PinRole::Disabled: + return GpioAction::None; + case PinRole::InputLock: + return GpioAction::Lock; + case PinRole::InputUnlock: + return GpioAction::Unlock; + case PinRole::InputUnlatch: + return GpioAction::Unlatch; + case PinRole::InputLockNgo: + return GpioAction::LockNgo; + case PinRole::InputLockNgoUnlatch: + return GpioAction::LockNgoUnlatch; + case PinRole::InputElectricStrikeActuation: + return GpioAction::ElectricStrikeActuation; + case PinRole::InputActivateRTO: + return GpioAction::ActivateRTO; + case PinRole::InputActivateCM: + return GpioAction::ActivateCM; + case PinRole::InputDeactivateRtoCm: + return GpioAction::DeactivateRtoCm; + case PinRole::InputDeactivateRTO: + return GpioAction::DeactivateRTO; + case PinRole::InputDeactivateCM: + return GpioAction::DeactivateCM; - case PinRole::GeneralInputPullDown: - case PinRole::GeneralInputPullUp: - return GpioAction::GeneralInput; + case PinRole::GeneralInputPullDown: + case PinRole::GeneralInputPullUp: + return GpioAction::GeneralInput; - case PinRole::GeneralOutput: - case PinRole::Ethernet: - case PinRole::OutputHighLocked: - case PinRole::OutputHighUnlocked: - case PinRole::OutputHighMotorBlocked: - case PinRole::OutputHighRtoActive: - case PinRole::OutputHighCmActive: - case PinRole::OutputHighRtoOrCmActive: - default: - return GpioAction::None; - }} + case PinRole::GeneralOutput: + case PinRole::Ethernet: + case PinRole::OutputHighLocked: + case PinRole::OutputHighUnlocked: + case PinRole::OutputHighMotorBlocked: + case PinRole::OutputHighRtoActive: + case PinRole::OutputHighCmActive: + case PinRole::OutputHighRtoOrCmActive: + default: + return GpioAction::None; + } +} void Gpio::getConfigurationText(String& text, const std::vector& pinConfiguration, const String& linebreak) const diff --git a/src/Gpio.h b/src/Gpio.h index 2607df9..be54d16 100644 --- a/src/Gpio.h +++ b/src/Gpio.h @@ -84,6 +84,7 @@ private: void IRAM_ATTR onTimer(); bool IRAM_ATTR isTriggered(const PinEntry& pinEntry); GpioAction IRAM_ATTR getGpioAction(const PinRole& role) const; + static void IRAM_ATTR isrOnTimer(); #if defined(CONFIG_IDF_TARGET_ESP32C3) //Based on https://docs.espressif.com/projects/esp-idf/en/stable/esp32c3/api-reference/peripherals/gpio.html and https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf @@ -127,15 +128,12 @@ private: }; std::vector _pinConfiguration; - static const uint _debounceTime; - - static void IRAM_ATTR isrOnTimer(); std::vector> _callbacks; static Gpio* _inst; - std::vector _triggerCount; + std::vector _triggerState; hw_timer_t* timer = nullptr; Preferences* _preferences = nullptr; diff --git a/src/MqttReceiver.h b/src/MqttReceiver.h index 3db350d..5529cfa 100644 --- a/src/MqttReceiver.h +++ b/src/MqttReceiver.h @@ -5,5 +5,5 @@ class MqttReceiver { public: - virtual void onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) = 0; + virtual void onMqttDataReceived(char* topic, int topic_len, char* data, int data_len) = 0; }; \ No newline at end of file diff --git a/src/NukiDeviceId.cpp b/src/NukiDeviceId.cpp index 5c9bd42..6eb01bb 100644 --- a/src/NukiDeviceId.cpp +++ b/src/NukiDeviceId.cpp @@ -5,8 +5,8 @@ #include "PreferencesKeys.h" NukiDeviceId::NukiDeviceId(Preferences* preferences, const std::string& preferencesId) -: _preferences(preferences), - _preferencesId(preferencesId) + : _preferences(preferences), + _preferencesId(preferencesId) { _deviceId = _preferences->getUInt(_preferencesId.c_str(), 0); diff --git a/src/NukiNetwork.cpp b/src/NukiNetwork.cpp index 1aff483..dd73ca4 100644 --- a/src/NukiNetwork.cpp +++ b/src/NukiNetwork.cpp @@ -24,13 +24,13 @@ extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_ #ifndef NUKI_HUB_UPDATER NukiNetwork::NukiNetwork(Preferences *preferences, Gpio* gpio, const String& maintenancePathPrefix, char* buffer, size_t bufferSize) -: _preferences(preferences), - _gpio(gpio), - _buffer(buffer), - _bufferSize(bufferSize) + : _preferences(preferences), + _gpio(gpio), + _buffer(buffer), + _bufferSize(bufferSize) #else NukiNetwork::NukiNetwork(Preferences *preferences) -: _preferences(preferences) + : _preferences(preferences) #endif { // Remove obsolete W5500 hardware detection configuration @@ -43,7 +43,7 @@ NukiNetwork::NukiNetwork(Preferences *preferences) _webEnabled = _preferences->getBool(preference_webserver_enabled, true); _updateFromMQTT = _preferences->getBool(preference_update_from_mqtt, false); - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER memset(_maintenancePathPrefix, 0, sizeof(_maintenancePathPrefix)); size_t len = maintenancePathPrefix.length(); for(int i=0; i < len; i++) @@ -60,7 +60,7 @@ NukiNetwork::NukiNetwork(Preferences *preferences) { _mqttConnectionStateTopic[i] = connectionStateTopic.charAt(i); } - #endif +#endif setupDevice(); } @@ -69,33 +69,33 @@ void NukiNetwork::setupDevice() { _ipConfiguration = new IPConfiguration(_preferences); int hardwareDetect = _preferences->getInt(preference_network_hardware, 0); - Log->print(F("Hardware detect : ")); + Log->print(F("Hardware detect: ")); Log->println(hardwareDetect); _firstBootAfterDeviceChange = _preferences->getBool(preference_ntw_reconfigure, false); if(hardwareDetect == 0) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 hardwareDetect = 1; - #else +#else hardwareDetect = 11; - _preferences->putInt(preference_network_custom_addr, 1); - _preferences->putInt(preference_network_custom_cs, 8); - _preferences->putInt(preference_network_custom_irq, 9); - _preferences->putInt(preference_network_custom_rst, 10); - _preferences->putInt(preference_network_custom_sck, 11); - _preferences->putInt(preference_network_custom_miso, 12); - _preferences->putInt(preference_network_custom_mosi, 13); - _preferences->putBool(preference_ntw_reconfigure, true); - #endif + _preferences->putInt(preference_network_custom_addr, 1); + _preferences->putInt(preference_network_custom_cs, 8); + _preferences->putInt(preference_network_custom_irq, 9); + _preferences->putInt(preference_network_custom_rst, 10); + _preferences->putInt(preference_network_custom_sck, 11); + _preferences->putInt(preference_network_custom_miso, 12); + _preferences->putInt(preference_network_custom_mosi, 13); + _preferences->putBool(preference_ntw_reconfigure, true); +#endif _preferences->putInt(preference_network_hardware, hardwareDetect); } if(strcmp(WiFi_fallbackDetect, "wifi_fallback") == 0) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 - if(_preferences->getBool(preference_network_wifi_fallback_disabled) && !_firstBootAfterDeviceChange) +#ifndef CONFIG_IDF_TARGET_ESP32H2 + if(!_firstBootAfterDeviceChange) { Log->println(F("Failed to connect to network. Wi-Fi fallback is disabled, rebooting.")); memset(WiFi_fallbackDetect, 0, sizeof(WiFi_fallbackDetect)); @@ -105,14 +105,20 @@ void NukiNetwork::setupDevice() Log->println(F("Switching to Wi-Fi device as fallback.")); _networkDeviceType = NetworkDeviceType::WiFi; - #else +#else int custEth = _preferences->getInt(preference_network_custom_phy, 0); - if(custEth<3) custEth++; - else custEth = 0; + if(custEth<3) + { + custEth++; + } + else + { + custEth = 0; + } _preferences->putInt(preference_network_custom_phy, custEth); _preferences->putBool(preference_ntw_reconfigure, true); - #endif +#endif } else { @@ -122,19 +128,7 @@ void NukiNetwork::setupDevice() _device = NetworkDeviceInstantiator::Create(_networkDeviceType, _hostname, _preferences, _ipConfiguration); Log->print(F("Network device: ")); - Log->print(_device->deviceName()); - - -#ifndef NUKI_HUB_UPDATER - _device->mqttOnConnect([&](bool sessionPresent) - { - onMqttConnect(sessionPresent); - }); - _device->mqttOnDisconnect([&](espMqttClientTypes::DisconnectReason reason) - { - onMqttDisconnect(reason); - }); - #endif + Log->println(_device->deviceName()); } void NukiNetwork::reconfigureDevice() @@ -142,6 +136,16 @@ void NukiNetwork::reconfigureDevice() _device->reconfigure(); } +void NukiNetwork::scan(bool passive, bool async) +{ + _device->scan(passive, async); +} + +bool NukiNetwork::isApOpen() +{ + return _device->isApOpen(); +} + const String NukiNetwork::networkDeviceName() const { return _device->deviceName(); @@ -172,6 +176,11 @@ NetworkDevice *NukiNetwork::device() return _device; } +bool NukiNetwork::isConnected() +{ + return _device->isConnected(); +} + #ifdef NUKI_HUB_UPDATER void NukiNetwork::initialize() { @@ -242,26 +251,178 @@ void NukiNetwork::initialize() } } - Log->print(F("MQTT Broker: ")); - Log->print(_mqttBrokerAddr); - Log->print(F(":")); - Log->println(_mqttPort); - - _device->mqttSetClientId(_hostnameArr); - _device->mqttSetCleanSession(MQTT_CLEAN_SESSIONS); - _device->mqttSetKeepAlive(MQTT_KEEP_ALIVE); - - char gpioPath[250]; - bool rebGpio = rebuildGpio(); - - if(rebGpio) + if(strcmp(_mqttBrokerAddr, "") == 0) { - Log->println(F("Rebuild MQTT GPIO structure")); + Log->println(F("MQTT Broker not configured, aborting connection attempt.")); } - for (const auto &pinEntry: _gpio->pinConfiguration()) + else { - switch (pinEntry.role) + Log->print(F("MQTT Broker: ")); + Log->print(_mqttBrokerAddr); + Log->print(F(":")); + Log->println(_mqttPort); + + _mqtt_cfg.credentials.client_id = _hostnameArr; + _mqtt_cfg.session.disable_clean_session = !MQTT_CLEAN_SESSIONS; + _mqtt_cfg.session.keepalive = MQTT_KEEP_ALIVE; + + 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); + + if(caLength > 1) { + Log->println(F("MQTT over TLS.")); + + String uri = "mqtts://"; + uri.concat(_preferences->getString(preference_mqtt_broker, "")); + uri.concat(":"); + uri.concat(_preferences->getInt(preference_mqtt_broker_port, 8883)); + Log->print("URI: "); + Log->println(uri.c_str()); + //_mqtt_cfg.broker.address.uri = uri.c_str(); + _mqtt_cfg.broker.address.hostname = _mqttBrokerAddr; + _mqtt_cfg.broker.address.transport = MQTT_TRANSPORT_OVER_SSL; + _mqtt_cfg.broker.address.port = _preferences->getInt(preference_mqtt_broker_port, 8883); + _mqtt_cfg.broker.verification.certificate = _ca; + + if(crtLength > 1 && keyLength > 1) // length is 1 when empty + { + Log->println(F("MQTT with client certificate.")); + _mqtt_cfg.credentials.authentication.certificate = _cert; + _mqtt_cfg.credentials.authentication.key = _key; + } + } + else + { + Log->println(F("MQTT without TLS.")); + String uri = "mqtt://"; + uri.concat(_preferences->getString(preference_mqtt_broker, "")); + uri.concat(":"); + uri.concat(_preferences->getInt(preference_mqtt_broker_port, 1883)); + Log->print("URI: "); + Log->println(uri.c_str()); + //_mqtt_cfg.broker.address.uri = uri.c_str(); + _mqtt_cfg.broker.address.hostname = _mqttBrokerAddr; + _mqtt_cfg.broker.address.transport = MQTT_TRANSPORT_OVER_TCP; + _mqtt_cfg.broker.address.port = _preferences->getInt(preference_mqtt_broker_port, 1883); + } + + if(strlen(_mqttUser) == 0) + { + Log->println(F("MQTT: Connecting without credentials")); + } + else + { + Log->print(F("MQTT: Connecting with user: ")); + Log->println(_mqttUser); + _mqtt_cfg.credentials.username = _mqttUser; + _mqtt_cfg.credentials.authentication.password = _mqttPass; + } + + _mqtt_cfg.session.last_will.topic = _mqttConnectionStateTopic; + _mqtt_cfg.session.last_will.msg = _lastWillPayload; + _mqtt_cfg.session.last_will.msg_len = sizeof(_lastWillPayload); + _mqtt_cfg.session.last_will.qos = 1; + _mqtt_cfg.session.last_will.retain = true; + + _mqttClient = esp_mqtt_client_init(&_mqtt_cfg); + esp_mqtt_client_register_event(_mqttClient, (esp_mqtt_event_id_t)ESP_EVENT_ANY_ID, mqtt_event_handler_cb, NULL); + } + + _discoveryTopic = _preferences->getString(preference_mqtt_hass_discovery, ""); + _offEnabled = _preferences->getBool(preference_official_hybrid_enabled, false); + readSettings(); +} + +void NukiNetwork::readSettings() +{ + _restartOnDisconnect = _preferences->getBool(preference_restart_on_disconnect, false); + _checkUpdates = _preferences->getBool(preference_check_updates, false); + _rssiPublishInterval = _preferences->getInt(preference_rssi_publish_interval, 0) * 1000; + + if(_rssiPublishInterval == 0) + { + _rssiPublishInterval = 60000; + _preferences->putInt(preference_rssi_publish_interval, 60); + } + + _networkTimeout = _preferences->getInt(preference_network_timeout, 0); + if(_networkTimeout == 0) + { + _networkTimeout = -1; + _preferences->putInt(preference_network_timeout, _networkTimeout); + } + + _publishDebugInfo = _preferences->getBool(preference_publish_debug_info, false); +} + +bool NukiNetwork::update() +{ + int64_t ts = espMillis(); + _device->update(); + + if(!_mqttEnabled || _device->isApOpen()) + { + return true; + } + + if(!_device->isConnected() || (_mqttConnectCounter > 15 && !_firstConnect)) + { + _mqttConnectCounter = 0; + + if(!_webEnabled) + { + forceEnableWebServer = true; + } + if(_restartOnDisconnect && espMillis() > 60000) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } + } + + if(_device->isConnected() && !_mqttClientInitiated && strcmp(_mqttBrokerAddr, "") != 0) + { + Log->println(F("Attempting MQTT connection")); + esp_mqtt_client_start(_mqttClient); + + if(_preferences->getBool(preference_mqtt_log_enabled, false) || _preferences->getBool(preference_webserial_enabled, false)) + { + MqttLoggerMode mode; + + if(_preferences->getBool(preference_mqtt_log_enabled, false) && _preferences->getBool(preference_webserial_enabled, false)) + { + mode = MqttLoggerMode::MqttAndSerialAndWeb; + } + else if (_preferences->getBool(preference_webserial_enabled, false)) + { + mode = MqttLoggerMode::SerialAndWeb; + } + else + { + mode = MqttLoggerMode::MqttAndSerial; + } + + char* _path = new char[200]; + memset(_path, 0, sizeof(_path)); + + String pathStr = _preferences->getString(preference_mqtt_lock_path); + pathStr.concat(mqtt_topic_log); + strcpy(_path, pathStr.c_str()); + Log = new MqttLogger(_mqttClient, _path, mode); + } + + char gpioPath[250]; + bool rebGpio = rebuildGpio(); + + if(rebGpio) + { + Log->println(F("Rebuild MQTT GPIO structure")); + } + for (const auto &pinEntry: _gpio->pinConfiguration()) + { + switch (pinEntry.role) + { case PinRole::GeneralInputPullDown: case PinRole::GeneralInputPullUp: if(rebGpio) @@ -285,102 +446,30 @@ void NukiNetwork::initialize() break; default: break; + } } - } - _gpio->addCallback([this](const GpioAction& action, const int& pin) - { - gpioActionCallback(action, pin); - }); - - _discoveryTopic = _preferences->getString(preference_mqtt_hass_discovery, ""); - _offEnabled = _preferences->getBool(preference_official_hybrid_enabled, false); - readSettings(); -} - -void NukiNetwork::readSettings() -{ - _restartOnDisconnect = _preferences->getBool(preference_restart_on_disconnect, false); - _checkUpdates = _preferences->getBool(preference_check_updates, false); - _reconnectNetworkOnMqttDisconnect = _preferences->getBool(preference_recon_netw_on_mqtt_discon, false); - _rssiPublishInterval = _preferences->getInt(preference_rssi_publish_interval, 0) * 1000; - - if(_rssiPublishInterval == 0) - { - _rssiPublishInterval = 60000; - _preferences->putInt(preference_rssi_publish_interval, 60); - } - - _networkTimeout = _preferences->getInt(preference_network_timeout, 0); - if(_networkTimeout == 0) - { - _networkTimeout = -1; - _preferences->putInt(preference_network_timeout, _networkTimeout); - } - - _publishDebugInfo = _preferences->getBool(preference_publish_debug_info, false); -} - -bool NukiNetwork::update() -{ - int64_t ts = (esp_timer_get_time() / 1000); - _device->update(); - - if(!_mqttEnabled) - { - return true; - } - - if(!_device->isConnected() || (_mqttConnectCounter > 15 && _reconnectNetworkOnMqttDisconnect && !_firstConnect)) - { - _mqttConnectCounter = 0; - - if(_firstDisconnected) { - _firstDisconnected = false; - _device->mqttDisconnect(true); - } - - if(!_webEnabled) forceEnableWebServer = true; - if(_restartOnDisconnect && (esp_timer_get_time() / 1000) > 60000) restartEsp(RestartReason::RestartOnDisconnectWatchdog); - - Log->println(F("Network not connected. Trying reconnect.")); - ReconnectStatus reconnectStatus = _device->reconnect(true); - - switch(reconnectStatus) + _gpio->addCallback([this](const GpioAction& action, const int& pin) { - case ReconnectStatus::CriticalFailure: - strcpy(WiFi_fallbackDetect, "wifi_fallback"); - Log->println("Network device has a critical failure, enable fallback to Wi-Fi and reboot."); - delay(200); - restartEsp(RestartReason::NetworkDeviceCriticalFailure); - break; - case ReconnectStatus::Success: - memset(WiFi_fallbackDetect, 0, sizeof(WiFi_fallbackDetect)); - Log->print(F("Reconnect successful: IP: ")); - Log->println(_device->localIP()); - break; - case ReconnectStatus::Failure: - Log->println(F("Reconnect failed")); - break; - } + gpioActionCallback(action, pin); + }); } - if(_logIp && device()->isConnected() && !_device->localIP().equals("0.0.0.0")) + if(_logIp && _device->isConnected() && !_device->localIP().equals("0.0.0.0")) { _logIp = false; Log->print(F("IP: ")); Log->println(_device->localIP()); - _firstDisconnected = true; } - if(!_device->mqttConnected() && _device->isConnected()) + while(!_mqttConnected && _device->isConnected()) + { + delay(2000); + _mqttConnectCounter++; + return false; + } + + if(!_mqttConnected && _device->isConnected()) { - bool success = reconnect(); - if(!success) - { - delay(2000); - _mqttConnectCounter++; - return false; - } _mqttConnectCounter = 0; if(forceEnableWebServer && !_webEnabled) { @@ -388,15 +477,21 @@ bool NukiNetwork::update() delay(200); restartEsp(RestartReason::ReconfigureWebServer); } - else if(!_webEnabled) forceEnableWebServer = false; + else if(!_webEnabled) + { + forceEnableWebServer = false; + } delay(2000); } - if(!_device->mqttConnected() || !_device->isConnected()) + if(!_mqttConnected || !_device->isConnected()) { if(_networkTimeout > 0 && (ts - _lastConnectedTs > _networkTimeout * 1000) && ts > 60000) { - if(!_webEnabled) forceEnableWebServer = true; + if(!_webEnabled) + { + forceEnableWebServer = true; + } Log->println("Network timeout has been reached, restarting ..."); delay(200); restartEsp(RestartReason::NetworkTimeoutWatchdog); @@ -447,21 +542,26 @@ bool NukiNetwork::update() JsonDocument doc; NetworkClientSecure *client = new NetworkClientSecure; - if (client) { + if (client) + { client->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); { HTTPClient https; https.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); https.useHTTP10(true); - if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) { + if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) + { int httpResponseCode = https.GET(); if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_MOVED_PERMANENTLY) { DeserializationError jsonError = deserializeJson(doc, https.getStream()); - if (!jsonError) { otaManifestSuccess = true; } + if (!jsonError) + { + otaManifestSuccess = true; + } } } https.end(); @@ -473,14 +573,29 @@ bool NukiNetwork::update() { String currentVersion = NUKI_HUB_VERSION; - if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) _latestVersion = doc["release"]["fullversion"]; - else if(currentVersion.indexOf("beta") > 0) _latestVersion = doc["beta"]["fullversion"]; - else if(currentVersion.indexOf("master") > 0) _latestVersion = doc["master"]["fullversion"]; - else _latestVersion = doc["release"]["fullversion"]; + if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) + { + _latestVersion = doc["release"]["fullversion"]; + } + else if(currentVersion.indexOf("beta") > 0) + { + _latestVersion = doc["beta"]["fullversion"]; + } + else if(currentVersion.indexOf("master") > 0) + { + _latestVersion = doc["master"]["fullversion"]; + } + else + { + _latestVersion = doc["release"]["fullversion"]; + } publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_latest, _latestVersion, true); - if(strcmp(_latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) _preferences->putString(preference_latest_version, _latestVersion); + if(strcmp(_latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) + { + _preferences->putString(preference_latest_version, _latestVersion); + } } } } @@ -489,7 +604,7 @@ bool NukiNetwork::update() { uint8_t pin = gpioTs.first; int64_t ts = gpioTs.second; - if(ts != 0 && (((esp_timer_get_time() / 1000) - ts) >= GPIO_DEBOUNCE_TIME)) + if(ts != 0 && ((espMillis() - ts) >= GPIO_DEBOUNCE_TIME)) { _gpioTs[pin] = 0; @@ -508,131 +623,96 @@ bool NukiNetwork::update() return true; } - -void NukiNetwork::onMqttConnect(const bool &sessionPresent) +void NukiNetwork::mqtt_event_handler_cb(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { - _connectReplyReceived = true; + _inst->mqtt_event_handler(handler_args, base, event_id, event_data); } -void NukiNetwork::onMqttDisconnect(const espMqttClientTypes::DisconnectReason &reason) +void NukiNetwork::mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { - _connectReplyReceived = false; + static const char *MQTT_TAG = "mqtt"; - Log->print("MQTT disconnected. Reason: "); - switch(reason) + ESP_LOGD(MQTT_TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id); + esp_mqtt_event_handle_t event = (esp_mqtt_event_t*)event_data; + esp_mqtt_client_handle_t client = event->client; + int msg_id; + switch ((esp_mqtt_event_id_t)event_id) { - case espMqttClientTypes::DisconnectReason::USER_OK: - Log->println(F("USER_OK")); - break; - case espMqttClientTypes::DisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION: - Log->println(F("MQTT_UNACCEPTABLE_PROTOCOL_VERSION")); - break; - case espMqttClientTypes::DisconnectReason::MQTT_IDENTIFIER_REJECTED: - Log->println(F("MQTT_IDENTIFIER_REJECTED")); - break; - case espMqttClientTypes::DisconnectReason::MQTT_SERVER_UNAVAILABLE: - Log->println(F("MQTT_SERVER_UNAVAILABLE")); - break; - case espMqttClientTypes::DisconnectReason::MQTT_MALFORMED_CREDENTIALS: - Log->println(F("MQTT_MALFORMED_CREDENTIALS")); - break; - case espMqttClientTypes::DisconnectReason::MQTT_NOT_AUTHORIZED: - Log->println(F("MQTT_NOT_AUTHORIZED")); - break; - case espMqttClientTypes::DisconnectReason::TLS_BAD_FINGERPRINT: - Log->println(F("TLS_BAD_FINGERPRINT")); - break; - case espMqttClientTypes::DisconnectReason::TCP_DISCONNECTED: - Log->println(F("TCP_DISCONNECTED")); - break; - default: - Log->println(F("Unknown")); - break; + case MQTT_EVENT_CONNECTED: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_CONNECTED"); + Log->println("MQTT Connected"); + _mqttClientInitiated = true; + _mqttConnected = true; + reconnect(); + break; + case MQTT_EVENT_DISCONNECTED: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_DISCONNECTED"); + Log->println("MQTT Disconnected"); + _mqttConnected = false; + reconnect(); + break; + case MQTT_EVENT_SUBSCRIBED: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id); + break; + case MQTT_EVENT_UNSUBSCRIBED: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id); + break; + case MQTT_EVENT_PUBLISHED: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id); + break; + case MQTT_EVENT_DATA: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_DATA"); + //printf("TOPIC=%.*s\r\n", event->topic_len, event->topic); + //printf("DATA=%.*s\r\n", event->data_len, event->data); + onMqttDataReceived(event->topic, event->topic_len, event->data, event->data_len); + break; + case MQTT_EVENT_ERROR: + ESP_LOGI(MQTT_TAG, "MQTT_EVENT_ERROR"); + if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) + { + ESP_LOGI(MQTT_TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno)); + } + break; + default: + ESP_LOGI(MQTT_TAG, "Other event id:%d", event->event_id); + break; } } bool NukiNetwork::reconnect() { - _mqttConnectionState = 0; - - while (!_device->mqttConnected() && (esp_timer_get_time() / 1000) > _nextReconnect) + if (_mqttConnected) { - if(strcmp(_mqttBrokerAddr, "") == 0) + _mqttConnectedTs = millis(); + _mqttConnectionState = 1; + delay(100); + for(const String& topic : _subscribedTopics) { - Log->println(F("MQTT Broker not configured, aborting connection attempt.")); - _nextReconnect = (esp_timer_get_time() / 1000) + 5000; - return false; + esp_mqtt_client_subscribe(_mqttClient, topic.c_str(), MQTT_QOS_LEVEL); } - - Log->println(F("Attempting MQTT connection")); - - _connectReplyReceived = false; - - if(strlen(_mqttUser) == 0) + if(_firstConnect) { - Log->println(F("MQTT: Connecting without credentials")); - } - else - { - Log->print(F("MQTT: Connecting with user: ")); Log->println(_mqttUser); - _device->mqttSetCredentials(_mqttUser, _mqttPass); - } - - _device->setWill(_mqttConnectionStateTopic, 1, true, _lastWillPayload); - _device->mqttSetServer(_mqttBrokerAddr, _mqttPort); - _device->mqttConnect(); - - int64_t timeout = (esp_timer_get_time() / 1000) + 60000; - - while(!_connectReplyReceived && (esp_timer_get_time() / 1000) < timeout) - { - delay(50); - _device->update(); - if(_keepAliveCallback != nullptr) + _firstConnect = false; + publishString(_maintenancePathPrefix, mqtt_topic_network_device, _device->deviceName().c_str(), true); + for(const auto& it : _initTopics) { - _keepAliveCallback(); + esp_mqtt_client_publish(_mqttClient, it.first.c_str(), it.second.c_str(), 0, MQTT_QOS_LEVEL, 1); } } - if (_device->mqttConnected()) - { - Log->println(F("MQTT connected")); - _mqttConnectedTs = millis(); - _mqttConnectionState = 1; - delay(100); - _device->mqttOnMessage(NukiNetwork::onMqttDataReceivedCallback); - for(const String& topic : _subscribedTopics) - { - _device->mqttSubscribe(topic.c_str(), MQTT_QOS_LEVEL); - } - if(_firstConnect) - { - _firstConnect = false; - 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", true); + publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_ip, _device->localIP().c_str(), true); - 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) - { - callback(); - } - } - else + _mqttConnectionState = 2; + for(const auto& callback : _reconnectedCallbacks) { - Log->print(F("MQTT connect failed, rc=")); - _device->printError(); - _mqttConnectionState = 0; - _nextReconnect = (esp_timer_get_time() / 1000) + 5000; - //_device->mqttDisconnect(true); + callback(); } } + else + { + _mqttConnectionState = 0; + } return _mqttConnectionState > 0; } @@ -683,34 +763,26 @@ void NukiNetwork::registerMqttReceiver(MqttReceiver* receiver) _mqttReceivers.push_back(receiver); } -void NukiNetwork::onMqttDataReceivedCallback(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) +void NukiNetwork::onMqttDataReceived(char* topic, int topic_len, char* data, int data_len) { - uint8_t value[800] = {0}; - - size_t l = min(len, sizeof(value)-1); - - for(int i=0; ionMqttDataReceived(properties, topic, value, len, index, total); -} - -void NukiNetwork::onMqttDataReceived(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total) -{ - if(_mqttConnectedTs == -1 || (millis() - _mqttConnectedTs < 2000)) return; - - parseGpioTopics(properties, topic, payload, len, index, total); + parseGpioTopics(topic, topic_len, (char*)value, data_len); for(auto receiver : _mqttReceivers) { - receiver->onMqttDataReceived(topic, (byte*)payload, index); + receiver->onMqttDataReceived(topic, topic_len, (char*)value, data_len); } } -void NukiNetwork::parseGpioTopics(const espMqttClientTypes::MessageProperties &properties, const char *topic, const uint8_t *payload, size_t& len, size_t& index, size_t& total) +void NukiNetwork::parseGpioTopics(char* topic, int topic_len, char* data, int data_len) { char gpioPath[250]; buildMqttPath(gpioPath, {_lockPath.c_str(), mqtt_topic_gpio_prefix, mqtt_topic_gpio_pin}); @@ -729,7 +801,7 @@ void NukiNetwork::parseGpioTopics(const espMqttClientTypes::MessageProperties &p if(_gpio->getPinRole(pin) == PinRole::GeneralOutput) { - const uint8_t pinState = strcmp((const char*)payload, "1") == 0 ? HIGH : LOW; + const uint8_t pinState = strcmp(data, "1") == 0 ? HIGH : LOW; Log->print(F("GPIO ")); Log->print(pin); Log->print(F(" (Output) --> ")); @@ -742,7 +814,7 @@ void NukiNetwork::parseGpioTopics(const espMqttClientTypes::MessageProperties &p void NukiNetwork::gpioActionCallback(const GpioAction &action, const int &pin) { - _gpioTs[pin] = (esp_timer_get_time() / 1000); + _gpioTs[pin] = espMillis(); } void NukiNetwork::disableAutoRestarts() @@ -756,11 +828,6 @@ int NukiNetwork::mqttConnectionState() return _mqttConnectionState; } -bool NukiNetwork::encryptionSupported() -{ - return _device->supportsEncryption(); -} - bool NukiNetwork::mqttRecentlyConnected() { return _mqttConnectedTs != -1 && (millis() - _mqttConnectedTs < 6000); @@ -775,42 +842,62 @@ bool NukiNetwork::pathEquals(const char* prefix, const char* path, const char* r void NukiNetwork::publishFloat(const char* prefix, const char* topic, const float value, bool retain, const uint8_t precision) { + if(!_mqttClientInitiated) + { + return; + } char str[30]; dtostrf(value, 0, precision, str); char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); + esp_mqtt_client_publish(_mqttClient, path, str, 0, MQTT_QOS_LEVEL, retain); } void NukiNetwork::publishInt(const char* prefix, const char *topic, const int value, bool retain) { + if(!_mqttClientInitiated) + { + return; + } char str[30]; itoa(value, str, 10); char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); + esp_mqtt_client_publish(_mqttClient, path, str, 0, MQTT_QOS_LEVEL, retain); } void NukiNetwork::publishUInt(const char* prefix, const char *topic, const unsigned int value, bool retain) { + if(!_mqttClientInitiated) + { + return; + } char str[30]; utoa(value, str, 10); char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); + esp_mqtt_client_publish(_mqttClient, path, str, 0, MQTT_QOS_LEVEL, retain); } void NukiNetwork::publishULong(const char* prefix, const char *topic, const unsigned long value, bool retain) { + if(!_mqttClientInitiated) + { + return; + } char str[30]; utoa(value, str, 10); char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); + esp_mqtt_client_publish(_mqttClient, path, str, 0, MQTT_QOS_LEVEL, retain); } void NukiNetwork::publishLongLong(const char* prefix, const char *topic, int64_t value, bool retain) { + if(!_mqttClientInitiated) + { + return; + } static char result[21] = ""; memset(&result[0], 0, sizeof(result)); char temp[21] = ""; @@ -827,27 +914,39 @@ void NukiNetwork::publishLongLong(const char* prefix, const char *topic, int64_t } char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, result); + esp_mqtt_client_publish(_mqttClient, path, result, 0, MQTT_QOS_LEVEL, retain); } void NukiNetwork::publishBool(const char* prefix, const char *topic, const bool value, bool retain) { + if(!_mqttClientInitiated) + { + return; + } char str[2] = {0}; str[0] = value ? '1' : '0'; char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str); + esp_mqtt_client_publish(_mqttClient, path, str, 0, MQTT_QOS_LEVEL, retain); } bool NukiNetwork::publishString(const char* prefix, const char *topic, const char *value, bool retain) { + if(!_mqttClientInitiated) + { + return false; + } char path[200] = {0}; buildMqttPath(path, { prefix, topic }); - return _device->mqttPublish(path, MQTT_QOS_LEVEL, retain, value) > 0; + return esp_mqtt_client_publish(_mqttClient, path, value, 0, MQTT_QOS_LEVEL, retain) > 0; } 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) { + if(!_mqttClientInitiated) + { + return; + } JsonDocument json; json.clear(); JsonObject dev = json["dev"].to(); @@ -880,7 +979,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); - if((int)aclPrefs[2]) json["pl_open"] = openAction; + + if((strcmp(deviceType, "SmartLock") == 0 && (int)aclPrefs[2]) || (strcmp(deviceType, "SmartLock") != 0 && (int)aclPrefs[11])) + { + json["pl_open"] = openAction; + } json["stat_t"] = String("~") + mqtt_topic_lock_ha_state; json["stat_jam"] = "jammed"; @@ -899,7 +1002,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha path.concat(uidString); path.concat("/smartlock/config"); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); // Battery critical publishHassTopic("binary_sensor", @@ -915,9 +1018,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - {{(char*)"pl_on", (char*)"1"}, - {(char*)"pl_off", (char*)"0"}, - {(char*)"val_tpl", (char*)"{{value_json.critical}}" }}); + { + {(char*)"pl_on", (char*)"1"}, + {(char*)"pl_off", (char*)"0"}, + {(char*)"val_tpl", (char*)"{{value_json.critical}}" } + }); // Battery voltage publishHassTopic("sensor", @@ -933,8 +1038,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"V"}, - {(char*)"val_tpl", (char*)"{{value_json.batteryVoltage}}" }}); + { + {(char*)"unit_of_meas", (char*)"V"}, + {(char*)"val_tpl", (char*)"{{value_json.batteryVoltage}}" } + }); // Trigger publishHassTopic("sensor", @@ -950,7 +1057,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" } }); + { { (char*)"en", (char*)"true" } }); // MQTT Connected publishHassTopic("binary_sensor", @@ -966,9 +1073,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - {{(char*)"pl_on", (char*)"online"}, - {(char*)"pl_off", (char*)"offline"}, - {(char*)"ic", (char*)"mdi:lan-connect"}}); + { + {(char*)"pl_on", (char*)"online"}, + {(char*)"pl_off", (char*)"offline"}, + {(char*)"ic", (char*)"mdi:lan-connect"} + }); // Reset publishHassTopic("switch", @@ -984,13 +1093,15 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_reset, - { { (char*)"ic", (char*)"mdi:restart" }, - { (char*)"pl_on", (char*)"1" }, - { (char*)"pl_off", (char*)"0" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"ic", (char*)"mdi:restart" }, + { (char*)"pl_on", (char*)"1" }, + { (char*)"pl_off", (char*)"0" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); - // Network device + // Network device publishHassTopic("sensor", "network_device", uidString, @@ -1004,7 +1115,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); // Nuki Hub Webserver enabled publishHassTopic("switch", @@ -1020,12 +1131,14 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", _lockPath + mqtt_topic_webserver_action, - { { (char*)"pl_on", (char*)"1" }, - { (char*)"pl_off", (char*)"0" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"pl_on", (char*)"1" }, + { (char*)"pl_off", (char*)"0" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); - // Uptime + // Uptime publishHassTopic("sensor", "uptime", uidString, @@ -1035,15 +1148,18 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha baseTopic, _lockPath + mqtt_topic_uptime, deviceType, - "", + "duration", "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"unit_of_meas", (char*)"min"} + }); if(_preferences->getBool(preference_mqtt_log_enabled, false)) { - // MQTT Log + // MQTT Log publishHassTopic("sensor", "mqtt_log", uidString, @@ -1057,7 +1173,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); } else { @@ -1080,9 +1196,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { {(char*)"pl_on", (char*)"1"}, - {(char*)"pl_off", (char*)"0"}, - { (char*)"en", (char*)"true" }}); + { + {(char*)"pl_on", (char*)"1"}, + {(char*)"pl_off", (char*)"0"}, + { (char*)"en", (char*)"true" } + }); } else { @@ -1103,8 +1221,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Hardware version publishHassTopic("sensor", @@ -1120,8 +1240,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Nuki Hub version publishHassTopic("sensor", @@ -1137,8 +1259,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Nuki Hub build publishHassTopic("sensor", @@ -1154,8 +1278,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Nuki Hub restart reason publishHassTopic("sensor", @@ -1171,7 +1297,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); // Nuki Hub restart reason ESP publishHassTopic("sensor", @@ -1187,7 +1313,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); if(_checkUpdates) { @@ -1205,8 +1331,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // NUKI Hub update char latest_version_topic[250]; @@ -1228,10 +1356,12 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "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 }}); + { + { (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 { @@ -1248,11 +1378,13 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "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 }}); + { + { (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 @@ -1275,8 +1407,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:ip"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:ip"} + }); // Query Lock State publishHassTopic("button", @@ -1292,8 +1426,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_query_lockstate, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); // Query Config publishHassTopic("button", @@ -1309,8 +1445,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_query_config, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); // Query Lock State Command result publishHassTopic("button", @@ -1326,8 +1464,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_query_lockstate_command_result, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); publishHassTopic("sensor", "bluetooth_signal_strength", @@ -1342,11 +1482,15 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"dBm"} }); + { {(char*)"unit_of_meas", (char*)"dBm"} }); } void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) { + if(!_mqttClientInitiated) + { + return; + } uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); @@ -1375,8 +1519,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"unlatch" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"unlatch" } + }); } else { @@ -1399,8 +1545,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"lockNgo" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"lockNgo" } + }); } else { @@ -1423,8 +1571,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"lockNgoUnlatch" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"lockNgoUnlatch" } + }); } else { @@ -1445,8 +1595,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "diagnostic", String("~") + mqtt_topic_query_battery, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); if((int)basicLockConfigAclPrefs[6] == 1) { @@ -1464,13 +1616,15 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:led-variant-on" }, - { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:led-variant-on" }, + { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1493,13 +1647,15 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:radiobox-marked" }, - { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:radiobox-marked" }, + { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1522,12 +1678,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoLockEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"autoLockEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoLockEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoLockEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"autoLockEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoLockEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1550,12 +1708,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoUnLockDisabled\": \"0\"}" }, - { (char*)"pl_off", (char*)"{ \"autoUnLockDisabled\": \"1\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoUnLockDisabled}}" }, - { (char*)"stat_on", (char*)"0" }, - { (char*)"stat_off", (char*)"1" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoUnLockDisabled\": \"0\"}" }, + { (char*)"pl_off", (char*)"{ \"autoUnLockDisabled\": \"1\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoUnLockDisabled}}" }, + { (char*)"stat_on", (char*)"0" }, + { (char*)"stat_off", (char*)"1" } + }); } else { @@ -1578,12 +1738,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"singleLock\": \"0\"}" }, - { (char*)"pl_off", (char*)"{ \"singleLock\": \"1\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.singleLock}}" }, - { (char*)"stat_on", (char*)"0" }, - { (char*)"stat_off", (char*)"1" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"singleLock\": \"0\"}" }, + { (char*)"pl_off", (char*)"{ \"singleLock\": \"1\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.singleLock}}" }, + { (char*)"stat_on", (char*)"0" }, + { (char*)"stat_off", (char*)"1" } + }); } else { @@ -1603,8 +1765,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"%"}, - {(char*)"val_tpl", (char*)"{{value_json.level}}" }}); + { + {(char*)"unit_of_meas", (char*)"%"}, + {(char*)"val_tpl", (char*)"{{value_json.level}}" } + }); if((int)basicLockConfigAclPrefs[7] == 1) { @@ -1621,12 +1785,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:brightness-6" }, - { (char*)"cmd_tpl", (char*)"{ \"ledBrightness\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.ledBrightness}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:brightness-6" }, + { (char*)"cmd_tpl", (char*)"{ \"ledBrightness\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.ledBrightness}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"5" } + }); } else { @@ -1649,12 +1815,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoUnlatch\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"autoUnlatch\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoUnlatch}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoUnlatch\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"autoUnlatch\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoUnlatch}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1677,12 +1845,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1704,12 +1874,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:timer-cog-outline" }, - { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:timer-cog-outline" }, + { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -1732,12 +1904,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1755,7 +1929,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][4] = "Intelligent"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "fob_action_1", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -1773,7 +1947,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][4] = "Intelligent"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "fob_action_2", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -1791,7 +1965,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][4] = "Intelligent"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "fob_action_3", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -1808,7 +1982,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][3] = "Slowest"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "advertising_mode", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -1869,7 +2043,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "timezone", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -1891,11 +2065,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"unlockedPositionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.unlockedPositionOffsetDegrees}}" }, - { (char*)"min", (char*)"-90" }, - { (char*)"max", (char*)"180" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"unlockedPositionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.unlockedPositionOffsetDegrees}}" }, + { (char*)"min", (char*)"-90" }, + { (char*)"max", (char*)"180" } + }); } else { @@ -1917,11 +2093,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"lockedPositionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.lockedPositionOffsetDegrees}}" }, - { (char*)"min", (char*)"-180" }, - { (char*)"max", (char*)"90" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"lockedPositionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.lockedPositionOffsetDegrees}}" }, + { (char*)"min", (char*)"-180" }, + { (char*)"max", (char*)"90" } + }); } else { @@ -1943,11 +2121,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"singleLockedPositionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.singleLockedPositionOffsetDegrees}}" }, - { (char*)"min", (char*)"-180" }, - { (char*)"max", (char*)"180" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"singleLockedPositionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.singleLockedPositionOffsetDegrees}}" }, + { (char*)"min", (char*)"-180" }, + { (char*)"max", (char*)"180" } + }); } else { @@ -1969,11 +2149,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"unlockedToLockedTransitionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.unlockedToLockedTransitionOffsetDegrees}}" }, - { (char*)"min", (char*)"-180" }, - { (char*)"max", (char*)"180" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"unlockedToLockedTransitionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.unlockedToLockedTransitionOffsetDegrees}}" }, + { (char*)"min", (char*)"-180" }, + { (char*)"max", (char*)"180" } + }); } else { @@ -1995,11 +2177,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"lockNgoTimeout\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.lockNgoTimeout}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"lockNgoTimeout\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.lockNgoTimeout}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -2019,7 +2203,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][6] = "Show Status"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "single_button_press_action", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2039,7 +2223,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][6] = "Show Status"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "double_button_press_action", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2062,12 +2246,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"detachedCylinder\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"detachedCylinder\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.detachedCylinder}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"detachedCylinder\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"detachedCylinder\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.detachedCylinder}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2083,7 +2269,7 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons json["options"][2] = "Lithium"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "battery_type", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2106,12 +2292,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2133,11 +2321,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"unlatchDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.unlatchDuration}}" }, - { (char*)"min", (char*)"1" }, - { (char*)"max", (char*)"30" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"unlatchDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.unlatchDuration}}" }, + { (char*)"min", (char*)"1" }, + { (char*)"max", (char*)"30" } + }); } else { @@ -2159,11 +2349,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"autoLockTimeOut\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.autoLockTimeOut}}" }, - { (char*)"min", (char*)"30" }, - { (char*)"max", (char*)"1800" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"autoLockTimeOut\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.autoLockTimeOut}}" }, + { (char*)"min", (char*)"30" }, + { (char*)"max", (char*)"1800" } + }); } else { @@ -2186,12 +2378,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2214,12 +2408,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, - { (char*)"cmd_tpl", (char*)"{ \"nightModeStartTime\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeStartTime}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, + { (char*)"cmd_tpl", (char*)"{ \"nightModeStartTime\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeStartTime}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"5" } + }); } else { @@ -2242,12 +2438,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, - { (char*)"cmd_tpl", (char*)"{ \"nightModeEndTime\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeEndTime}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, + { (char*)"cmd_tpl", (char*)"{ \"nightModeEndTime\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeEndTime}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"5" } + }); } else { @@ -2270,12 +2468,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeAutoLockEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeAutoLockEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoLockEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeAutoLockEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeAutoLockEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoLockEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2298,12 +2498,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeAutoUnlockDisabled\": \"0\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeAutoUnlockDisabled\": \"1\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoUnlockDisabled}}" }, - { (char*)"stat_on", (char*)"0" }, - { (char*)"stat_off", (char*)"1" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeAutoUnlockDisabled\": \"0\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeAutoUnlockDisabled\": \"1\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoUnlockDisabled}}" }, + { (char*)"stat_on", (char*)"0" }, + { (char*)"stat_off", (char*)"1" } + }); } else { @@ -2326,12 +2528,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeImmediateLockOnStart\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeImmediateLockOnStart\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeImmediateLockOnStart}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeImmediateLockOnStart\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeImmediateLockOnStart\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeImmediateLockOnStart}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2354,12 +2558,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"immediateAutoLockEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"immediateAutoLockEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.immediateAutoLockEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"immediateAutoLockEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"immediateAutoLockEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.immediateAutoLockEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2382,12 +2588,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoUpdateEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"autoUpdateEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoUpdateEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoUpdateEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"autoUpdateEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoUpdateEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2397,6 +2605,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons void NukiNetwork::publishHASSConfigDoorSensor(char *deviceType, const char *baseTopic, char *name, char *uidString) { + if(!_mqttClientInitiated) + { + return; + } publishHassTopic("binary_sensor", "door_sensor", uidString, @@ -2410,13 +2622,19 @@ void NukiNetwork::publishHASSConfigDoorSensor(char *deviceType, const char *base "", "", "", - {{(char*)"pl_on", (char*)"doorOpened"}, - {(char*)"pl_off", (char*)"doorClosed"}, - {(char*)"pl_not_avail", (char*)"unavailable"}}); + { + {(char*)"pl_on", (char*)"doorOpened"}, + {(char*)"pl_off", (char*)"doorClosed"}, + {(char*)"pl_not_avail", (char*)"unavailable"} + }); } void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) { + if(!_mqttClientInitiated) + { + return; + } uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); uint32_t basicOpenerConfigAclPrefs[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; @@ -2444,8 +2662,10 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"electricStrikeActuation" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"electricStrikeActuation" } + }); } else { @@ -2465,8 +2685,10 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", "", - {{(char*)"pl_on", (char*)"on"}, - {(char*)"pl_off", (char*)"off"}}); + { + {(char*)"pl_on", (char*)"on"}, + {(char*)"pl_off", (char*)"off"} + }); if((int)aclPrefs[12] == 1 && (int)aclPrefs[13] == 1) { @@ -2483,11 +2705,13 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", String("~") + mqtt_topic_lock_action, - {{ (char*)"en", (char*)"true" }, - {(char*)"stat_on", (char*)"on"}, - {(char*)"stat_off", (char*)"off"}, - {(char*)"pl_on", (char*)"activateCM"}, - {(char*)"pl_off", (char*)"deactivateCM"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"stat_on", (char*)"on"}, + {(char*)"stat_off", (char*)"off"}, + {(char*)"pl_on", (char*)"activateCM"}, + {(char*)"pl_off", (char*)"deactivateCM"} + }); } else { @@ -2507,8 +2731,10 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", "", - {{(char*)"pl_on", (char*)"ring"}, - {(char*)"pl_off", (char*)"standby"}}); + { + {(char*)"pl_on", (char*)"ring"}, + {(char*)"pl_off", (char*)"standby"} + }); JsonDocument json; json = createHassJson(uidString, "_ring_event", "Ring", name, baseTopic, String("~") + mqtt_topic_lock_ring, deviceType, "doorbell", "", "", "", {{(char*)"val_tpl", (char*)"{ \"event_type\": \"{{ value }}\" }"}}); @@ -2516,7 +2742,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["event_types"][1] = "ringlocked"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("event", "ring", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); if((int)basicOpenerConfigAclPrefs[5] == 1) { @@ -2534,13 +2760,15 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:led-variant-on" }, - { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:led-variant-on" }, + { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2563,13 +2791,15 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:radiobox-marked" }, - { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:radiobox-marked" }, + { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2591,14 +2821,16 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:volume-source" }, - { (char*)"cmd_tpl", (char*)"{ \"soundLevel\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.soundLevel}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"255" }, - { (char*)"mode", (char*)"slider" }, - { (char*)"step", (char*)"25.5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:volume-source" }, + { (char*)"cmd_tpl", (char*)"{ \"soundLevel\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.soundLevel}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"255" }, + { (char*)"mode", (char*)"slider" }, + { (char*)"step", (char*)"25.5" } + }); } else { @@ -2621,12 +2853,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2648,12 +2882,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:timer-cog-outline" }, - { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:timer-cog-outline" }, + { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -2676,12 +2912,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2700,7 +2938,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][5] = "Ring"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "fob_action_1", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2719,7 +2957,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][5] = "Ring"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "fob_action_2", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2738,7 +2976,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][5] = "Ring"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "fob_action_3", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2755,7 +2993,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][3] = "Slowest"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "advertising_mode", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2816,7 +3054,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "timezone", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2845,7 +3083,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][15] = "Spare"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "operating_mode", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -2868,12 +3106,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"busModeSwitch\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"busModeSwitch\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.busModeSwitch}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"busModeSwitch\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"busModeSwitch\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.busModeSwitch}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2895,10 +3135,12 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"shortCircuitDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.shortCircuitDuration}}" }, - { (char*)"min", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"shortCircuitDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.shortCircuitDuration}}" }, + { (char*)"min", (char*)"0" } + }); } else { @@ -2920,12 +3162,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDelay\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDelay}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"min", (char*)"30000" }, - { (char*)"step", (char*)"3000" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDelay\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDelay}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"30000" }, + { (char*)"step", (char*)"3000" } + }); } else { @@ -2948,12 +3192,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"randomElectricStrikeDelay\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"randomElectricStrikeDelay\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.randomElectricStrikeDelay}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"randomElectricStrikeDelay\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"randomElectricStrikeDelay\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.randomElectricStrikeDelay}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2975,12 +3221,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDuration}}" }, - { (char*)"min", (char*)"1000" }, - { (char*)"min", (char*)"30000" }, - { (char*)"step", (char*)"3000" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDuration}}" }, + { (char*)"min", (char*)"1000" }, + { (char*)"max", (char*)"30000" }, + { (char*)"step", (char*)"3000" } + }); } else { @@ -3003,12 +3251,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"disableRtoAfterRing\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"disableRtoAfterRing\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.disableRtoAfterRing}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"disableRtoAfterRing\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"disableRtoAfterRing\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.disableRtoAfterRing}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3030,11 +3280,13 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"rtoTimeout\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.rtoTimeout}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"min", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"rtoTimeout\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.rtoTimeout}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -3055,7 +3307,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][7] = "CM & RTO & Ring"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "doorbell_suppression", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3077,12 +3329,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"doorbellSuppressionDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.doorbellSuppressionDuration}}" }, - { (char*)"min", (char*)"500" }, - { (char*)"min", (char*)"10000" }, - { (char*)"step", (char*)"1000" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"doorbellSuppressionDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.doorbellSuppressionDuration}}" }, + { (char*)"min", (char*)"500" }, + { (char*)"max", (char*)"10000" }, + { (char*)"step", (char*)"1000" } + }); } else { @@ -3099,7 +3353,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][3] = "Sound 3"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "sound_ring", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3116,7 +3370,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][3] = "Sound 3"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "sound_open", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3133,7 +3387,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][3] = "Sound 3"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "sound_rto", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3150,7 +3404,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][3] = "Sound 3"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "sound_cm", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3173,12 +3427,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"soundConfirmation\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"soundConfirmation\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.soundConfirmation}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"soundConfirmation\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"soundConfirmation\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.soundConfirmation}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3199,7 +3455,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][7] = "Open"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "single_button_press_action", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3220,7 +3476,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][7] = "Open"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "double_button_press_action", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3236,7 +3492,7 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co json["options"][2] = "Lithium"; serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath("select", "battery_type", uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } else { @@ -3259,12 +3515,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3287,8 +3545,10 @@ void NukiNetwork::publishHASSConfigAccessLog(char *deviceType, const char *baseT "", "diagnostic", "", - { { (char*)"ic", (char*)"mdi:format-list-bulleted" }, - { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'LockAction')|selectattr('action', 'in', ['Lock', 'Unlock', 'Unlatch'])|first|default).authorizationName|default }}" }}); + { + { (char*)"ic", (char*)"mdi:format-list-bulleted" }, + { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'LockAction')|selectattr('action', 'in', ['Lock', 'Unlock', 'Unlatch'])|first|default).authorizationName|default }}" } + }); String rollingSate = "~"; rollingSate.concat(mqtt_topic_lock_log_rolling); @@ -3307,30 +3567,34 @@ void NukiNetwork::publishHASSConfigAccessLog(char *deviceType, const char *baseT "", "diagnostic", "", - { { (char*)"ic", (char*)"mdi:format-list-bulleted" }, - { (char*)"json_attr_t", (char*)rollingStateChr }, - { (char*)"val_tpl", (char*)"{{value_json.index}}" }}); + { + { (char*)"ic", (char*)"mdi:format-list-bulleted" }, + { (char*)"json_attr_t", (char*)rollingStateChr }, + { (char*)"val_tpl", (char*)"{{value_json.index}}" } + }); } void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopic, char *name, char *uidString) { // Keypad battery critical - publishHassTopic("binary_sensor", - "keypad_battery_low", - uidString, - "_keypad_battery_low", - "Keypad battery low", - name, - baseTopic, - String("~") + mqtt_topic_battery_basic_json, - deviceType, - "battery", - "", - "diagnostic", - "", - {{(char*)"pl_on", (char*)"1"}, - {(char*)"pl_off", (char*)"0"}, - {(char*)"val_tpl", (char*)"{{value_json.keypadCritical}}" }}); + publishHassTopic("binary_sensor", + "keypad_battery_low", + uidString, + "_keypad_battery_low", + "Keypad battery low", + name, + baseTopic, + String("~") + mqtt_topic_battery_basic_json, + deviceType, + "battery", + "", + "diagnostic", + "", + { + {(char*)"pl_on", (char*)"1"}, + {(char*)"pl_off", (char*)"0"}, + {(char*)"val_tpl", (char*)"{{value_json.keypadCritical}}" } + }); // Query Keypad publishHassTopic("button", @@ -3346,8 +3610,10 @@ void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopi "", "diagnostic", String("~") + mqtt_topic_query_keypad, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); publishHassTopic("sensor", "keypad_status", @@ -3362,8 +3628,10 @@ void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopi "", "diagnostic", "", - { { (char*)"ic", (char*)"mdi:drag-vertical" }, - { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'KeypadAction')|first|default).completionStatus|default }}" }}); + { + { (char*)"ic", (char*)"mdi:drag-vertical" }, + { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'KeypadAction')|first|default).completionStatus|default }}" } + }); } void NukiNetwork::publishHASSWifiRssiConfig(char *deviceType, const char *baseTopic, char *name, char *uidString) @@ -3386,32 +3654,36 @@ void NukiNetwork::publishHASSWifiRssiConfig(char *deviceType, const char *baseTo "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"dBm"} }); + { {(char*)"unit_of_meas", (char*)"dBm"} }); } void NukiNetwork::publishHassTopic(const String& mqttDeviceType, - const String& mqttDeviceName, - const String& uidString, - const String& uidStringPostfix, - const String& displayName, - const String& name, - const String& baseTopic, - const String& stateTopic, - const String& deviceType, - const String& deviceClass, - const String& stateClass, - const String& entityCat, - const String& commandTopic, - std::vector> additionalEntries -) + const String& mqttDeviceName, + const String& uidString, + const String& uidStringPostfix, + const String& displayName, + const String& name, + const String& baseTopic, + const String& stateTopic, + const String& deviceType, + const String& deviceClass, + const String& stateClass, + const String& entityCat, + const String& commandTopic, + std::vector> additionalEntries + ) { + if(!_mqttClientInitiated) + { + return; + } if (_discoveryTopic != "") { JsonDocument json; json = createHassJson(uidString, uidStringPostfix, displayName, name, baseTopic, stateTopic, deviceType, deviceClass, stateClass, entityCat, commandTopic, additionalEntries); serializeJson(json, _buffer, _bufferSize); String path = createHassTopicPath(mqttDeviceType, mqttDeviceName, uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, _buffer); + esp_mqtt_client_publish(_mqttClient, path.c_str(), _buffer, 0, MQTT_QOS_LEVEL, 1); } } @@ -3431,23 +3703,31 @@ String NukiNetwork::createHassTopicPath(const String& mqttDeviceType, const Stri void NukiNetwork::removeHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString) { + if(!_mqttClientInitiated) + { + return; + } if (_discoveryTopic != "") { String path = createHassTopicPath(mqttDeviceType, mqttDeviceName, uidString); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, ""); + esp_mqtt_client_publish(_mqttClient, path.c_str(), "", 0, MQTT_QOS_LEVEL, 1); } } void NukiNetwork::removeTopic(const String& mqttPath, const String& mqttTopic) { + if(!_mqttClientInitiated) + { + return; + } String path = mqttPath; path.concat(mqttTopic); - _device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, ""); + esp_mqtt_client_publish(_mqttClient, path.c_str(), "", 0, MQTT_QOS_LEVEL, 1); - #ifdef DEBUG_NUKIHUB +#ifdef DEBUG_NUKIHUB Log->print(F("Removing MQTT topic: ")); Log->println(path.c_str()); - #endif +#endif } @@ -3553,18 +3833,18 @@ void NukiNetwork::removeHASSConfigTopic(char *deviceType, char *name, char *uidS } JsonDocument NukiNetwork::createHassJson(const String& uidString, - const String& uidStringPostfix, - const String& displayName, - const String& name, - const String& baseTopic, - const String& stateTopic, - const String& deviceType, - const String& deviceClass, - const String& stateClass, - const String& entityCat, - const String& commandTopic, - std::vector> additionalEntries -) + const String& uidStringPostfix, + const String& displayName, + const String& name, + const String& baseTopic, + const String& stateTopic, + const String& deviceType, + const String& deviceClass, + const String& stateClass, + const String& entityCat, + const String& commandTopic, + std::vector> additionalEntries + ) { JsonDocument json; json.clear(); @@ -3624,195 +3904,205 @@ JsonDocument NukiNetwork::createHassJson(const String& uidString, return json; } -void NukiNetwork::batteryTypeToString(const Nuki::BatteryType battype, char* str) { - switch (battype) { +void NukiNetwork::batteryTypeToString(const Nuki::BatteryType battype, char* str) +{ + switch (battype) + { case Nuki::BatteryType::Alkali: - strcpy(str, "Alkali"); - break; + strcpy(str, "Alkali"); + break; case Nuki::BatteryType::Accumulators: - strcpy(str, "Accumulators"); - break; + strcpy(str, "Accumulators"); + break; case Nuki::BatteryType::Lithium: - strcpy(str, "Lithium"); - break; + strcpy(str, "Lithium"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetwork::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str) { - switch (advmode) { +void NukiNetwork::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str) +{ + switch (advmode) + { case Nuki::AdvertisingMode::Automatic: - strcpy(str, "Automatic"); - break; + strcpy(str, "Automatic"); + break; case Nuki::AdvertisingMode::Normal: - strcpy(str, "Normal"); - break; + strcpy(str, "Normal"); + break; case Nuki::AdvertisingMode::Slow: - strcpy(str, "Slow"); - break; + strcpy(str, "Slow"); + break; case Nuki::AdvertisingMode::Slowest: - strcpy(str, "Slowest"); - break; + strcpy(str, "Slowest"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetwork::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) { - switch (timeZoneId) { +void NukiNetwork::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) +{ + switch (timeZoneId) + { case Nuki::TimeZoneId::Africa_Cairo: - strcpy(str, "Africa/Cairo"); - break; + strcpy(str, "Africa/Cairo"); + break; case Nuki::TimeZoneId::Africa_Lagos: - strcpy(str, "Africa/Lagos"); - break; + strcpy(str, "Africa/Lagos"); + break; case Nuki::TimeZoneId::Africa_Maputo: - strcpy(str, "Africa/Maputo"); - break; + strcpy(str, "Africa/Maputo"); + break; case Nuki::TimeZoneId::Africa_Nairobi: - strcpy(str, "Africa/Nairobi"); - break; + strcpy(str, "Africa/Nairobi"); + break; case Nuki::TimeZoneId::America_Anchorage: - strcpy(str, "America/Anchorage"); - break; + strcpy(str, "America/Anchorage"); + break; case Nuki::TimeZoneId::America_Argentina_Buenos_Aires: - strcpy(str, "America/Argentina/Buenos_Aires"); - break; + strcpy(str, "America/Argentina/Buenos_Aires"); + break; case Nuki::TimeZoneId::America_Chicago: - strcpy(str, "America/Chicago"); - break; + strcpy(str, "America/Chicago"); + break; case Nuki::TimeZoneId::America_Denver: - strcpy(str, "America/Denver"); - break; + strcpy(str, "America/Denver"); + break; case Nuki::TimeZoneId::America_Halifax: - strcpy(str, "America/Halifax"); - break; + strcpy(str, "America/Halifax"); + break; case Nuki::TimeZoneId::America_Los_Angeles: - strcpy(str, "America/Los_Angeles"); - break; + strcpy(str, "America/Los_Angeles"); + break; case Nuki::TimeZoneId::America_Manaus: - strcpy(str, "America/Manaus"); - break; + strcpy(str, "America/Manaus"); + break; case Nuki::TimeZoneId::America_Mexico_City: - strcpy(str, "America/Mexico_City"); - break; + strcpy(str, "America/Mexico_City"); + break; case Nuki::TimeZoneId::America_New_York: - strcpy(str, "America/New_York"); - break; + strcpy(str, "America/New_York"); + break; case Nuki::TimeZoneId::America_Phoenix: - strcpy(str, "America/Phoenix"); - break; + strcpy(str, "America/Phoenix"); + break; case Nuki::TimeZoneId::America_Regina: - strcpy(str, "America/Regina"); - break; + strcpy(str, "America/Regina"); + break; case Nuki::TimeZoneId::America_Santiago: - strcpy(str, "America/Santiago"); - break; + strcpy(str, "America/Santiago"); + break; case Nuki::TimeZoneId::America_Sao_Paulo: - strcpy(str, "America/Sao_Paulo"); - break; + strcpy(str, "America/Sao_Paulo"); + break; case Nuki::TimeZoneId::America_St_Johns: - strcpy(str, "America/St_Johns"); - break; + strcpy(str, "America/St_Johns"); + break; case Nuki::TimeZoneId::Asia_Bangkok: - strcpy(str, "Asia/Bangkok"); - break; + strcpy(str, "Asia/Bangkok"); + break; case Nuki::TimeZoneId::Asia_Dubai: - strcpy(str, "Asia/Dubai"); - break; + strcpy(str, "Asia/Dubai"); + break; case Nuki::TimeZoneId::Asia_Hong_Kong: - strcpy(str, "Asia/Hong_Kong"); - break; + strcpy(str, "Asia/Hong_Kong"); + break; case Nuki::TimeZoneId::Asia_Jerusalem: - strcpy(str, "Asia/Jerusalem"); - break; + strcpy(str, "Asia/Jerusalem"); + break; case Nuki::TimeZoneId::Asia_Karachi: - strcpy(str, "Asia/Karachi"); - break; + strcpy(str, "Asia/Karachi"); + break; case Nuki::TimeZoneId::Asia_Kathmandu: - strcpy(str, "Asia/Kathmandu"); - break; + strcpy(str, "Asia/Kathmandu"); + break; case Nuki::TimeZoneId::Asia_Kolkata: - strcpy(str, "Asia/Kolkata"); - break; + strcpy(str, "Asia/Kolkata"); + break; case Nuki::TimeZoneId::Asia_Riyadh: - strcpy(str, "Asia/Riyadh"); - break; + strcpy(str, "Asia/Riyadh"); + break; case Nuki::TimeZoneId::Asia_Seoul: - strcpy(str, "Asia/Seoul"); - break; + strcpy(str, "Asia/Seoul"); + break; case Nuki::TimeZoneId::Asia_Shanghai: - strcpy(str, "Asia/Shanghai"); - break; + strcpy(str, "Asia/Shanghai"); + break; case Nuki::TimeZoneId::Asia_Tehran: - strcpy(str, "Asia/Tehran"); - break; + strcpy(str, "Asia/Tehran"); + break; case Nuki::TimeZoneId::Asia_Tokyo: - strcpy(str, "Asia/Tokyo"); - break; + strcpy(str, "Asia/Tokyo"); + break; case Nuki::TimeZoneId::Asia_Yangon: - strcpy(str, "Asia/Yangon"); - break; + strcpy(str, "Asia/Yangon"); + break; case Nuki::TimeZoneId::Australia_Adelaide: - strcpy(str, "Australia/Adelaide"); - break; + strcpy(str, "Australia/Adelaide"); + break; case Nuki::TimeZoneId::Australia_Brisbane: - strcpy(str, "Australia/Brisbane"); - break; + strcpy(str, "Australia/Brisbane"); + break; case Nuki::TimeZoneId::Australia_Darwin: - strcpy(str, "Australia/Darwin"); - break; + strcpy(str, "Australia/Darwin"); + break; case Nuki::TimeZoneId::Australia_Hobart: - strcpy(str, "Australia/Hobart"); - break; + strcpy(str, "Australia/Hobart"); + break; case Nuki::TimeZoneId::Australia_Perth: - strcpy(str, "Australia/Perth"); - break; + strcpy(str, "Australia/Perth"); + break; case Nuki::TimeZoneId::Australia_Sydney: - strcpy(str, "Australia/Sydney"); - break; + strcpy(str, "Australia/Sydney"); + break; case Nuki::TimeZoneId::Europe_Berlin: - strcpy(str, "Europe/Berlin"); - break; + strcpy(str, "Europe/Berlin"); + break; case Nuki::TimeZoneId::Europe_Helsinki: - strcpy(str, "Europe/Helsinki"); - break; + strcpy(str, "Europe/Helsinki"); + break; case Nuki::TimeZoneId::Europe_Istanbul: - strcpy(str, "Europe/Istanbul"); - break; + strcpy(str, "Europe/Istanbul"); + break; case Nuki::TimeZoneId::Europe_London: - strcpy(str, "Europe/London"); - break; + strcpy(str, "Europe/London"); + break; case Nuki::TimeZoneId::Europe_Moscow: - strcpy(str, "Europe/Moscow"); - break; + strcpy(str, "Europe/Moscow"); + break; case Nuki::TimeZoneId::Pacific_Auckland: - strcpy(str, "Pacific/Auckland"); - break; + strcpy(str, "Pacific/Auckland"); + break; case Nuki::TimeZoneId::Pacific_Guam: - strcpy(str, "Pacific/Guam"); - break; + strcpy(str, "Pacific/Guam"); + break; case Nuki::TimeZoneId::Pacific_Honolulu: - strcpy(str, "Pacific/Honolulu"); - break; + strcpy(str, "Pacific/Honolulu"); + break; case Nuki::TimeZoneId::Pacific_Pago_Pago: - strcpy(str, "Pacific/Pago_Pago"); - break; + strcpy(str, "Pacific/Pago_Pago"); + break; case Nuki::TimeZoneId::None: - strcpy(str, "None"); - break; + strcpy(str, "None"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } uint16_t NukiNetwork::subscribe(const char *topic, uint8_t qos) { - return _device->mqttSubscribe(topic, qos); + if(!_mqttClientInitiated) + { + return -1; + } + return esp_mqtt_client_subscribe(_mqttClient, topic, qos); } void NukiNetwork::addReconnectedCallback(std::function reconnectedCallback) @@ -3822,7 +4112,7 @@ void NukiNetwork::addReconnectedCallback(std::function reconnectedCallba void NukiNetwork::disableMqtt() { - _device->disableMqtt(); + esp_mqtt_client_disconnect(_mqttClient); _mqttEnabled = false; } @@ -3830,9 +4120,4 @@ String NukiNetwork::localIP() { return _device->localIP(); } - -bool NukiNetwork::isConnected() -{ - return _device->isConnected(); -} #endif \ No newline at end of file diff --git a/src/NukiNetwork.h b/src/NukiNetwork.h index 65d2921..6908686 100644 --- a/src/NukiNetwork.h +++ b/src/NukiNetwork.h @@ -7,17 +7,17 @@ #include "networkDevices/IPConfiguration.h" #include "enums/NetworkDeviceType.h" #include "util/NetworkUtil.h" +#include "EspMillis.h" #ifndef NUKI_HUB_UPDATER #include "MqttReceiver.h" +#include "mqtt_client.h" #include "MqttTopics.h" #include "Gpio.h" #include #include "NukiConstants.h" #endif -#define JSON_BUFFER_SIZE 1024 - class NukiNetwork { public: @@ -25,6 +25,9 @@ public: void readSettings(); bool update(); void reconfigureDevice(); + void scan(bool passive = false, bool async = true); + bool isApOpen(); + bool isConnected(); void clearWifiFallback(); const String networkDeviceName() const; @@ -43,7 +46,6 @@ public: void disableAutoRestarts(); // disable on OTA start void disableMqtt(); String localIP(); - bool isConnected(); void subscribe(const char* prefix, const char* path); void initTopic(const char* prefix, const char* path, const char* value); @@ -86,7 +88,6 @@ public: void timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str); int mqttConnectionState(); // 0 = not connected; 1 = connected; 2 = connected and mqtt processed - bool encryptionSupported(); bool mqttRecentlyConnected(); bool pathEquals(const char* prefix, const char* path, const char* referencePath); uint16_t subscribe(const char* topic, uint8_t qos); @@ -117,9 +118,10 @@ private: bool _offEnabled = false; #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); + static void mqtt_event_handler_cb(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data); + void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data); + void onMqttDataReceived(char* topic, int topic_len, char* data, int data_len); + void parseGpioTopics(char* topic, int topic_len, char* data, int data_len); void gpioActionCallback(const GpioAction& action, const int& pin); String createHassTopicPath(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString); @@ -136,10 +138,6 @@ private: const String& commandTopic = "", std::vector> additionalEntries = {} ); - - void onMqttConnect(const bool& sessionPresent); - void onMqttDisconnect(const espMqttClientTypes::DisconnectReason& reason); - void buildMqttPath(char* outPath, std::initializer_list paths); const char* _lastWillPayload = "offline"; @@ -148,13 +146,20 @@ private: String _discoveryTopic; Gpio* _gpio; - + + esp_mqtt_client_config_t _mqtt_cfg = { 0 }; + bool _mqttClientInitiated = false; int _mqttConnectionState = 0; + bool _mqttConnected = false; int _mqttConnectCounter = 0; int _mqttPort = 1883; long _mqttConnectedTs = -1; - bool _connectReplyReceived = false; bool _firstDisconnected = true; + + esp_mqtt_client_handle_t _mqttClient; + char _ca[TLS_CA_MAX_SIZE] = {0}; + char _cert[TLS_CERT_MAX_SIZE] = {0}; + char _key[TLS_KEY_MAX_SIZE] = {0}; int64_t _nextReconnect = 0; char _mqttBrokerAddr[101] = {0}; @@ -166,7 +171,6 @@ private: std::vector _mqttReceivers; bool _restartOnDisconnect = false; bool _checkUpdates = false; - bool _reconnectNetworkOnMqttDisconnect = false; bool _firstConnect = true; bool _publishDebugInfo = false; bool _logIp = true; diff --git a/src/NukiNetworkLock.cpp b/src/NukiNetworkLock.cpp index 0edc0e5..4397650 100644 --- a/src/NukiNetworkLock.cpp +++ b/src/NukiNetworkLock.cpp @@ -15,11 +15,11 @@ extern const uint8_t x509_crt_imported_bundle_bin_start[] asm("_binary_x509_crt_ extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_bundle_end"); NukiNetworkLock::NukiNetworkLock(NukiNetwork* network, NukiOfficial* nukiOfficial, Preferences* preferences, char* buffer, size_t bufferSize) -: _network(network), - _nukiOfficial(nukiOfficial), - _preferences(preferences), - _buffer(buffer), - _bufferSize(bufferSize) + : _network(network), + _nukiOfficial(nukiOfficial), + _preferences(preferences), + _buffer(buffer), + _bufferSize(bufferSize) { _nukiPublisher = new NukiPublisher(network, _mqttPath); _nukiOfficial->setPublisher(_nukiPublisher); @@ -178,24 +178,22 @@ void NukiNetworkLock::update() } } -void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) +void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, int data_len) { - char* value = (char*)payload; - if(_network->mqttRecentlyConnected() && _network->pathEquals(_mqttPath, mqtt_topic_lock_action, topic)) { Log->println("MQTT recently connected, ignoring lock action."); return; } - if(comparePrefixedPath(topic, mqtt_topic_reset) && strcmp(value, "1") == 0) + if(comparePrefixedPath(topic, mqtt_topic_reset) && strcmp(data, "1") == 0) { Log->println(F("Restart requested via MQTT.")); _network->clearWifiFallback(); delay(200); restartEsp(RestartReason::RequestedViaMqtt); } - else if(comparePrefixedPath(topic, mqtt_topic_update) && strcmp(value, "1") == 0 && _preferences->getBool(preference_update_from_mqtt, false)) + else if(comparePrefixedPath(topic, mqtt_topic_update) && strcmp(data, "1") == 0 && _preferences->getBool(preference_update_from_mqtt, false)) { Log->println(F("Update requested via MQTT.")); @@ -203,21 +201,26 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const JsonDocument doc; NetworkClientSecure *client = new NetworkClientSecure; - if (client) { + if (client) + { client->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); { HTTPClient https; https.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); https.useHTTP10(true); - if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) { + if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) + { int httpResponseCode = https.GET(); if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_MOVED_PERMANENTLY) { DeserializationError jsonError = deserializeJson(doc, https.getStream()); - if (!jsonError) { otaManifestSuccess = true; } + if (!jsonError) + { + otaManifestSuccess = true; + } } } https.end(); @@ -297,19 +300,28 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const } else if(comparePrefixedPath(topic, mqtt_topic_webserver_action)) { - if(strcmp(value, "") == 0 || - strcmp(value, "--") == 0) return; - - if(strcmp(value, "1") == 0) + if(strcmp(data, "") == 0 || + strcmp(data, "--") == 0) { - if(_preferences->getBool(preference_webserver_enabled, true) || forceEnableWebServer) return; + return; + } + + if(strcmp(data, "1") == 0) + { + if(_preferences->getBool(preference_webserver_enabled, true) || forceEnableWebServer) + { + return; + } Log->println(F("Webserver enabled, restarting.")); _preferences->putBool(preference_webserver_enabled, true); } - else if (strcmp(value, "0") == 0) + else if (strcmp(data, "0") == 0) { - if(!_preferences->getBool(preference_webserver_enabled, true) && !forceEnableWebServer) return; + if(!_preferences->getBool(preference_webserver_enabled, true) && !forceEnableWebServer) + { + return; + } Log->println(F("Webserver disabled, restarting.")); _preferences->putBool(preference_webserver_enabled, false); } @@ -321,10 +333,16 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const } else if(comparePrefixedPath(topic, mqtt_topic_lock_log_rolling_last)) { - if(strcmp(value, "") == 0 || - strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || + strcmp(data, "--") == 0) + { + return; + } - if(atoi(value) > 0 && atoi(value) > _lastRollingLog) _lastRollingLog = atoi(value); + if(atoi(data) > 0 && atoi(data) > _lastRollingLog) + { + _lastRollingLog = atoi(data); + } } if(_nukiOfficial->getOffEnabled()) @@ -335,7 +353,7 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const { if(_officialUpdateReceivedCallback != nullptr) { - _officialUpdateReceivedCallback(offTopic, value); + _officialUpdateReceivedCallback(offTopic, data); } } } @@ -343,35 +361,38 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const if(comparePrefixedPath(topic, mqtt_topic_lock_action)) { - if(strcmp(value, "") == 0 || - strcmp(value, "--") == 0 || - strcmp(value, "ack") == 0 || - strcmp(value, "unknown_action") == 0 || - strcmp(value, "denied") == 0 || - strcmp(value, "error") == 0) return; + if(strcmp(data, "") == 0 || + strcmp(data, "--") == 0 || + strcmp(data, "ack") == 0 || + strcmp(data, "unknown_action") == 0 || + strcmp(data, "denied") == 0 || + strcmp(data, "error") == 0) + { + return; + } Log->print(F("Lock action received: ")); - Log->println(value); + Log->println(data); LockActionResult lockActionResult = LockActionResult::Failed; if(_lockActionReceivedCallback != NULL) { - lockActionResult = _lockActionReceivedCallback(value); + lockActionResult = _lockActionReceivedCallback(data); } switch(lockActionResult) { - case LockActionResult::Success: - publishString(mqtt_topic_lock_action, "ack", false); - break; - case LockActionResult::UnknownAction: - publishString(mqtt_topic_lock_action, "unknown_action", false); - break; - case LockActionResult::AccessDenied: - publishString(mqtt_topic_lock_action, "denied", false); - break; - case LockActionResult::Failed: - publishString(mqtt_topic_lock_action, "error", false); - break; + case LockActionResult::Success: + publishString(mqtt_topic_lock_action, "ack", false); + break; + case LockActionResult::UnknownAction: + publishString(mqtt_topic_lock_action, "unknown_action", false); + break; + case LockActionResult::AccessDenied: + publishString(mqtt_topic_lock_action, "denied", false); + break; + case LockActionResult::Failed: + publishString(mqtt_topic_lock_action, "error", false); + break; } } @@ -381,16 +402,19 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const { if(_keypadCommandReceivedReceivedCallback != nullptr) { - if(strcmp(value, "--") == 0) return; + if(strcmp(data, "--") == 0) + { + return; + } - _keypadCommandReceivedReceivedCallback(value, _keypadCommandId, _keypadCommandName, _keypadCommandCode, _keypadCommandEnabled); + _keypadCommandReceivedReceivedCallback(data, _keypadCommandId, _keypadCommandName, _keypadCommandCode, _keypadCommandEnabled); _keypadCommandId = 0; _keypadCommandName = "--"; _keypadCommandCode = "000000"; _keypadCommandEnabled = 1; - if(strcmp(value, "--") != 0) + if(strcmp(data, "--") != 0) { publishString(mqtt_topic_keypad_command_action, "--", true); } @@ -402,38 +426,38 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_id)) { - _keypadCommandId = atoi(value); + _keypadCommandId = atoi(data); } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_name)) { - _keypadCommandName = value; + _keypadCommandName = data; } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_code)) { - _keypadCommandCode = value; + _keypadCommandCode = data; } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_enabled)) { - _keypadCommandEnabled = atoi(value); + _keypadCommandEnabled = atoi(data); } } - if(comparePrefixedPath(topic, mqtt_topic_query_config) && strcmp(value, "1") == 0) + if(comparePrefixedPath(topic, mqtt_topic_query_config) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_CONFIG; publishString(mqtt_topic_query_config, "0", true); } - else if(comparePrefixedPath(topic, mqtt_topic_query_lockstate) && strcmp(value, "1") == 0) + else if(comparePrefixedPath(topic, mqtt_topic_query_lockstate) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_LOCKSTATE; publishString(mqtt_topic_query_lockstate, "0", true); } - else if(comparePrefixedPath(topic, mqtt_topic_query_keypad) && strcmp(value, "1") == 0) + else if(comparePrefixedPath(topic, mqtt_topic_query_keypad) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_KEYPAD; publishString(mqtt_topic_query_keypad, "0", true); } - else if(comparePrefixedPath(topic, mqtt_topic_query_battery) && strcmp(value, "1") == 0) + else if(comparePrefixedPath(topic, mqtt_topic_query_battery) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_BATTERY; publishString(mqtt_topic_query_battery, "0", true); @@ -441,11 +465,14 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const if(comparePrefixedPath(topic, mqtt_topic_config_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_configUpdateReceivedCallback != NULL) { - _configUpdateReceivedCallback(value); + _configUpdateReceivedCallback(data); } publishString(mqtt_topic_config_action, "--", true); @@ -453,11 +480,14 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const if(comparePrefixedPath(topic, mqtt_topic_keypad_json_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_keypadJsonCommandReceivedReceivedCallback != NULL) { - _keypadJsonCommandReceivedReceivedCallback(value); + _keypadJsonCommandReceivedReceivedCallback(data); } publishString(mqtt_topic_keypad_json_action, "--", true); @@ -465,11 +495,14 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const if(comparePrefixedPath(topic, mqtt_topic_timecontrol_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_timeControlCommandReceivedReceivedCallback != NULL) { - _timeControlCommandReceivedReceivedCallback(value); + _timeControlCommandReceivedReceivedCallback(data); } publishString(mqtt_topic_timecontrol_action, "--", true); @@ -477,11 +510,14 @@ void NukiNetworkLock::onMqttDataReceived(const char* topic, byte* payload, const if(comparePrefixedPath(topic, mqtt_topic_auth_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_authCommandReceivedReceivedCallback != NULL) { - _authCommandReceivedReceivedCallback(value); + _authCommandReceivedReceivedCallback(data); } publishString(mqtt_topic_auth_action, "--", true); @@ -635,39 +671,39 @@ void NukiNetworkLock::publishState(NukiLock::LockState lockState) { switch(lockState) { - case NukiLock::LockState::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", true); - publishString(mqtt_topic_lock_binary_state, "locked", true); - break; - case NukiLock::LockState::Unlocking: - 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", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiLock::LockState::Unlatched: - 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", 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", true); - break; - default: - break; + case NukiLock::LockState::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", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); + break; + case NukiLock::LockState::Unlocking: + 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", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiLock::LockState::Unlatched: + 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", 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", true); + break; + default: + break; } } @@ -688,7 +724,10 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list authIndex) { @@ -714,7 +753,7 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list().length() == 0 && _authEntries.count(log.authId) > 0) { - entry["authorizationName"] = _authEntries[log.authId]; + entry["authorizationName"] = _authEntries[log.authId]; } entry["timeYear"] = log.timeStampYear; @@ -730,69 +769,75 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list _lastRollingLog) @@ -806,8 +851,14 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list 0) { @@ -1015,7 +1066,10 @@ void NukiNetworkLock::publishKeypad(const std::list& entr jsonEntry["codeId"] = entry.codeId; - if(publishCode) jsonEntry["code"] = entry.code; + if(publishCode) + { + jsonEntry["code"] = entry.code; + } jsonEntry["enabled"] = entry.enabled; jsonEntry["name"] = entry.name; char createdDT[20]; @@ -1036,7 +1090,8 @@ void NukiNetworkLock::publishKeypad(const std::list& entr uint8_t allowedWeekdaysInt = entry.allowedWeekdays; JsonArray weekdays = jsonEntry["allowedWeekdays"].to(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -1113,24 +1168,26 @@ void NukiNetworkLock::publishKeypad(const std::list& entr std::string displayName = std::string("Keypad - ") + std::string((char*)codeName) + " - " + std::to_string(entry.codeId); _network->publishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_keypad_json_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_keypad_json_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1204,7 +1261,10 @@ void NukiNetworkLock::publishKeypad(const std::list& entr void NukiNetworkLock::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } char codeName[sizeof(entry.name) + 1]; memset(codeName, 0, sizeof(codeName)); @@ -1247,7 +1307,8 @@ void NukiNetworkLock::publishTimeControl(const std::list(); - while(weekdaysInt > 0) { + while(weekdaysInt > 0) + { if(weekdaysInt >= 64) { weekdays.add("mon"); @@ -1321,24 +1382,26 @@ void NukiNetworkLock::publishTimeControl(const std::listpublishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_timecontrol_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_timecontrol_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1395,7 +1458,8 @@ void NukiNetworkLock::publishAuth(const std::list& uint8_t allowedWeekdaysInt = entry.allowedWeekdays; JsonArray weekdays = jsonEntry["allowedWeekdays"].to(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -1468,24 +1532,26 @@ void NukiNetworkLock::publishAuth(const std::list& std::string displayName = std::string("Authorization - ") + std::to_string(entry.authId); _network->publishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_auth_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_auth_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1512,7 +1578,10 @@ void NukiNetworkLock::publishConfigCommandResult(const char* result) void NukiNetworkLock::publishKeypadCommandResult(const char* result) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } publishString(mqtt_topic_keypad_command_result, result, true); } @@ -1553,7 +1622,10 @@ void NukiNetworkLock::setConfigUpdateReceivedCallback(void (*configUpdateReceive void NukiNetworkLock::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } _keypadCommandReceivedReceivedCallback = keypadCommandReceivedReceivedCallback; } @@ -1606,7 +1678,7 @@ bool NukiNetworkLock::comparePrefixedPath(const char *fullPath, const char *subP } 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) + char *unlockAction, char *openAction) { _network->publishHASSConfig(deviceType, baseTopic, name, uidString, softwareVersion, hardwareVersion, "~/maintenance/mqttConnectionState", hasKeypad, lockAction, unlockAction, openAction); _network->publishHASSConfigAdditionalLockEntities(deviceType, baseTopic, name, uidString); @@ -1620,9 +1692,9 @@ void NukiNetworkLock::publishHASSConfig(char *deviceType, const char *baseTopic, _network->removeHASSConfigTopic((char*)"binary_sensor", (char*)"door_sensor", uidString); } - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 _network->publishHASSWifiRssiConfig(deviceType, baseTopic, name, uidString); - #endif +#endif if(publishAuthData) { @@ -1721,76 +1793,82 @@ uint8_t NukiNetworkLock::queryCommands() return qc; } -void NukiNetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str) { - switch (btnPressAction) { +void NukiNetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str) +{ + switch (btnPressAction) + { case NukiLock::ButtonPressAction::NoAction: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case NukiLock::ButtonPressAction::Intelligent: - strcpy(str, "Intelligent"); - break; + strcpy(str, "Intelligent"); + break; case NukiLock::ButtonPressAction::Unlock: - strcpy(str, "Unlock"); - break; + strcpy(str, "Unlock"); + break; case NukiLock::ButtonPressAction::Lock: - strcpy(str, "Lock"); - break; + strcpy(str, "Lock"); + break; case NukiLock::ButtonPressAction::Unlatch: - strcpy(str, "Unlatch"); - break; + strcpy(str, "Unlatch"); + break; case NukiLock::ButtonPressAction::LockNgo: - strcpy(str, "Lock n Go"); - break; + strcpy(str, "Lock n Go"); + break; case NukiLock::ButtonPressAction::ShowStatus: - strcpy(str, "Show Status"); - break; + strcpy(str, "Show Status"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkLock::homeKitStatusToString(const int hkstatus, char* str) { - switch (hkstatus) { +void NukiNetworkLock::homeKitStatusToString(const int hkstatus, char* str) +{ + switch (hkstatus) + { case 0: - strcpy(str, "Not Available"); - break; + strcpy(str, "Not Available"); + break; case 1: - strcpy(str, "Disabled"); - break; + strcpy(str, "Disabled"); + break; case 2: - strcpy(str, "Enabled"); - break; + strcpy(str, "Enabled"); + break; case 3: - strcpy(str, "Enabled & Paired"); - break; + strcpy(str, "Enabled & Paired"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkLock::fobActionToString(const int fobact, char* str) { - switch (fobact) { +void NukiNetworkLock::fobActionToString(const int fobact, char* str) +{ + switch (fobact) + { case 0: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case 1: - strcpy(str, "Unlock"); - break; + strcpy(str, "Unlock"); + break; case 2: - strcpy(str, "Lock"); - break; + strcpy(str, "Lock"); + break; case 3: - strcpy(str, "Lock n Go"); - break; + strcpy(str, "Lock n Go"); + break; case 4: - strcpy(str, "Intelligent"); - break; + strcpy(str, "Intelligent"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } const uint32_t NukiNetworkLock::getAuthId() const diff --git a/src/NukiNetworkLock.h b/src/NukiNetworkLock.h index 6ff2e9b..fd045a1 100644 --- a/src/NukiNetworkLock.h +++ b/src/NukiNetworkLock.h @@ -14,8 +14,7 @@ #include "LockActionResult.h" #include "NukiOfficial.h" #include "NukiPublisher.h" - -#define LOCK_LOG_JSON_BUFFER_SIZE 2048 +#include "EspMillis.h" class NukiNetworkLock : public MqttReceiver { @@ -58,7 +57,7 @@ public: void setKeypadJsonCommandReceivedCallback(void (*keypadJsonCommandReceivedReceivedCallback)(const char* value)); void setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char* value)); void setAuthCommandReceivedCallback(void (*authCommandReceivedReceivedCallback)(const char* value)); - void onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) override; + void onMqttDataReceived(char* topic, int topic_len, char* data, int data_len) override; void publishFloat(const char* topic, const float value, bool retain, const uint8_t precision = 2); void publishInt(const char* topic, const int value, bool retain); diff --git a/src/NukiNetworkOpener.cpp b/src/NukiNetworkOpener.cpp index 22fb5e2..71069c1 100644 --- a/src/NukiNetworkOpener.cpp +++ b/src/NukiNetworkOpener.cpp @@ -7,10 +7,10 @@ #include NukiNetworkOpener::NukiNetworkOpener(NukiNetwork* network, Preferences* preferences, char* buffer, size_t bufferSize) - : _preferences(preferences), - _network(network), - _buffer(buffer), - _bufferSize(bufferSize) + : _preferences(preferences), + _network(network), + _buffer(buffer), + _bufferSize(bufferSize) { _nukiPublisher = new NukiPublisher(network, _mqttPath); @@ -124,24 +124,22 @@ void NukiNetworkOpener::initialize() } _network->addReconnectedCallback([&]() - { - _reconnected = true; - }); + { + _reconnected = true; + }); } void NukiNetworkOpener::update() { - if(_resetRingStateTs != 0 && (esp_timer_get_time() / 1000) >= _resetRingStateTs) + if(_resetRingStateTs != 0 && espMillis() >= _resetRingStateTs) { _resetRingStateTs = 0; publishString(mqtt_topic_lock_binary_ring, "standby", true); } } -void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) +void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* data, int data_len) { - char* value = (char*)payload; - if(_network->mqttRecentlyConnected() && _network->pathEquals(_mqttPath, mqtt_topic_lock_action, topic)) { Log->println("MQTT recently connected, ignoring opener action."); @@ -150,43 +148,52 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con if(comparePrefixedPath(topic, mqtt_topic_lock_log_rolling_last)) { - if(strcmp(value, "") == 0 || - strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || + strcmp(data, "--") == 0) + { + return; + } - if(atoi(value) > 0 && atoi(value) > _lastRollingLog) _lastRollingLog = atoi(value); + if(atoi(data) > 0 && atoi(data) > _lastRollingLog) + { + _lastRollingLog = atoi(data); + } } if(comparePrefixedPath(topic, mqtt_topic_lock_action)) { - if(strcmp(value, "") == 0 || - strcmp(value, "--") == 0 || - strcmp(value, "ack") == 0 || - strcmp(value, "unknown_action") == 0 || - strcmp(value, "denied") == 0 || - strcmp(value, "error") == 0) return; + if(strcmp(data, "") == 0 || + strcmp(data, "--") == 0 || + strcmp(data, "ack") == 0 || + strcmp(data, "unknown_action") == 0 || + strcmp(data, "denied") == 0 || + strcmp(data, "error") == 0) + { + return; + } Log->print(F("Opener action received: ")); - Log->println(value); + Log->println(data); LockActionResult lockActionResult = LockActionResult::Failed; if(_lockActionReceivedCallback != NULL) { - lockActionResult = _lockActionReceivedCallback(value); + lockActionResult = _lockActionReceivedCallback(data); } switch(lockActionResult) { - case LockActionResult::Success: - publishString(mqtt_topic_lock_action, "ack", false); - break; - case LockActionResult::UnknownAction: - publishString(mqtt_topic_lock_action, "unknown_action", false); - break; - case LockActionResult::AccessDenied: - publishString(mqtt_topic_lock_action, "denied", false); - break; - case LockActionResult::Failed: - publishString(mqtt_topic_lock_action, "error", false); - break; + case LockActionResult::Success: + publishString(mqtt_topic_lock_action, "ack", false); + break; + case LockActionResult::UnknownAction: + publishString(mqtt_topic_lock_action, "unknown_action", false); + break; + case LockActionResult::AccessDenied: + publishString(mqtt_topic_lock_action, "denied", false); + break; + case LockActionResult::Failed: + publishString(mqtt_topic_lock_action, "error", false); + break; } } @@ -196,16 +203,19 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con { if(_keypadCommandReceivedReceivedCallback != nullptr) { - if(strcmp(value, "--") == 0) return; + if(strcmp(data, "--") == 0) + { + return; + } - _keypadCommandReceivedReceivedCallback(value, _keypadCommandId, _keypadCommandName, _keypadCommandCode, _keypadCommandEnabled); + _keypadCommandReceivedReceivedCallback(data, _keypadCommandId, _keypadCommandName, _keypadCommandCode, _keypadCommandEnabled); _keypadCommandId = 0; _keypadCommandName = "--"; _keypadCommandCode = "000000"; _keypadCommandEnabled = 1; - if(strcmp(value, "--") != 0) + if(strcmp(data, "--") != 0) { publishString(mqtt_topic_keypad_command_action, "--", true); } @@ -217,38 +227,38 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_id)) { - _keypadCommandId = atoi(value); + _keypadCommandId = atoi(data); } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_name)) { - _keypadCommandName = value; + _keypadCommandName = data; } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_code)) { - _keypadCommandCode = value; + _keypadCommandCode = data; } else if(comparePrefixedPath(topic, mqtt_topic_keypad_command_enabled)) { - _keypadCommandEnabled = atoi(value); + _keypadCommandEnabled = atoi(data); } } - if(comparePrefixedPath(topic, mqtt_topic_query_config) && strcmp(value, "1") == 0) + if(comparePrefixedPath(topic, mqtt_topic_query_config) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_CONFIG; publishString(mqtt_topic_query_config, "0", true); } - else if(comparePrefixedPath(topic, mqtt_topic_query_lockstate) && strcmp(value, "1") == 0) + else if(comparePrefixedPath(topic, mqtt_topic_query_lockstate) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_LOCKSTATE; publishString(mqtt_topic_query_lockstate, "0", true); } - else if(comparePrefixedPath(topic, mqtt_topic_query_keypad) && strcmp(value, "1") == 0) + else if(comparePrefixedPath(topic, mqtt_topic_query_keypad) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_KEYPAD; publishString(mqtt_topic_query_keypad, "0", true); } - else if(comparePrefixedPath(topic, mqtt_topic_query_battery) && strcmp(value, "1") == 0) + else if(comparePrefixedPath(topic, mqtt_topic_query_battery) && strcmp(data, "1") == 0) { _queryCommands = _queryCommands | QUERY_COMMAND_BATTERY; publishString(mqtt_topic_query_battery, "0", true); @@ -256,11 +266,14 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con if(comparePrefixedPath(topic, mqtt_topic_config_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_configUpdateReceivedCallback != NULL) { - _configUpdateReceivedCallback(value); + _configUpdateReceivedCallback(data); } publishString(mqtt_topic_config_action, "--", true); @@ -268,11 +281,14 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con if(comparePrefixedPath(topic, mqtt_topic_keypad_json_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_keypadJsonCommandReceivedReceivedCallback != NULL) { - _keypadJsonCommandReceivedReceivedCallback(value); + _keypadJsonCommandReceivedReceivedCallback(data); } publishString(mqtt_topic_keypad_json_action, "--", true); @@ -280,11 +296,14 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con if(comparePrefixedPath(topic, mqtt_topic_timecontrol_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_timeControlCommandReceivedReceivedCallback != NULL) { - _timeControlCommandReceivedReceivedCallback(value); + _timeControlCommandReceivedReceivedCallback(data); } publishString(mqtt_topic_timecontrol_action, "--", true); @@ -292,11 +311,14 @@ void NukiNetworkOpener::onMqttDataReceived(const char* topic, byte* payload, con if(comparePrefixedPath(topic, mqtt_topic_auth_action)) { - if(strcmp(value, "") == 0 || strcmp(value, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_authCommandReceivedReceivedCallback != NULL) { - _authCommandReceivedReceivedCallback(value); + _authCommandReceivedReceivedCallback(data); } publishString(mqtt_topic_auth_action, "--", true); @@ -331,7 +353,9 @@ void NukiNetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& key { publishString(mqtt_topic_lock_continuous_mode, "on", true); json["continuous_mode"] = 1; - } else { + } + else + { publishString(mqtt_topic_lock_continuous_mode, "off", true); json["continuous_mode"] = 0; } @@ -417,7 +441,7 @@ void NukiNetworkOpener::publishRing(const bool locked) } publishString(mqtt_topic_lock_binary_ring, "ring", true); - _resetRingStateTs = (esp_timer_get_time() / 1000) + 2000; + _resetRingStateTs = espMillis() + 2000; } void NukiNetworkOpener::publishState(NukiOpener::OpenerState lockState) @@ -431,28 +455,28 @@ void NukiNetworkOpener::publishState(NukiOpener::OpenerState lockState) { switch (lockState.lockState) { - case NukiOpener::LockState::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", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiOpener::LockState::Open: - 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", 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", true); - break; - default: - break; + case NukiOpener::LockState::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", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiOpener::LockState::Open: + 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", 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", true); + break; + default: + break; } } } @@ -474,7 +498,10 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list authIndex) { @@ -483,7 +510,7 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list 0) { memset(_authName, 0, sizeof(_authName)); @@ -497,12 +524,12 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list().length() == 0 && _authEntries.count(log.authId) > 0) { - entry["authorizationName"] = _authEntries[log.authId]; + entry["authorizationName"] = _authEntries[log.authId]; } - + entry["timeYear"] = log.timeStampYear; entry["timeMonth"] = log.timeStampMonth; entry["timeDay"] = log.timeStampDay; @@ -516,104 +543,111 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list _lastRollingLog) @@ -627,8 +661,14 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list 0) { @@ -860,7 +900,10 @@ void NukiNetworkOpener::publishKeypad(const std::list& en jsonEntry["codeId"] = entry.codeId; - if(publishCode) jsonEntry["code"] = entry.code; + if(publishCode) + { + jsonEntry["code"] = entry.code; + } jsonEntry["enabled"] = entry.enabled; jsonEntry["name"] = entry.name; char createdDT[20]; @@ -881,7 +924,8 @@ void NukiNetworkOpener::publishKeypad(const std::list& en uint8_t allowedWeekdaysInt = entry.allowedWeekdays; JsonArray weekdays = jsonEntry["allowedWeekdays"].to(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -958,24 +1002,26 @@ void NukiNetworkOpener::publishKeypad(const std::list& en std::string displayName = std::string("Keypad - ") + std::string((char*)codeName) + " - " + std::to_string(entry.codeId); _network->publishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_keypad_json_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_keypad_json_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1064,7 +1110,8 @@ void NukiNetworkOpener::publishTimeControl(const std::list(); - while(weekdaysInt > 0) { + while(weekdaysInt > 0) + { if(weekdaysInt >= 64) { weekdays.add("mon"); @@ -1136,24 +1183,26 @@ void NukiNetworkOpener::publishTimeControl(const std::listpublishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"Opener", - "", - "", - "diagnostic", - String("~") + mqtt_topic_timecontrol_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"Opener", + "", + "", + "diagnostic", + String("~") + mqtt_topic_timecontrol_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1210,7 +1259,8 @@ void NukiNetworkOpener::publishAuth(const std::list(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -1283,24 +1333,26 @@ void NukiNetworkOpener::publishAuth(const std::listpublishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"Opener", - "", - "", - "diagnostic", - String("~") + mqtt_topic_auth_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"Opener", + "", + "", + "diagnostic", + String("~") + mqtt_topic_auth_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1327,7 +1379,10 @@ void NukiNetworkOpener::publishConfigCommandResult(const char* result) void NukiNetworkOpener::publishKeypadCommandResult(const char* result) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } publishString(mqtt_topic_keypad_command_result, result, true); } @@ -1363,7 +1418,10 @@ void NukiNetworkOpener::setConfigUpdateReceivedCallback(void (*configUpdateRecei void NukiNetworkOpener::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } _keypadCommandReceivedReceivedCallback = keypadCommandReceivedReceivedCallback; } @@ -1425,7 +1483,10 @@ void NukiNetworkOpener::publishString(const char* topic, const char* value, bool void NukiNetworkOpener::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } char codeName[sizeof(entry.name) + 1]; memset(codeName, 0, sizeof(codeName)); @@ -1507,185 +1568,197 @@ uint8_t NukiNetworkOpener::queryCommands() return qc; } -void NukiNetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str) { - switch (btnPressAction) { +void NukiNetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str) +{ + switch (btnPressAction) + { case NukiOpener::ButtonPressAction::NoAction: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case NukiOpener::ButtonPressAction::ToggleRTO: - strcpy(str, "Toggle RTO"); - break; + strcpy(str, "Toggle RTO"); + break; case NukiOpener::ButtonPressAction::ActivateRTO: - strcpy(str, "Activate RTO"); - break; + strcpy(str, "Activate RTO"); + break; case NukiOpener::ButtonPressAction::DeactivateRTO: - strcpy(str, "Deactivate RTO"); - break; + strcpy(str, "Deactivate RTO"); + break; case NukiOpener::ButtonPressAction::ToggleCM: - strcpy(str, "Toggle CM"); - break; + strcpy(str, "Toggle CM"); + break; case NukiOpener::ButtonPressAction::ActivateCM: - strcpy(str, "Activate CM"); - break; + strcpy(str, "Activate CM"); + break; case NukiOpener::ButtonPressAction::DectivateCM: - strcpy(str, "Deactivate CM"); - break; + strcpy(str, "Deactivate CM"); + break; case NukiOpener::ButtonPressAction::Open: - strcpy(str, "Open"); - break; + strcpy(str, "Open"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::fobActionToString(const int fobact, char* str) { - switch (fobact) { +void NukiNetworkOpener::fobActionToString(const int fobact, char* str) +{ + switch (fobact) + { case 0: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case 1: - strcpy(str, "Toggle RTO"); - break; + strcpy(str, "Toggle RTO"); + break; case 2: - strcpy(str, "Activate RTO"); - break; + strcpy(str, "Activate RTO"); + break; case 3: - strcpy(str, "Deactivate RTO"); - break; + strcpy(str, "Deactivate RTO"); + break; case 7: - strcpy(str, "Open"); - break; + strcpy(str, "Open"); + break; case 8: - strcpy(str, "Ring"); - break; + strcpy(str, "Ring"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::capabilitiesToString(const int capabilities, char* str) { - switch (capabilities) { +void NukiNetworkOpener::capabilitiesToString(const int capabilities, char* str) +{ + switch (capabilities) + { case 0: - strcpy(str, "Door opener"); - break; + strcpy(str, "Door opener"); + break; case 1: - strcpy(str, "Both"); - break; + strcpy(str, "Both"); + break; case 2: - strcpy(str, "RTO"); - break; + strcpy(str, "RTO"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::operatingModeToString(const int opmode, char* str) { - switch (opmode) { +void NukiNetworkOpener::operatingModeToString(const int opmode, char* str) +{ + switch (opmode) + { case 0: - strcpy(str, "Generic door opener"); - break; + strcpy(str, "Generic door opener"); + break; case 1: - strcpy(str, "Analogue intercom"); - break; + strcpy(str, "Analogue intercom"); + break; case 2: - strcpy(str, "Digital intercom"); - break; + strcpy(str, "Digital intercom"); + break; case 3: - strcpy(str, "Siedle"); - break; + strcpy(str, "Siedle"); + break; case 4: - strcpy(str, "TCS"); - break; + strcpy(str, "TCS"); + break; case 5: - strcpy(str, "Bticino"); - break; + strcpy(str, "Bticino"); + break; case 6: - strcpy(str, "Siedle HTS"); - break; + strcpy(str, "Siedle HTS"); + break; case 7: - strcpy(str, "STR"); - break; + strcpy(str, "STR"); + break; case 8: - strcpy(str, "Ritto"); - break; + strcpy(str, "Ritto"); + break; case 9: - strcpy(str, "Fermax"); - break; + strcpy(str, "Fermax"); + break; case 10: - strcpy(str, "Comelit"); - break; + strcpy(str, "Comelit"); + break; case 11: - strcpy(str, "Urmet BiBus"); - break; + strcpy(str, "Urmet BiBus"); + break; case 12: - strcpy(str, "Urmet 2Voice"); - break; + strcpy(str, "Urmet 2Voice"); + break; case 13: - strcpy(str, "Golmar"); - break; + strcpy(str, "Golmar"); + break; case 14: - strcpy(str, "SKS"); - break; + strcpy(str, "SKS"); + break; case 15: - strcpy(str, "Spare"); - break; + strcpy(str, "Spare"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) { - switch (dbsupr) { +void NukiNetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) +{ + switch (dbsupr) + { case 0: - strcpy(str, "Off"); - break; + strcpy(str, "Off"); + break; case 1: - strcpy(str, "CM"); - break; + strcpy(str, "CM"); + break; case 2: - strcpy(str, "RTO"); - break; + strcpy(str, "RTO"); + break; case 3: - strcpy(str, "CM & RTO"); - break; + strcpy(str, "CM & RTO"); + break; case 4: - strcpy(str, "Ring"); - break; + strcpy(str, "Ring"); + break; case 5: - strcpy(str, "CM & Ring"); - break; + strcpy(str, "CM & Ring"); + break; case 6: - strcpy(str, "RTO & Ring"); - break; + strcpy(str, "RTO & Ring"); + break; case 7: - strcpy(str, "CM & RTO & Ring"); - break; + strcpy(str, "CM & RTO & Ring"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::soundToString(const int sound, char* str) { - switch (sound) { +void NukiNetworkOpener::soundToString(const int sound, char* str) +{ + switch (sound) + { case 0: - strcpy(str, "No Sound"); - break; + strcpy(str, "No Sound"); + break; case 1: - strcpy(str, "Sound 1"); - break; + strcpy(str, "Sound 1"); + break; case 2: - strcpy(str, "Sound 2"); - break; + strcpy(str, "Sound 2"); + break; case 3: - strcpy(str, "Sound 3"); - break; + strcpy(str, "Sound 3"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } diff --git a/src/NukiNetworkOpener.h b/src/NukiNetworkOpener.h index 9993e05..08aafd3 100644 --- a/src/NukiNetworkOpener.h +++ b/src/NukiNetworkOpener.h @@ -6,6 +6,7 @@ #include "NukiConstants.h" #include "NukiOpenerConstants.h" #include "NukiNetworkLock.h" +#include "EspMillis.h" class NukiNetworkOpener : public MqttReceiver { @@ -47,7 +48,7 @@ public: void setKeypadJsonCommandReceivedCallback(void (*keypadJsonCommandReceivedReceivedCallback)(const char* value)); void setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char* value)); void setAuthCommandReceivedCallback(void (*authCommandReceivedReceivedCallback)(const char* value)); - void onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) override; + void onMqttDataReceived(char* topic, int topic_len, char* data, int data_len) override; bool reconnected(); uint8_t queryCommands(); diff --git a/src/NukiOfficial.cpp b/src/NukiOfficial.cpp index 9eaef7d..af10b63 100644 --- a/src/NukiOfficial.cpp +++ b/src/NukiOfficial.cpp @@ -136,7 +136,10 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value Log->print(F("Battery critical: ")); Log->println(offCritical); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_critical, offCritical, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_critical, offCritical, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_batteryCharging) == 0) @@ -146,7 +149,10 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value Log->print(F("Battery charging: ")); Log->println(offCharging); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_charging, offCharging, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_charging, offCharging, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_batteryChargeState) == 0) @@ -156,19 +162,28 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value Log->print(F("Battery level: ")); Log->println(offChargeState); - if(!_disableNonJSON) _publisher->publishInt(mqtt_topic_battery_level, offChargeState, true); + if(!_disableNonJSON) + { + _publisher->publishInt(mqtt_topic_battery_level, offChargeState, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_keypadBatteryCritical) == 0) { offKeypadCritical = (strcmp(value, "true") == 0 ? 1 : 0); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_keypad_critical, offKeypadCritical, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_keypad_critical, offKeypadCritical, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_doorsensorBatteryCritical) == 0) { offDoorsensorCritical = (strcmp(value, "true") == 0 ? 1 : 0); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_doorsensor_critical, offDoorsensorCritical, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_doorsensor_critical, offDoorsensorCritical, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_commandResponse) == 0) diff --git a/src/NukiOpenerWrapper.cpp b/src/NukiOpenerWrapper.cpp index 14c5a34..c24997f 100644 --- a/src/NukiOpenerWrapper.cpp +++ b/src/NukiOpenerWrapper.cpp @@ -10,13 +10,13 @@ NukiOpenerWrapper* nukiOpenerInst; Preferences* nukiOpenerPreferences = nullptr; 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()), - _bleScanner(scanner), - _network(network), - _gpio(gpio), - _preferences(preferences) + : _deviceName(deviceName), + _deviceId(deviceId), + _nukiOpener(deviceName, _deviceId->get()), + _bleScanner(scanner), + _network(network), + _gpio(gpio), + _preferences(preferences) { Log->print("Device id opener: "); Log->println(_deviceId->get()); @@ -64,14 +64,38 @@ void NukiOpenerWrapper::readSettings() int pwrLvl = _preferences->getInt(preference_ble_tx_power, 9); - if(pwrLvl >= 9) powerLevel = ESP_PWR_LVL_P9; - else if(pwrLvl >= 6) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 3) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 0) powerLevel = ESP_PWR_LVL_P3; - else if(pwrLvl >= -3) powerLevel = ESP_PWR_LVL_N3; - else if(pwrLvl >= -6) powerLevel = ESP_PWR_LVL_N6; - else if(pwrLvl >= -9) powerLevel = ESP_PWR_LVL_N9; - else if(pwrLvl >= -12) powerLevel = ESP_PWR_LVL_N12; + if(pwrLvl >= 9) + { + powerLevel = ESP_PWR_LVL_P9; + } + else if(pwrLvl >= 6) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 3) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 0) + { + powerLevel = ESP_PWR_LVL_P3; + } + else if(pwrLvl >= -3) + { + powerLevel = ESP_PWR_LVL_N3; + } + else if(pwrLvl >= -6) + { + powerLevel = ESP_PWR_LVL_N6; + } + else if(pwrLvl >= -9) + { + powerLevel = ESP_PWR_LVL_N9; + } + else if(pwrLvl >= -12) + { + powerLevel = ESP_PWR_LVL_N12; + } _nukiOpener.setPower(powerLevel); @@ -174,14 +198,14 @@ void NukiOpenerWrapper::update() } int64_t lastReceivedBeaconTs = _nukiOpener.getLastReceivedBeaconTs(); - int64_t ts = (esp_timer_get_time() / 1000); + int64_t ts = espMillis(); uint8_t queryCommands = _network->queryCommands(); if(_restartBeaconTimeout > 0 && - ts > 60000 && - lastReceivedBeaconTs > 0 && - _disableBleWatchdogTs < ts && - (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) + ts > 60000 && + lastReceivedBeaconTs > 0 && + _disableBleWatchdogTs < ts && + (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) { Log->print("No BLE beacon received from the opener for "); Log->print((ts - lastReceivedBeaconTs) / 1000); @@ -299,7 +323,10 @@ void NukiOpenerWrapper::update() _nextLockAction = (NukiOpener::LockAction) 0xff; _network->publishRetry("--"); retryCount = 0; - if(_intervalLockstate > 10) _nextLockStateUpdateTs = ts + 10 * 1000; + if(_intervalLockstate > 10) + { + _nextLockStateUpdateTs = ts + 10 * 1000; + } } else { @@ -337,8 +364,14 @@ void NukiOpenerWrapper::activateCM() void NukiOpenerWrapper::deactivateRtoCm() { - if(_keyTurnerState.nukiState == NukiOpener::State::ContinuousMode) _nextLockAction = NukiOpener::LockAction::DeactivateCM; - else if(_keyTurnerState.lockState == NukiOpener::LockState::RTOactive) _nextLockAction = NukiOpener::LockAction::DeactivateRTO; + if(_keyTurnerState.nukiState == NukiOpener::State::ContinuousMode) + { + _nextLockAction = NukiOpener::LockAction::DeactivateCM; + } + else if(_keyTurnerState.lockState == NukiOpener::LockState::RTOactive) + { + _nextLockAction = NukiOpener::LockAction::DeactivateRTO; + } } void NukiOpenerWrapper::deactivateRTO() @@ -408,16 +441,16 @@ void NukiOpenerWrapper::updateKeyTurnerState() postponeBleWatchdog(); if(_retryLockstateCount < _nrOfRetries + 1) { - _nextLockStateUpdateTs = (esp_timer_get_time() / 1000) + _retryDelay; + _nextLockStateUpdateTs = espMillis() + _retryDelay; } return; } _retryLockstateCount = 0; if(_statusUpdated && - _keyTurnerState.lockState == NukiOpener::LockState::Locked && - _lastKeyTurnerState.lockState == NukiOpener::LockState::Locked && - _lastKeyTurnerState.nukiState == _keyTurnerState.nukiState) + _keyTurnerState.lockState == NukiOpener::LockState::Locked && + _lastKeyTurnerState.lockState == NukiOpener::LockState::Locked && + _lastKeyTurnerState.nukiState == _keyTurnerState.nukiState) { Log->println(F("Nuki opener: Ring detected (Locked)")); _network->publishRing(true); @@ -425,8 +458,8 @@ void NukiOpenerWrapper::updateKeyTurnerState() else { if(_keyTurnerState.lockState != _lastKeyTurnerState.lockState && - _keyTurnerState.lockState == NukiOpener::LockState::Open && - _keyTurnerState.trigger == NukiOpener::Trigger::Manual) + _keyTurnerState.lockState == NukiOpener::LockState::Open && + _keyTurnerState.trigger == NukiOpener::Trigger::Manual) { Log->println(F("Nuki opener: Ring detected (Open)")); _network->publishRing(false); @@ -466,10 +499,14 @@ void NukiOpenerWrapper::updateBatteryState() Log->print(F("Querying opener battery state: ")); result = _nukiOpener.requestBatteryReport(&_batteryReport); delay(250); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -506,14 +543,24 @@ void NukiOpenerWrapper::updateConfig() _hasKeypad = _nukiConfig.hasKeypad > 0 || _nukiConfig.hasKeypadV2 > 0; _firmwareVersion = std::to_string(_nukiConfig.firmwareVersion[0]) + "." + std::to_string(_nukiConfig.firmwareVersion[1]) + "." + std::to_string(_nukiConfig.firmwareVersion[2]); _hardwareVersion = std::to_string(_nukiConfig.hardwareRevision[0]) + "." + std::to_string(_nukiConfig.hardwareRevision[1]); - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishConfig(_nukiConfig); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishConfig(_nukiConfig); + } _retryConfigCount = 0; - if(_preferences->getBool(preference_timecontrol_info_enabled, false)) updateTimeControl(false); - if(_preferences->getBool(preference_auth_info_enabled)) updateAuth(false); + if(_preferences->getBool(preference_timecontrol_info_enabled, false)) + { + updateTimeControl(false); + } + if(_preferences->getBool(preference_auth_info_enabled)) + { + updateAuth(false); + } const int pinStatus = _preferences->getInt(preference_opener_pin_status, 4); - if(isPinSet()) { + if(isPinSet()) + { Nuki::CmdResult result = (Nuki::CmdResult)-1; int retryCount = 0; Log->println(F("Nuki opener PIN is set")); @@ -522,23 +569,29 @@ void NukiOpenerWrapper::updateConfig() { result = _nukiOpener.verifySecurityPin(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if(result != Nuki::CmdResult::Success) { Log->println(F("Nuki opener PIN is invalid")); - if(pinStatus != 2) { + if(pinStatus != 2) + { _preferences->putInt(preference_opener_pin_status, 2); } } else { Log->println(F("Nuki opener PIN is valid")); - if(pinStatus != 1) { + if(pinStatus != 1) + { _preferences->putInt(preference_opener_pin_status, 1); } } @@ -546,7 +599,8 @@ void NukiOpenerWrapper::updateConfig() else { Log->println(F("Nuki opener PIN is not set")); - if(pinStatus != 0) { + if(pinStatus != 0) + { _preferences->putInt(preference_opener_pin_status, 0); } } @@ -569,7 +623,10 @@ void NukiOpenerWrapper::updateConfig() if(_nukiAdvancedConfigValid) { - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishAdvancedConfig(_nukiAdvancedConfig); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishAdvancedConfig(_nukiAdvancedConfig); + } } else { @@ -587,7 +644,7 @@ void NukiOpenerWrapper::updateConfig() { ++_retryConfigCount; Log->println(F("Invalid/Unexpected opener config and/or advanced config recieved, retrying in 10 seconds")); - int64_t ts = (esp_timer_get_time() / 1000); + int64_t ts = espMillis(); _nextConfigUpdateTs = ts + 10000; } } @@ -610,17 +667,21 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) Log->print(F("Retrieve log entries: ")); result = _nukiOpener.retrieveLogEntries(0, _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 1, false); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } Log->println(result); printCommandResult(result); if(result == Nuki::CmdResult::Success) { - _waitAuthLogUpdateTs = (esp_timer_get_time() / 1000) + 5000; + _waitAuthLogUpdateTs = espMillis() + 5000; delay(100); std::list log; @@ -631,11 +692,14 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, 3)); } - log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) + { + return a.index < b.index; + }); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, true); + _network->publishAuthorizationInfo(log, true); } } } @@ -649,14 +713,17 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG)); } - log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) + { + return a.index < b.index; + }); Log->print(F("Log size: ")); Log->println(log.size()); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, false); + _network->publishAuthorizationInfo(log, false); } } @@ -665,7 +732,10 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) void NukiOpenerWrapper::updateKeypad(bool retrieved) { - if(!_preferences->getBool(preference_keypad_info_enabled)) return; + if(!_preferences->getBool(preference_keypad_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -683,16 +753,20 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) Log->print(F("Querying opener keypad: ")); result = _nukiOpener.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); if(result == Nuki::CmdResult::Success) { - _waitKeypadUpdateTs = (esp_timer_get_time() / 1000) + 5000; + _waitKeypadUpdateTs = espMillis() + 5000; } } else @@ -703,7 +777,10 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) Log->print(F("Opener keypad codes: ")); Log->println(entries.size()); - entries.sort([](const NukiOpener::KeypadEntry& a, const NukiOpener::KeypadEntry& b) { return a.codeId < b.codeId; }); + entries.sort([](const NukiOpener::KeypadEntry& a, const NukiOpener::KeypadEntry& b) + { + return a.codeId < b.codeId; + }); if(entries.size() > _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)) { @@ -735,7 +812,10 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) void NukiOpenerWrapper::updateTimeControl(bool retrieved) { - if(!_preferences->getBool(preference_timecontrol_info_enabled)) return; + if(!_preferences->getBool(preference_timecontrol_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -753,16 +833,20 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) Log->print(F("Querying opener timecontrol: ")); result = _nukiOpener.retrieveTimeControlEntries(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); if(result == Nuki::CmdResult::Success) { - _waitTimeControlUpdateTs = (esp_timer_get_time() / 1000) + 5000; + _waitTimeControlUpdateTs = espMillis() + 5000; } } else @@ -773,7 +857,10 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) Log->print(F("Opener timecontrol entries: ")); Log->println(timeControlEntries.size()); - timeControlEntries.sort([](const NukiOpener::TimeControlEntry& a, const NukiOpener::TimeControlEntry& b) { return a.entryId < b.entryId; }); + timeControlEntries.sort([](const NukiOpener::TimeControlEntry& a, const NukiOpener::TimeControlEntry& b) + { + return a.entryId < b.entryId; + }); if(timeControlEntries.size() > _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL)) { @@ -802,7 +889,10 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) void NukiOpenerWrapper::updateAuth(bool retrieved) { - if(!_preferences->getBool(preference_auth_info_enabled)) return; + if(!_preferences->getBool(preference_auth_info_enabled)) + { + return; + } if(!retrieved) { @@ -814,10 +904,14 @@ void NukiOpenerWrapper::updateAuth(bool retrieved) Log->print(F("Querying opener authorization: ")); result = _nukiOpener.retrieveAuthorizationEntries(0, _preferences->getInt(preference_auth_max_entries, MAX_AUTH)); delay(250); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -834,7 +928,10 @@ void NukiOpenerWrapper::updateAuth(bool retrieved) Log->print(F("Opener authorization entries: ")); Log->println(authEntries.size()); - authEntries.sort([](const NukiOpener::AuthorizationEntry& a, const NukiOpener::AuthorizationEntry& b) { return a.authId < b.authId; }); + authEntries.sort([](const NukiOpener::AuthorizationEntry& a, const NukiOpener::AuthorizationEntry& b) + { + return a.authId < b.authId; + }); if(authEntries.size() > _preferences->getInt(preference_auth_max_entries, MAX_AUTH)) { @@ -863,19 +960,43 @@ void NukiOpenerWrapper::updateAuth(bool retrieved) void NukiOpenerWrapper::postponeBleWatchdog() { - _disableBleWatchdogTs = (esp_timer_get_time() / 1000) + 15000; + _disableBleWatchdogTs = espMillis() + 15000; } NukiOpener::LockAction NukiOpenerWrapper::lockActionToEnum(const char *str) { - if(strcmp(str, "activateRTO") == 0 || strcmp(str, "ActivateRTO") == 0) return NukiOpener::LockAction::ActivateRTO; - else if(strcmp(str, "deactivateRTO") == 0 || strcmp(str, "DeactivateRTO") == 0) return NukiOpener::LockAction::DeactivateRTO; - else if(strcmp(str, "electricStrikeActuation") == 0 || strcmp(str, "ElectricStrikeActuation") == 0) return NukiOpener::LockAction::ElectricStrikeActuation; - else if(strcmp(str, "activateCM") == 0 || strcmp(str, "ActivateCM") == 0) return NukiOpener::LockAction::ActivateCM; - else if(strcmp(str, "deactivateCM") == 0 || strcmp(str, "DeactivateCM") == 0) return NukiOpener::LockAction::DeactivateCM; - else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) return NukiOpener::LockAction::FobAction2; - else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) return NukiOpener::LockAction::FobAction1; - else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) return NukiOpener::LockAction::FobAction3; + if(strcmp(str, "activateRTO") == 0 || strcmp(str, "ActivateRTO") == 0) + { + return NukiOpener::LockAction::ActivateRTO; + } + else if(strcmp(str, "deactivateRTO") == 0 || strcmp(str, "DeactivateRTO") == 0) + { + return NukiOpener::LockAction::DeactivateRTO; + } + else if(strcmp(str, "electricStrikeActuation") == 0 || strcmp(str, "ElectricStrikeActuation") == 0) + { + return NukiOpener::LockAction::ElectricStrikeActuation; + } + else if(strcmp(str, "activateCM") == 0 || strcmp(str, "ActivateCM") == 0) + { + return NukiOpener::LockAction::ActivateCM; + } + else if(strcmp(str, "deactivateCM") == 0 || strcmp(str, "DeactivateCM") == 0) + { + return NukiOpener::LockAction::DeactivateCM; + } + else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) + { + return NukiOpener::LockAction::FobAction2; + } + else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) + { + return NukiOpener::LockAction::FobAction1; + } + else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) + { + return NukiOpener::LockAction::FobAction3; + } return (NukiOpener::LockAction)0xff; } @@ -888,11 +1009,20 @@ LockActionResult NukiOpenerWrapper::onLockActionReceivedCallback(const char *val if(strlen(value) > 0) { action = nukiOpenerInst->lockActionToEnum(value); - if((int)action == 0xff) return LockActionResult::UnknownAction; + if((int)action == 0xff) + { + return LockActionResult::UnknownAction; + } + } + else + { + return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; + else + { + return LockActionResult::UnknownAction; + } nukiOpenerPreferences = new Preferences(); nukiOpenerPreferences->begin("nukihub", true); @@ -917,137 +1047,425 @@ void NukiOpenerWrapper::onConfigUpdateReceivedCallback(const char *value) Nuki::AdvertisingMode NukiOpenerWrapper::advertisingModeToEnum(const char *str) { - if(strcmp(str, "Automatic") == 0) return Nuki::AdvertisingMode::Automatic; - else if(strcmp(str, "Normal") == 0) return Nuki::AdvertisingMode::Normal; - else if(strcmp(str, "Slow") == 0) return Nuki::AdvertisingMode::Slow; - else if(strcmp(str, "Slowest") == 0) return Nuki::AdvertisingMode::Slowest; + if(strcmp(str, "Automatic") == 0) + { + return Nuki::AdvertisingMode::Automatic; + } + else if(strcmp(str, "Normal") == 0) + { + return Nuki::AdvertisingMode::Normal; + } + else if(strcmp(str, "Slow") == 0) + { + return Nuki::AdvertisingMode::Slow; + } + else if(strcmp(str, "Slowest") == 0) + { + return Nuki::AdvertisingMode::Slowest; + } return (Nuki::AdvertisingMode)0xff; } Nuki::TimeZoneId NukiOpenerWrapper::timeZoneToEnum(const char *str) { - if(strcmp(str, "Africa/Cairo") == 0) return Nuki::TimeZoneId::Africa_Cairo; - else if(strcmp(str, "Africa/Lagos") == 0) return Nuki::TimeZoneId::Africa_Lagos; - else if(strcmp(str, "Africa/Maputo") == 0) return Nuki::TimeZoneId::Africa_Maputo; - else if(strcmp(str, "Africa/Nairobi") == 0) return Nuki::TimeZoneId::Africa_Nairobi; - else if(strcmp(str, "America/Anchorage") == 0) return Nuki::TimeZoneId::America_Anchorage; - else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; - else if(strcmp(str, "America/Chicago") == 0) return Nuki::TimeZoneId::America_Chicago; - else if(strcmp(str, "America/Denver") == 0) return Nuki::TimeZoneId::America_Denver; - else if(strcmp(str, "America/Halifax") == 0) return Nuki::TimeZoneId::America_Halifax; - else if(strcmp(str, "America/Los_Angeles") == 0) return Nuki::TimeZoneId::America_Los_Angeles; - else if(strcmp(str, "America/Manaus") == 0) return Nuki::TimeZoneId::America_Manaus; - else if(strcmp(str, "America/Mexico_City") == 0) return Nuki::TimeZoneId::America_Mexico_City; - else if(strcmp(str, "America/New_York") == 0) return Nuki::TimeZoneId::America_New_York; - else if(strcmp(str, "America/Phoenix") == 0) return Nuki::TimeZoneId::America_Phoenix; - else if(strcmp(str, "America/Regina") == 0) return Nuki::TimeZoneId::America_Regina; - else if(strcmp(str, "America/Santiago") == 0) return Nuki::TimeZoneId::America_Santiago; - else if(strcmp(str, "America/Sao_Paulo") == 0) return Nuki::TimeZoneId::America_Sao_Paulo; - else if(strcmp(str, "America/St_Johns") == 0) return Nuki::TimeZoneId::America_St_Johns; - else if(strcmp(str, "Asia/Bangkok") == 0) return Nuki::TimeZoneId::Asia_Bangkok; - else if(strcmp(str, "Asia/Dubai") == 0) return Nuki::TimeZoneId::Asia_Dubai; - else if(strcmp(str, "Asia/Hong_Kong") == 0) return Nuki::TimeZoneId::Asia_Hong_Kong; - else if(strcmp(str, "Asia/Jerusalem") == 0) return Nuki::TimeZoneId::Asia_Jerusalem; - else if(strcmp(str, "Asia/Karachi") == 0) return Nuki::TimeZoneId::Asia_Karachi; - else if(strcmp(str, "Asia/Kathmandu") == 0) return Nuki::TimeZoneId::Asia_Kathmandu; - else if(strcmp(str, "Asia/Kolkata") == 0) return Nuki::TimeZoneId::Asia_Kolkata; - else if(strcmp(str, "Asia/Riyadh") == 0) return Nuki::TimeZoneId::Asia_Riyadh; - else if(strcmp(str, "Asia/Seoul") == 0) return Nuki::TimeZoneId::Asia_Seoul; - else if(strcmp(str, "Asia/Shanghai") == 0) return Nuki::TimeZoneId::Asia_Shanghai; - else if(strcmp(str, "Asia/Tehran") == 0) return Nuki::TimeZoneId::Asia_Tehran; - else if(strcmp(str, "Asia/Tokyo") == 0) return Nuki::TimeZoneId::Asia_Tokyo; - else if(strcmp(str, "Asia/Yangon") == 0) return Nuki::TimeZoneId::Asia_Yangon; - else if(strcmp(str, "Australia/Adelaide") == 0) return Nuki::TimeZoneId::Australia_Adelaide; - else if(strcmp(str, "Australia/Brisbane") == 0) return Nuki::TimeZoneId::Australia_Brisbane; - else if(strcmp(str, "Australia/Darwin") == 0) return Nuki::TimeZoneId::Australia_Darwin; - else if(strcmp(str, "Australia/Hobart") == 0) return Nuki::TimeZoneId::Australia_Hobart; - else if(strcmp(str, "Australia/Perth") == 0) return Nuki::TimeZoneId::Australia_Perth; - else if(strcmp(str, "Australia/Sydney") == 0) return Nuki::TimeZoneId::Australia_Sydney; - else if(strcmp(str, "Europe/Berlin") == 0) return Nuki::TimeZoneId::Europe_Berlin; - else if(strcmp(str, "Europe/Helsinki") == 0) return Nuki::TimeZoneId::Europe_Helsinki; - else if(strcmp(str, "Europe/Istanbul") == 0) return Nuki::TimeZoneId::Europe_Istanbul; - else if(strcmp(str, "Europe/London") == 0) return Nuki::TimeZoneId::Europe_London; - else if(strcmp(str, "Europe/Moscow") == 0) return Nuki::TimeZoneId::Europe_Moscow; - else if(strcmp(str, "Pacific/Auckland") == 0) return Nuki::TimeZoneId::Pacific_Auckland; - else if(strcmp(str, "Pacific/Guam") == 0) return Nuki::TimeZoneId::Pacific_Guam; - else if(strcmp(str, "Pacific/Honolulu") == 0) return Nuki::TimeZoneId::Pacific_Honolulu; - else if(strcmp(str, "Pacific/Pago_Pago") == 0) return Nuki::TimeZoneId::Pacific_Pago_Pago; - else if(strcmp(str, "None") == 0) return Nuki::TimeZoneId::None; + if(strcmp(str, "Africa/Cairo") == 0) + { + return Nuki::TimeZoneId::Africa_Cairo; + } + else if(strcmp(str, "Africa/Lagos") == 0) + { + return Nuki::TimeZoneId::Africa_Lagos; + } + else if(strcmp(str, "Africa/Maputo") == 0) + { + return Nuki::TimeZoneId::Africa_Maputo; + } + else if(strcmp(str, "Africa/Nairobi") == 0) + { + return Nuki::TimeZoneId::Africa_Nairobi; + } + else if(strcmp(str, "America/Anchorage") == 0) + { + return Nuki::TimeZoneId::America_Anchorage; + } + else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) + { + return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; + } + else if(strcmp(str, "America/Chicago") == 0) + { + return Nuki::TimeZoneId::America_Chicago; + } + else if(strcmp(str, "America/Denver") == 0) + { + return Nuki::TimeZoneId::America_Denver; + } + else if(strcmp(str, "America/Halifax") == 0) + { + return Nuki::TimeZoneId::America_Halifax; + } + else if(strcmp(str, "America/Los_Angeles") == 0) + { + return Nuki::TimeZoneId::America_Los_Angeles; + } + else if(strcmp(str, "America/Manaus") == 0) + { + return Nuki::TimeZoneId::America_Manaus; + } + else if(strcmp(str, "America/Mexico_City") == 0) + { + return Nuki::TimeZoneId::America_Mexico_City; + } + else if(strcmp(str, "America/New_York") == 0) + { + return Nuki::TimeZoneId::America_New_York; + } + else if(strcmp(str, "America/Phoenix") == 0) + { + return Nuki::TimeZoneId::America_Phoenix; + } + else if(strcmp(str, "America/Regina") == 0) + { + return Nuki::TimeZoneId::America_Regina; + } + else if(strcmp(str, "America/Santiago") == 0) + { + return Nuki::TimeZoneId::America_Santiago; + } + else if(strcmp(str, "America/Sao_Paulo") == 0) + { + return Nuki::TimeZoneId::America_Sao_Paulo; + } + else if(strcmp(str, "America/St_Johns") == 0) + { + return Nuki::TimeZoneId::America_St_Johns; + } + else if(strcmp(str, "Asia/Bangkok") == 0) + { + return Nuki::TimeZoneId::Asia_Bangkok; + } + else if(strcmp(str, "Asia/Dubai") == 0) + { + return Nuki::TimeZoneId::Asia_Dubai; + } + else if(strcmp(str, "Asia/Hong_Kong") == 0) + { + return Nuki::TimeZoneId::Asia_Hong_Kong; + } + else if(strcmp(str, "Asia/Jerusalem") == 0) + { + return Nuki::TimeZoneId::Asia_Jerusalem; + } + else if(strcmp(str, "Asia/Karachi") == 0) + { + return Nuki::TimeZoneId::Asia_Karachi; + } + else if(strcmp(str, "Asia/Kathmandu") == 0) + { + return Nuki::TimeZoneId::Asia_Kathmandu; + } + else if(strcmp(str, "Asia/Kolkata") == 0) + { + return Nuki::TimeZoneId::Asia_Kolkata; + } + else if(strcmp(str, "Asia/Riyadh") == 0) + { + return Nuki::TimeZoneId::Asia_Riyadh; + } + else if(strcmp(str, "Asia/Seoul") == 0) + { + return Nuki::TimeZoneId::Asia_Seoul; + } + else if(strcmp(str, "Asia/Shanghai") == 0) + { + return Nuki::TimeZoneId::Asia_Shanghai; + } + else if(strcmp(str, "Asia/Tehran") == 0) + { + return Nuki::TimeZoneId::Asia_Tehran; + } + else if(strcmp(str, "Asia/Tokyo") == 0) + { + return Nuki::TimeZoneId::Asia_Tokyo; + } + else if(strcmp(str, "Asia/Yangon") == 0) + { + return Nuki::TimeZoneId::Asia_Yangon; + } + else if(strcmp(str, "Australia/Adelaide") == 0) + { + return Nuki::TimeZoneId::Australia_Adelaide; + } + else if(strcmp(str, "Australia/Brisbane") == 0) + { + return Nuki::TimeZoneId::Australia_Brisbane; + } + else if(strcmp(str, "Australia/Darwin") == 0) + { + return Nuki::TimeZoneId::Australia_Darwin; + } + else if(strcmp(str, "Australia/Hobart") == 0) + { + return Nuki::TimeZoneId::Australia_Hobart; + } + else if(strcmp(str, "Australia/Perth") == 0) + { + return Nuki::TimeZoneId::Australia_Perth; + } + else if(strcmp(str, "Australia/Sydney") == 0) + { + return Nuki::TimeZoneId::Australia_Sydney; + } + else if(strcmp(str, "Europe/Berlin") == 0) + { + return Nuki::TimeZoneId::Europe_Berlin; + } + else if(strcmp(str, "Europe/Helsinki") == 0) + { + return Nuki::TimeZoneId::Europe_Helsinki; + } + else if(strcmp(str, "Europe/Istanbul") == 0) + { + return Nuki::TimeZoneId::Europe_Istanbul; + } + else if(strcmp(str, "Europe/London") == 0) + { + return Nuki::TimeZoneId::Europe_London; + } + else if(strcmp(str, "Europe/Moscow") == 0) + { + return Nuki::TimeZoneId::Europe_Moscow; + } + else if(strcmp(str, "Pacific/Auckland") == 0) + { + return Nuki::TimeZoneId::Pacific_Auckland; + } + else if(strcmp(str, "Pacific/Guam") == 0) + { + return Nuki::TimeZoneId::Pacific_Guam; + } + else if(strcmp(str, "Pacific/Honolulu") == 0) + { + return Nuki::TimeZoneId::Pacific_Honolulu; + } + else if(strcmp(str, "Pacific/Pago_Pago") == 0) + { + return Nuki::TimeZoneId::Pacific_Pago_Pago; + } + else if(strcmp(str, "None") == 0) + { + return Nuki::TimeZoneId::None; + } return (Nuki::TimeZoneId)0xff; } uint8_t NukiOpenerWrapper::fobActionToInt(const char *str) { - if(strcmp(str, "No Action") == 0) return 0; - else if(strcmp(str, "Toggle RTO") == 0) return 1; - else if(strcmp(str, "Activate RTO") == 0) return 2; - else if(strcmp(str, "Deactivate RTO") == 0) return 3; - else if(strcmp(str, "Open") == 0) return 7; - else if(strcmp(str, "Ring") == 0) return 8; + if(strcmp(str, "No Action") == 0) + { + return 0; + } + else if(strcmp(str, "Toggle RTO") == 0) + { + return 1; + } + else if(strcmp(str, "Activate RTO") == 0) + { + return 2; + } + else if(strcmp(str, "Deactivate RTO") == 0) + { + return 3; + } + else if(strcmp(str, "Open") == 0) + { + return 7; + } + else if(strcmp(str, "Ring") == 0) + { + return 8; + } return 99; } uint8_t NukiOpenerWrapper::operatingModeToInt(const char *str) { - if(strcmp(str, "Generic door opener") == 0) return 0; - else if(strcmp(str, "Analogue intercom") == 0) return 1; - else if(strcmp(str, "Digital intercom") == 0) return 2; - else if(strcmp(str, "Siedle") == 0) return 3; - else if(strcmp(str, "TCS") == 0) return 4; - else if(strcmp(str, "Bticino") == 0) return 5; - else if(strcmp(str, "Siedle HTS") == 0) return 6; - else if(strcmp(str, "STR") == 0) return 7; - else if(strcmp(str, "Ritto") == 0) return 8; - else if(strcmp(str, "Fermax") == 0) return 9; - else if(strcmp(str, "Comelit") == 0) return 10; - else if(strcmp(str, "Urmet BiBus") == 0) return 11; - else if(strcmp(str, "Urmet 2Voice") == 0) return 12; - else if(strcmp(str, "Golmar") == 0) return 13; - else if(strcmp(str, "SKS") == 0) return 14; - else if(strcmp(str, "Spare") == 0) return 15; + if(strcmp(str, "Generic door opener") == 0) + { + return 0; + } + else if(strcmp(str, "Analogue intercom") == 0) + { + return 1; + } + else if(strcmp(str, "Digital intercom") == 0) + { + return 2; + } + else if(strcmp(str, "Siedle") == 0) + { + return 3; + } + else if(strcmp(str, "TCS") == 0) + { + return 4; + } + else if(strcmp(str, "Bticino") == 0) + { + return 5; + } + else if(strcmp(str, "Siedle HTS") == 0) + { + return 6; + } + else if(strcmp(str, "STR") == 0) + { + return 7; + } + else if(strcmp(str, "Ritto") == 0) + { + return 8; + } + else if(strcmp(str, "Fermax") == 0) + { + return 9; + } + else if(strcmp(str, "Comelit") == 0) + { + return 10; + } + else if(strcmp(str, "Urmet BiBus") == 0) + { + return 11; + } + else if(strcmp(str, "Urmet 2Voice") == 0) + { + return 12; + } + else if(strcmp(str, "Golmar") == 0) + { + return 13; + } + else if(strcmp(str, "SKS") == 0) + { + return 14; + } + else if(strcmp(str, "Spare") == 0) + { + return 15; + } return 99; } uint8_t NukiOpenerWrapper::doorbellSuppressionToInt(const char *str) { - if(strcmp(str, "Off") == 0) return 0; - else if(strcmp(str, "CM") == 0) return 1; - else if(strcmp(str, "RTO") == 0) return 2; - else if(strcmp(str, "CM & RTO") == 0) return 3; - else if(strcmp(str, "Ring") == 0) return 4; - else if(strcmp(str, "CM & Ring") == 0) return 5; - else if(strcmp(str, "RTO & Ring") == 0) return 6; - else if(strcmp(str, "CM & RTO & Ring") == 0) return 7; + if(strcmp(str, "Off") == 0) + { + return 0; + } + else if(strcmp(str, "CM") == 0) + { + return 1; + } + else if(strcmp(str, "RTO") == 0) + { + return 2; + } + else if(strcmp(str, "CM & RTO") == 0) + { + return 3; + } + else if(strcmp(str, "Ring") == 0) + { + return 4; + } + else if(strcmp(str, "CM & Ring") == 0) + { + return 5; + } + else if(strcmp(str, "RTO & Ring") == 0) + { + return 6; + } + else if(strcmp(str, "CM & RTO & Ring") == 0) + { + return 7; + } return 99; } uint8_t NukiOpenerWrapper::soundToInt(const char *str) { - if(strcmp(str, "No Sound") == 0) return 0; - else if(strcmp(str, "Sound 1") == 0) return 1; - else if(strcmp(str, "Sound 2") == 0) return 2; - else if(strcmp(str, "Sound 3") == 0) return 3; + if(strcmp(str, "No Sound") == 0) + { + return 0; + } + else if(strcmp(str, "Sound 1") == 0) + { + return 1; + } + else if(strcmp(str, "Sound 2") == 0) + { + return 2; + } + else if(strcmp(str, "Sound 3") == 0) + { + return 3; + } return 99; } NukiOpener::ButtonPressAction NukiOpenerWrapper::buttonPressActionToEnum(const char* str) { - if(strcmp(str, "No Action") == 0) return NukiOpener::ButtonPressAction::NoAction; - else if(strcmp(str, "Toggle RTO") == 0) return NukiOpener::ButtonPressAction::ToggleRTO; - else if(strcmp(str, "Activate RTO") == 0) return NukiOpener::ButtonPressAction::ActivateRTO; - else if(strcmp(str, "Deactivate RTO") == 0) return NukiOpener::ButtonPressAction::DeactivateRTO; - else if(strcmp(str, "Toggle CM") == 0) return NukiOpener::ButtonPressAction::ToggleCM; - else if(strcmp(str, "Activate CM") == 0) return NukiOpener::ButtonPressAction::ActivateCM; - else if(strcmp(str, "Deactivate CM") == 0) return NukiOpener::ButtonPressAction::DectivateCM; - else if(strcmp(str, "Open") == 0) return NukiOpener::ButtonPressAction::Open; + if(strcmp(str, "No Action") == 0) + { + return NukiOpener::ButtonPressAction::NoAction; + } + else if(strcmp(str, "Toggle RTO") == 0) + { + return NukiOpener::ButtonPressAction::ToggleRTO; + } + else if(strcmp(str, "Activate RTO") == 0) + { + return NukiOpener::ButtonPressAction::ActivateRTO; + } + else if(strcmp(str, "Deactivate RTO") == 0) + { + return NukiOpener::ButtonPressAction::DeactivateRTO; + } + else if(strcmp(str, "Toggle CM") == 0) + { + return NukiOpener::ButtonPressAction::ToggleCM; + } + else if(strcmp(str, "Activate CM") == 0) + { + return NukiOpener::ButtonPressAction::ActivateCM; + } + else if(strcmp(str, "Deactivate CM") == 0) + { + return NukiOpener::ButtonPressAction::DectivateCM; + } + else if(strcmp(str, "Open") == 0) + { + return NukiOpener::ButtonPressAction::Open; + } return (NukiOpener::ButtonPressAction)0xff; } Nuki::BatteryType NukiOpenerWrapper::batteryTypeToEnum(const char* str) { - if(strcmp(str, "Alkali") == 0) return Nuki::BatteryType::Alkali; - else if(strcmp(str, "Accumulators") == 0) return Nuki::BatteryType::Accumulators; - else if(strcmp(str, "Lithium") == 0) return Nuki::BatteryType::Lithium; + if(strcmp(str, "Alkali") == 0) + { + return Nuki::BatteryType::Alkali; + } + else if(strcmp(str, "Accumulators") == 0) + { + return Nuki::BatteryType::Accumulators; + } + else if(strcmp(str, "Lithium") == 0) + { + return Nuki::BatteryType::Lithium; + } return (Nuki::BatteryType)0xff; } @@ -1113,10 +1531,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) { if(strlen(jsonchar) <= 32) { - if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setName(std::string(jsonchar)); + if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setName(std::string(jsonchar)); + } + } + else + { + jsonResult[basicKeys[i]] = "valueTooLong"; } - else jsonResult[basicKeys[i]] = "valueTooLong"; } else if(strcmp(basicKeys[i], "latitude") == 0) { @@ -1124,10 +1551,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.latitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setLatitude(keyvalue); + if(_nukiConfig.latitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setLatitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "longitude") == 0) { @@ -1135,10 +1571,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.longitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setLongitude(keyvalue); + if(_nukiConfig.longitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setLongitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "pairingEnabled") == 0) { @@ -1146,10 +1591,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.pairingEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enablePairing((keyvalue > 0)); + if(_nukiConfig.pairingEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enablePairing((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "buttonEnabled") == 0) { @@ -1157,10 +1611,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.buttonEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enableButton((keyvalue > 0)); + if(_nukiConfig.buttonEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableButton((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "ledFlashEnabled") == 0) { @@ -1168,10 +1631,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.ledFlashEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enableLedFlash((keyvalue > 0)); + if(_nukiConfig.ledFlashEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableLedFlash((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZoneOffset") == 0) { @@ -1179,10 +1651,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 60) { - if(_nukiConfig.timeZoneOffset == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setTimeZoneOffset(keyvalue); + if(_nukiConfig.timeZoneOffset == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setTimeZoneOffset(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "dstMode") == 0) { @@ -1190,10 +1671,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.dstMode == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enableDst((keyvalue > 0)); + if(_nukiConfig.dstMode == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableDst((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction1") == 0) { @@ -1201,10 +1691,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(fobAct1 != 99) { - if(_nukiConfig.fobAction1 == fobAct1) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setFobAction(1, fobAct1); + if(_nukiConfig.fobAction1 == fobAct1) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setFobAction(1, fobAct1); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction2") == 0) { @@ -1212,10 +1711,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(fobAct2 != 99) { - if(_nukiConfig.fobAction2 == fobAct2) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setFobAction(2, fobAct2); + if(_nukiConfig.fobAction2 == fobAct2) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setFobAction(2, fobAct2); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction3") == 0) { @@ -1223,10 +1731,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(fobAct3 != 99) { - if(_nukiConfig.fobAction3 == fobAct3) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setFobAction(3, fobAct3); + if(_nukiConfig.fobAction3 == fobAct3) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setFobAction(3, fobAct3); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "operatingMode") == 0) { @@ -1234,10 +1751,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(opmode != 99) { - if(_nukiConfig.operatingMode == opmode) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setOperatingMode(opmode); + if(_nukiConfig.operatingMode == opmode) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setOperatingMode(opmode); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "advertisingMode") == 0) { @@ -1245,10 +1771,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)advmode != 0xff) { - if(_nukiConfig.advertisingMode == advmode) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setAdvertisingMode(advmode); + if(_nukiConfig.advertisingMode == advmode) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setAdvertisingMode(advmode); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZone") == 0) { @@ -1256,27 +1791,47 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)tzid != 0xff) { - if(_nukiConfig.timeZoneId == tzid) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setTimeZoneId(tzid); + if(_nukiConfig.timeZoneId == tzid) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setTimeZoneId(tzid); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + if(cmdResult != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) basicUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + basicUpdated = true; + } - if(!jsonResult[basicKeys[i]]) { + if(!jsonResult[basicKeys[i]]) + { char resultStr[15] = {0}; NukiOpener::cmdResultToString(cmdResult, resultStr); jsonResult[basicKeys[i]] = resultStr; } } - else jsonResult[basicKeys[i]] = "accessDenied"; + else + { + jsonResult[basicKeys[i]] = "accessDenied"; + } } } @@ -1305,10 +1860,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0) { - if(_nukiAdvancedConfig.intercomID == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setIntercomID(keyvalue); + if(_nukiAdvancedConfig.intercomID == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setIntercomID(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "busModeSwitch") == 0) { @@ -1316,10 +1880,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.busModeSwitch == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setBusModeSwitch((keyvalue > 0)); + if(_nukiAdvancedConfig.busModeSwitch == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setBusModeSwitch((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "shortCircuitDuration") == 0) { @@ -1327,10 +1900,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0) { - if(_nukiAdvancedConfig.shortCircuitDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setShortCircuitDuration(keyvalue); + if(_nukiAdvancedConfig.shortCircuitDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setShortCircuitDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "electricStrikeDelay") == 0) { @@ -1338,10 +1920,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 30000) { - if(_nukiAdvancedConfig.electricStrikeDelay == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setElectricStrikeDelay(keyvalue); + if(_nukiAdvancedConfig.electricStrikeDelay == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setElectricStrikeDelay(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "randomElectricStrikeDelay") == 0) { @@ -1349,10 +1940,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.randomElectricStrikeDelay == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.enableRandomElectricStrikeDelay((keyvalue > 0)); + if(_nukiAdvancedConfig.randomElectricStrikeDelay == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableRandomElectricStrikeDelay((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "electricStrikeDuration") == 0) { @@ -1360,10 +1960,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 1000 && keyvalue <= 30000) { - if(_nukiAdvancedConfig.electricStrikeDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setElectricStrikeDuration(keyvalue); + if(_nukiAdvancedConfig.electricStrikeDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setElectricStrikeDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "disableRtoAfterRing") == 0) { @@ -1371,10 +1980,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.disableRtoAfterRing == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.disableRtoAfterRing((keyvalue > 0)); + if(_nukiAdvancedConfig.disableRtoAfterRing == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.disableRtoAfterRing((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "rtoTimeout") == 0) { @@ -1382,10 +2000,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 5 && keyvalue <= 60) { - if(_nukiAdvancedConfig.rtoTimeout == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setRtoTimeout(keyvalue); + if(_nukiAdvancedConfig.rtoTimeout == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setRtoTimeout(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doorbellSuppression") == 0) { @@ -1393,10 +2020,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(dbsupr != 99) { - if(_nukiAdvancedConfig.doorbellSuppression == dbsupr) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setDoorbellSuppression(dbsupr); + if(_nukiAdvancedConfig.doorbellSuppression == dbsupr) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setDoorbellSuppression(dbsupr); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doorbellSuppressionDuration") == 0) { @@ -1404,10 +2040,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 500 && keyvalue <= 10000) { - if(_nukiAdvancedConfig.doorbellSuppressionDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setDoorbellSuppressionDuration(keyvalue); + if(_nukiAdvancedConfig.doorbellSuppressionDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setDoorbellSuppressionDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundRing") == 0) { @@ -1415,10 +2060,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundRing == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundRing(sound); + if(_nukiAdvancedConfig.soundRing == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundRing(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundOpen") == 0) { @@ -1426,10 +2080,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundOpen == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundOpen(sound); + if(_nukiAdvancedConfig.soundOpen == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundOpen(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundRto") == 0) { @@ -1437,10 +2100,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundRto == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundRto(sound); + if(_nukiAdvancedConfig.soundRto == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundRto(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundCm") == 0) { @@ -1448,10 +2120,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundCm == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundCm(sound); + if(_nukiAdvancedConfig.soundCm == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundCm(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundConfirmation") == 0) { @@ -1459,10 +2140,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.soundConfirmation == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.enableSoundConfirmation((keyvalue > 0)); + if(_nukiAdvancedConfig.soundConfirmation == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableSoundConfirmation((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundLevel") == 0) { @@ -1470,10 +2160,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 255) { - if(_nukiAdvancedConfig.soundLevel == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundLevel(keyvalue); + if(_nukiAdvancedConfig.soundLevel == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundLevel(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "singleButtonPressAction") == 0) { @@ -1481,10 +2180,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)sbpa != 0xff) { - if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSingleButtonPressAction(sbpa); + if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSingleButtonPressAction(sbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doubleButtonPressAction") == 0) { @@ -1492,10 +2200,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)dbpa != 0xff) { - if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setDoubleButtonPressAction(dbpa); + if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setDoubleButtonPressAction(dbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "batteryType") == 0) { @@ -1503,10 +2220,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)battype != 0xff) { - if(_nukiAdvancedConfig.batteryType == battype) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setBatteryType(battype); + if(_nukiAdvancedConfig.batteryType == battype) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setBatteryType(battype); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "automaticBatteryTypeDetection") == 0) { @@ -1514,35 +2240,60 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.enableAutoBatteryTypeDetection((keyvalue > 0)); + if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableAutoBatteryTypeDetection((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } if(cmdResult != Nuki::CmdResult::Success) { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) advancedUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + advancedUpdated = true; + } - if(!jsonResult[advancedKeys[j]]) { + if(!jsonResult[advancedKeys[j]]) + { char resultStr[15] = {0}; NukiOpener::cmdResultToString(cmdResult, resultStr); jsonResult[advancedKeys[j]] = resultStr; } } - else jsonResult[advancedKeys[j]] = "accessDenied"; + else + { + jsonResult[advancedKeys[j]] = "accessDenied"; + } } } - if(basicUpdated || advancedUpdated) jsonResult["general"] = "success"; - else jsonResult["general"] = "noChange"; + if(basicUpdated || advancedUpdated) + { + jsonResult["general"] = "success"; + } + else + { + jsonResult["general"] = "noChange"; + } - _nextConfigUpdateTs = (esp_timer_get_time() / 1000) + 300; + _nextConfigUpdateTs = espMillis() + 300; serializeJson(jsonResult, _resbuf, sizeof(_resbuf)); _network->publishConfigCommandResult(_resbuf); @@ -1574,30 +2325,33 @@ void NukiOpenerWrapper::gpioActionCallback(const GpioAction &action, const int& { switch(action) { - case GpioAction::ElectricStrikeActuation: - nukiOpenerInst->electricStrikeActuation(); - break; - case GpioAction::ActivateRTO: - nukiOpenerInst->activateRTO(); - break; - case GpioAction::ActivateCM: - nukiOpenerInst->activateCM(); - break; - case GpioAction::DeactivateRtoCm: - nukiOpenerInst->deactivateRtoCm(); - break; - case GpioAction::DeactivateRTO: - nukiOpenerInst->deactivateRTO(); - break; - case GpioAction::DeactivateCM: - nukiOpenerInst->deactivateCM(); - break; + case GpioAction::ElectricStrikeActuation: + nukiOpenerInst->electricStrikeActuation(); + break; + case GpioAction::ActivateRTO: + nukiOpenerInst->activateRTO(); + break; + case GpioAction::ActivateCM: + nukiOpenerInst->activateCM(); + break; + case GpioAction::DeactivateRtoCm: + nukiOpenerInst->deactivateRtoCm(); + break; + case GpioAction::DeactivateRTO: + nukiOpenerInst->deactivateRTO(); + break; + case GpioAction::DeactivateCM: + nukiOpenerInst->deactivateCM(); + break; } } void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint &id, const String &name, const String &code, const int& enabled) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } if(!_preferences->getBool(preference_keypad_control_enabled, false)) { @@ -1712,10 +2466,14 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -1781,21 +2539,57 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json.containsKey("code")) code = json["code"].as(); - else code = 12; + if(json["code"].is()) + { + code = json["code"].as(); + } + else + { + code = 12; + } - if(json.containsKey("enabled")) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json.containsKey("timeLimited")) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json.containsKey("name")) name = json["name"].as(); - if(json.containsKey("allowedFrom")) allowedFrom = json["allowedFrom"].as(); - if(json.containsKey("allowedUntil")) allowedUntil = json["allowedUntil"].as(); - if(json.containsKey("allowedWeekdays")) allowedWeekdays = json["allowedWeekdays"].as(); - if(json.containsKey("allowedFromTime")) allowedFromTime = json["allowedFromTime"].as(); - if(json.containsKey("allowedUntilTime")) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -2121,6 +2915,7 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) allowedUntilTimeAr[0] = entry.allowedUntilTimeHour; allowedUntilTimeAr[1] = entry.allowedUntilTimeMin; } + } if(!foundExisting) @@ -2266,12 +3061,27 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) String lockAction; NukiOpener::LockAction timeControlLockAction; - if(json.containsKey("enabled")) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json.containsKey("weekdays")) weekdays = json["weekdays"].as(); - if(json.containsKey("time")) time = json["time"].as(); - if(json.containsKey("lockAction")) lockAction = json["lockAction"].as(); + if(json["weekdays"].is()) + { + weekdays = json["weekdays"].as(); + } + if(json["time"].is()) + { + time = json["time"].as(); + } + if(json["lockAction"].is()) + { + lockAction = json["lockAction"].as(); + } if(lockAction.length() > 0) { @@ -2298,7 +3108,8 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) while(retryCount < _nrOfRetries + 1) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiOpener.removeTimeControlEntry(entryId); @@ -2338,13 +3149,34 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) } } - if(weekdays.indexOf("mon") >= 0) weekdaysInt += 64; - if(weekdays.indexOf("tue") >= 0) weekdaysInt += 32; - if(weekdays.indexOf("wed") >= 0) weekdaysInt += 16; - if(weekdays.indexOf("thu") >= 0) weekdaysInt += 8; - if(weekdays.indexOf("fri") >= 0) weekdaysInt += 4; - if(weekdays.indexOf("sat") >= 0) weekdaysInt += 2; - if(weekdays.indexOf("sun") >= 0) weekdaysInt += 1; + if(weekdays.indexOf("mon") >= 0) + { + weekdaysInt += 64; + } + if(weekdays.indexOf("tue") >= 0) + { + weekdaysInt += 32; + } + if(weekdays.indexOf("wed") >= 0) + { + weekdaysInt += 16; + } + if(weekdays.indexOf("thu") >= 0) + { + weekdaysInt += 8; + } + if(weekdays.indexOf("fri") >= 0) + { + weekdaysInt += 4; + } + if(weekdays.indexOf("sat") >= 0) + { + weekdaysInt += 2; + } + if(weekdays.indexOf("sun") >= 0) + { + weekdaysInt += 1; + } if(strcmp(action, "add") == 0) { @@ -2382,18 +3214,33 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) for(const auto& entry : timeControlEntries) { - if (entryId != entry.entryId) continue; - else foundExisting = true; + if (entryId != entry.entryId) + { + continue; + } + else + { + foundExisting = true; + } - if(enabled == 2) enabled = entry.enabled; - if(weekdays.length() < 1) weekdaysInt = entry.weekdays; + if(enabled == 2) + { + enabled = entry.enabled; + } + if(weekdays.length() < 1) + { + weekdaysInt = entry.weekdays; + } if(time.length() < 1) { time = "old"; timeAr[0] = entry.timeHour; timeAr[1] = entry.timeMin; } - if(lockAction.length() < 1) timeControlLockAction = entry.lockAction; + if(lockAction.length() < 1) + { + timeControlLockAction = entry.lockAction; + } } if(!foundExisting) @@ -2432,10 +3279,14 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -2446,7 +3297,7 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) _network->publishTimeControlCommandResult(resultStr); } - _nextConfigUpdateTs = (esp_timer_get_time() / 1000) + 300; + _nextConfigUpdateTs = espMillis() + 300; } else { @@ -2500,22 +3351,58 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json.containsKey("remoteAllowed")) remoteAllowed = json["remoteAllowed"].as(); - else remoteAllowed = 2; + if(json["remoteAllowed"].is()) + { + remoteAllowed = json["remoteAllowed"].as(); + } + else + { + remoteAllowed = 2; + } - if(json.containsKey("enabled")) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json.containsKey("timeLimited")) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json.containsKey("name")) name = json["name"].as(); - //if(json.containsKey("sharedKey")) sharedKey = json["sharedKey"].as(); - if(json.containsKey("allowedFrom")) allowedFrom = json["allowedFrom"].as(); - if(json.containsKey("allowedUntil")) allowedUntil = json["allowedUntil"].as(); - if(json.containsKey("allowedWeekdays")) allowedWeekdays = json["allowedWeekdays"].as(); - if(json.containsKey("allowedFromTime")) allowedFromTime = json["allowedFromTime"].as(); - if(json.containsKey("allowedUntilTime")) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } + //if(json["sharedKey"].is()) sharedKey = json["sharedKey"].as(); + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -2667,13 +3554,34 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) } } - if(allowedWeekdays.indexOf("mon") >= 0) allowedWeekdaysInt += 64; - if(allowedWeekdays.indexOf("tue") >= 0) allowedWeekdaysInt += 32; - if(allowedWeekdays.indexOf("wed") >= 0) allowedWeekdaysInt += 16; - if(allowedWeekdays.indexOf("thu") >= 0) allowedWeekdaysInt += 8; - if(allowedWeekdays.indexOf("fri") >= 0) allowedWeekdaysInt += 4; - if(allowedWeekdays.indexOf("sat") >= 0) allowedWeekdaysInt += 2; - if(allowedWeekdays.indexOf("sun") >= 0) allowedWeekdaysInt += 1; + if(allowedWeekdays.indexOf("mon") >= 0) + { + allowedWeekdaysInt += 64; + } + if(allowedWeekdays.indexOf("tue") >= 0) + { + allowedWeekdaysInt += 32; + } + if(allowedWeekdays.indexOf("wed") >= 0) + { + allowedWeekdaysInt += 16; + } + if(allowedWeekdays.indexOf("thu") >= 0) + { + allowedWeekdaysInt += 8; + } + if(allowedWeekdays.indexOf("fri") >= 0) + { + allowedWeekdaysInt += 4; + } + if(allowedWeekdays.indexOf("sat") >= 0) + { + allowedWeekdaysInt += 2; + } + if(allowedWeekdays.indexOf("sun") >= 0) + { + allowedWeekdaysInt += 1; + } } if(strcmp(action, "add") == 0) @@ -2762,17 +3670,32 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) for(const auto& entry : entries) { - if (authId != entry.authId) continue; - else foundExisting = true; + if (authId != entry.authId) + { + continue; + } + else + { + foundExisting = true; + } if(name.length() < 1) { memset(oldName, 0, sizeof(oldName)); memcpy(oldName, entry.name, sizeof(entry.name)); } - if(remoteAllowed == 2) remoteAllowed = entry.remoteAllowed; - if(enabled == 2) enabled = entry.enabled; - if(timeLimited == 2) timeLimited = entry.timeLimited; + if(remoteAllowed == 2) + { + remoteAllowed = entry.remoteAllowed; + } + if(enabled == 2) + { + enabled = entry.enabled; + } + if(timeLimited == 2) + { + timeLimited = entry.timeLimited; + } if(allowedFrom.length() < 1) { allowedFrom = "old"; @@ -2793,7 +3716,10 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) allowedUntilAr[4] = entry.allowedUntilMinute; allowedUntilAr[5] = entry.allowedUntilSecond; } - if(allowedWeekdays.length() < 1) allowedWeekdaysInt = entry.allowedWeekdays; + if(allowedWeekdays.length() < 1) + { + allowedWeekdaysInt = entry.allowedWeekdays; + } if(allowedFromTime.length() < 1) { allowedFromTime = "old"; @@ -2891,10 +3817,14 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } updateAuth(false); @@ -2959,10 +3889,14 @@ void NukiOpenerWrapper::readConfig() result = _nukiOpener.requestConfig(&_nukiConfig); _nukiConfigValid = result == Nuki::CmdResult::Success; - if(!_nukiConfigValid) { + if(!_nukiConfigValid) + { ++retryCount; } - else break; + else + { + break; + } } char resultStr[20]; @@ -2982,13 +3916,17 @@ void NukiOpenerWrapper::readAdvancedConfig() while(retryCount < _nrOfRetries + 1) { - result = _nukiOpener.requestAdvancedConfig(&_nukiAdvancedConfig); + result = _nukiOpener.requestAdvancedConfig(&_nukiAdvancedConfig); _nukiAdvancedConfigValid = result == Nuki::CmdResult::Success; - if(!_nukiAdvancedConfigValid) { + if(!_nukiAdvancedConfigValid) + { ++retryCount; } - else break; + else + { + break; + } } char resultStr[20]; @@ -3000,15 +3938,27 @@ void NukiOpenerWrapper::readAdvancedConfig() void NukiOpenerWrapper::setupHASS() { - if(!_nukiConfigValid) return; - if(_preferences->getUInt(preference_nuki_id_opener, 0) != _nukiConfig.nukiId) return; + if(!_nukiConfigValid) + { + return; + } + if(_preferences->getUInt(preference_nuki_id_opener, 0) != _nukiConfig.nukiId) + { + return; + } String baseTopic = _preferences->getString(preference_mqtt_opener_path); char uidString[20]; itoa(_nukiConfig.nukiId, uidString, 16); - if(_preferences->getBool(preference_opener_continuous_mode, false)) _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateCM", (char*)"activateCM", (char*)"electricStrikeActuation"); - else _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateRTO", (char*)"activateRTO", (char*)"electricStrikeActuation"); + if(_preferences->getBool(preference_opener_continuous_mode, false)) + { + _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateCM", (char*)"activateCM", (char*)"electricStrikeActuation"); + } + else + { + _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateRTO", (char*)"activateRTO", (char*)"electricStrikeActuation"); + } _hassSetupCompleted = true; @@ -3059,15 +4009,15 @@ void NukiOpenerWrapper::updateGpioOutputs() { switch(entry.role) { - case PinRole::OutputHighRtoActive: - _gpio->setPinOutput(entry.pin, rtoActive ? HIGH : LOW); - break; - case PinRole::OutputHighCmActive: - _gpio->setPinOutput(entry.pin, cmActive ? HIGH : LOW); - break; - case PinRole::OutputHighRtoOrCmActive: - _gpio->setPinOutput(entry.pin, rtoActive || cmActive ? HIGH : LOW); - break; + case PinRole::OutputHighRtoActive: + _gpio->setPinOutput(entry.pin, rtoActive ? HIGH : LOW); + break; + case PinRole::OutputHighCmActive: + _gpio->setPinOutput(entry.pin, cmActive ? HIGH : LOW); + break; + case PinRole::OutputHighRtoOrCmActive: + _gpio->setPinOutput(entry.pin, rtoActive || cmActive ? HIGH : LOW); + break; } } } \ No newline at end of file diff --git a/src/NukiPublisher.cpp b/src/NukiPublisher.cpp index 78376ec..2ee3289 100644 --- a/src/NukiPublisher.cpp +++ b/src/NukiPublisher.cpp @@ -2,8 +2,8 @@ NukiPublisher::NukiPublisher(NukiNetwork *network, const char* mqttPath) -: _network(network), - _mqttPath(mqttPath) + : _network(network), + _mqttPath(mqttPath) { } diff --git a/src/NukiWrapper.cpp b/src/NukiWrapper.cpp index da04bfb..2235b7f 100644 --- a/src/NukiWrapper.cpp +++ b/src/NukiWrapper.cpp @@ -1,3 +1,6 @@ +#ifndef CONFIG_IDF_TARGET_ESP32H2 +#include "esp_wifi.h" +#endif #include "NukiWrapper.h" #include "PreferencesKeys.h" #include "MqttTopics.h" @@ -9,14 +12,14 @@ NukiWrapper* nukiInst = nullptr; NukiWrapper::NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkLock* network, NukiOfficial* nukiOfficial, Gpio* gpio, Preferences* preferences) -: _deviceName(deviceName), - _deviceId(deviceId), - _bleScanner(scanner), - _nukiLock(deviceName, _deviceId->get()), - _network(network), - _nukiOfficial(nukiOfficial), - _gpio(gpio), - _preferences(preferences) + : _deviceName(deviceName), + _deviceId(deviceId), + _bleScanner(scanner), + _nukiLock(deviceName, _deviceId->get()), + _network(network), + _nukiOfficial(nukiOfficial), + _gpio(gpio), + _preferences(preferences) { Log->print("Device id lock: "); Log->println(_deviceId->get()); @@ -58,8 +61,27 @@ 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); + +#ifndef CONFIG_IDF_TARGET_ESP32H2 + wifi_config_t wifi_cfg; + if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { + Log->println("Failed to get Wi-Fi configuration in RAM"); + } + + if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK) + { + Log->println("Failed to set storage Wi-Fi"); + } + + memset(wifi_cfg.sta.ssid, 0, sizeof(wifi_cfg.sta.ssid)); + memset(wifi_cfg.sta.password, 0, sizeof(wifi_cfg.sta.password)); + + if (esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { + Log->println("Failed to clear NVS Wi-Fi configuration"); + } +#endif _preferences->putBool(preference_check_updates, true); _preferences->putBool(preference_opener_continuous_mode, false); _preferences->putBool(preference_official_hybrid_enabled, false); @@ -111,14 +133,38 @@ void NukiWrapper::readSettings() esp_power_level_t powerLevel; int pwrLvl = _preferences->getInt(preference_ble_tx_power, 9); - if(pwrLvl >= 9) powerLevel = ESP_PWR_LVL_P9; - else if(pwrLvl >= 6) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 3) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 0) powerLevel = ESP_PWR_LVL_P3; - else if(pwrLvl >= -3) powerLevel = ESP_PWR_LVL_N3; - else if(pwrLvl >= -6) powerLevel = ESP_PWR_LVL_N6; - else if(pwrLvl >= -9) powerLevel = ESP_PWR_LVL_N9; - else if(pwrLvl >= -12) powerLevel = ESP_PWR_LVL_N12; + if(pwrLvl >= 9) + { + powerLevel = ESP_PWR_LVL_P9; + } + else if(pwrLvl >= 6) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 3) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 0) + { + powerLevel = ESP_PWR_LVL_P3; + } + else if(pwrLvl >= -3) + { + powerLevel = ESP_PWR_LVL_N3; + } + else if(pwrLvl >= -6) + { + powerLevel = ESP_PWR_LVL_N6; + } + else if(pwrLvl >= -9) + { + powerLevel = ESP_PWR_LVL_N9; + } + else if(pwrLvl >= -12) + { + powerLevel = ESP_PWR_LVL_N12; + } _nukiLock.setPower(powerLevel); @@ -229,14 +275,14 @@ void NukiWrapper::update() } int64_t lastReceivedBeaconTs = _nukiLock.getLastReceivedBeaconTs(); - int64_t ts = (esp_timer_get_time() / 1000); + int64_t ts = espMillis(); uint8_t queryCommands = _network->queryCommands(); if(_restartBeaconTimeout > 0 && - ts > 60000 && - lastReceivedBeaconTs > 0 && - _disableBleWatchdogTs < ts && - (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) + ts > 60000 && + lastReceivedBeaconTs > 0 && + _disableBleWatchdogTs < ts && + (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) { Log->print("No BLE beacon received from the lock for "); Log->print((ts - lastReceivedBeaconTs) / 1000); @@ -249,7 +295,7 @@ void NukiWrapper::update() if(_nukiOfficial->getOffCommandExecutedTs() > 0 && ts >= _nukiOfficial->getOffCommandExecutedTs()) { - nukiInst->_nextLockAction = _offCommand; + _nextLockAction = _offCommand; _nukiOfficial->clearOffCommandExecutedTs(); } if(_nextLockAction != (NukiLock::LockAction)0xff) @@ -290,9 +336,16 @@ void NukiWrapper::update() _nextLockAction = (NukiLock::LockAction) 0xff; _network->publishRetry("--"); retryCount = 0; - if(!_nukiOfficial->getOffConnected()) _statusUpdated = true; Log->println(F("Lock: updating status after action")); + if(!_nukiOfficial->getOffConnected()) + { + _statusUpdated = true; + } + Log->println(F("Lock: updating status after action")); _statusUpdatedTs = ts; - if(_intervalLockstate > 10) _nextLockStateUpdateTs = ts + 10 * 1000; + if(_intervalLockstate > 10) + { + _nextLockStateUpdateTs = ts + 10 * 1000; + } } else { @@ -472,7 +525,7 @@ void NukiWrapper::updateKeyTurnerState() Log->print(F("Query lock state retrying in ")); Log->print(_retryDelay); Log->println("ms"); - _nextLockStateUpdateTs = (esp_timer_get_time() / 1000) + _retryDelay; + _nextLockStateUpdateTs = espMillis() + _retryDelay; } return; } @@ -481,13 +534,16 @@ void NukiWrapper::updateKeyTurnerState() const NukiLock::LockState& lockState = _keyTurnerState.lockState; - if(lockState != _lastKeyTurnerState.lockState) _statusUpdatedTs = esp_timer_get_time() / 1000; + if(lockState != _lastKeyTurnerState.lockState) + { + _statusUpdatedTs = espMillis(); + } if(lockState == NukiLock::LockState::Locked || - lockState == NukiLock::LockState::Unlocked || - lockState == NukiLock::LockState::Calibration || - lockState == NukiLock::LockState::BootRun || - lockState == NukiLock::LockState::MotorBlocked) + lockState == NukiLock::LockState::Unlocked || + lockState == NukiLock::LockState::Calibration || + lockState == NukiLock::LockState::BootRun || + lockState == NukiLock::LockState::MotorBlocked) { if(_publishAuthData && (lockState == NukiLock::LockState::Locked || lockState == NukiLock::LockState::Unlocked)) { @@ -498,7 +554,7 @@ void NukiWrapper::updateKeyTurnerState() updateGpioOutputs(); } - else if(!_nukiOfficial->getOffConnected() && (esp_timer_get_time() / 1000) < _statusUpdatedTs + 10000) + else if(!_nukiOfficial->getOffConnected() && espMillis() < _statusUpdatedTs + 10000) { _statusUpdated = true; Log->println(F("Lock: Keep updating status on intermediate lock state")); @@ -528,10 +584,14 @@ void NukiWrapper::updateBatteryState() Log->print("): "); result = _nukiLock.requestBatteryReport(&_batteryReport); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -568,13 +628,23 @@ void NukiWrapper::updateConfig() _hasKeypad = _nukiConfig.hasKeypad > 0 || _nukiConfig.hasKeypadV2 > 0; _firmwareVersion = std::to_string(_nukiConfig.firmwareVersion[0]) + "." + std::to_string(_nukiConfig.firmwareVersion[1]) + "." + std::to_string(_nukiConfig.firmwareVersion[2]); _hardwareVersion = std::to_string(_nukiConfig.hardwareRevision[0]) + "." + std::to_string(_nukiConfig.hardwareRevision[1]); - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishConfig(_nukiConfig); - if(_preferences->getBool(preference_timecontrol_info_enabled)) updateTimeControl(false); - if(_preferences->getBool(preference_auth_info_enabled)) updateAuth(false); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishConfig(_nukiConfig); + } + if(_preferences->getBool(preference_timecontrol_info_enabled)) + { + updateTimeControl(false); + } + if(_preferences->getBool(preference_auth_info_enabled)) + { + updateAuth(false); + } const int pinStatus = _preferences->getInt(preference_lock_pin_status, 4); - if(isPinSet()) { + if(isPinSet()) + { Nuki::CmdResult result = (Nuki::CmdResult)-1; int retryCount = 0; Log->println(F("Nuki Lock PIN is set")); @@ -582,23 +652,29 @@ void NukiWrapper::updateConfig() while(retryCount < _nrOfRetries + 1) { result = _nukiLock.verifySecurityPin(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if(result != Nuki::CmdResult::Success) { Log->println(F("Nuki Lock PIN is invalid")); - if(pinStatus != 2) { + if(pinStatus != 2) + { _preferences->putInt(preference_lock_pin_status, 2); } } else { Log->println(F("Nuki Lock PIN is valid")); - if(pinStatus != 1) { + if(pinStatus != 1) + { _preferences->putInt(preference_lock_pin_status, 1); } } @@ -606,7 +682,8 @@ void NukiWrapper::updateConfig() else { Log->println(F("Nuki Lock PIN is not set")); - if(pinStatus != 0) { + if(pinStatus != 0) + { _preferences->putInt(preference_lock_pin_status, 0); } } @@ -629,7 +706,10 @@ void NukiWrapper::updateConfig() if(_nukiAdvancedConfigValid) { - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishAdvancedConfig(_nukiAdvancedConfig); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishAdvancedConfig(_nukiAdvancedConfig); + } } else { @@ -647,7 +727,7 @@ void NukiWrapper::updateConfig() { ++_retryConfigCount; Log->println(F("Invalid/Unexpected lock config and/or advanced config recieved, retrying in 10 seconds")); - int64_t ts = (esp_timer_get_time() / 1000); + int64_t ts = espMillis(); _nextConfigUpdateTs = ts + 10000; } } @@ -669,16 +749,20 @@ void NukiWrapper::updateAuthData(bool retrieved) { Log->print(F("Retrieve log entries: ")); result = _nukiLock.retrieveLogEntries(0, _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 1, false); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); if(result == Nuki::CmdResult::Success) { - _waitAuthLogUpdateTs = (esp_timer_get_time() / 1000) + 5000; + _waitAuthLogUpdateTs = espMillis() + 5000; delay(100); std::list log; @@ -689,11 +773,14 @@ void NukiWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, 3)); } - log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) + { + return a.index < b.index; + }); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, true); + _network->publishAuthorizationInfo(log, true); } } } @@ -707,14 +794,17 @@ void NukiWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG)); } - log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) + { + return a.index < b.index; + }); Log->print(F("Log size: ")); Log->println(log.size()); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, false); + _network->publishAuthorizationInfo(log, false); } } @@ -723,7 +813,10 @@ void NukiWrapper::updateAuthData(bool retrieved) void NukiWrapper::updateKeypad(bool retrieved) { - if(!_preferences->getBool(preference_keypad_info_enabled)) return; + if(!_preferences->getBool(preference_keypad_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -740,16 +833,20 @@ void NukiWrapper::updateKeypad(bool retrieved) { Log->print(F("Querying lock keypad: ")); result = _nukiLock.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); if(result == Nuki::CmdResult::Success) { - _waitKeypadUpdateTs = (esp_timer_get_time() / 1000) + 5000; + _waitKeypadUpdateTs = espMillis() + 5000; } } else @@ -760,7 +857,10 @@ void NukiWrapper::updateKeypad(bool retrieved) Log->print(F("Lock keypad codes: ")); Log->println(entries.size()); - entries.sort([](const NukiLock::KeypadEntry& a, const NukiLock::KeypadEntry& b) { return a.codeId < b.codeId; }); + entries.sort([](const NukiLock::KeypadEntry& a, const NukiLock::KeypadEntry& b) + { + return a.codeId < b.codeId; + }); if(entries.size() > _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)) { @@ -792,7 +892,10 @@ void NukiWrapper::updateKeypad(bool retrieved) void NukiWrapper::updateTimeControl(bool retrieved) { - if(!_preferences->getBool(preference_timecontrol_info_enabled)) return; + if(!_preferences->getBool(preference_timecontrol_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -809,16 +912,20 @@ void NukiWrapper::updateTimeControl(bool retrieved) { Log->print(F("Querying lock timecontrol: ")); result = _nukiLock.retrieveTimeControlEntries(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); if(result == Nuki::CmdResult::Success) { - _waitTimeControlUpdateTs = (esp_timer_get_time() / 1000) + 5000; + _waitTimeControlUpdateTs = espMillis() + 5000; } } else @@ -829,7 +936,10 @@ void NukiWrapper::updateTimeControl(bool retrieved) Log->print(F("Lock timecontrol entries: ")); Log->println(timeControlEntries.size()); - timeControlEntries.sort([](const NukiLock::TimeControlEntry& a, const NukiLock::TimeControlEntry& b) { return a.entryId < b.entryId; }); + timeControlEntries.sort([](const NukiLock::TimeControlEntry& a, const NukiLock::TimeControlEntry& b) + { + return a.entryId < b.entryId; + }); if(timeControlEntries.size() > _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL)) { @@ -858,7 +968,10 @@ void NukiWrapper::updateTimeControl(bool retrieved) void NukiWrapper::updateAuth(bool retrieved) { - if(!_preferences->getBool(preference_auth_info_enabled)) return; + if(!_preferences->getBool(preference_auth_info_enabled)) + { + return; + } if(!retrieved) { @@ -870,10 +983,14 @@ void NukiWrapper::updateAuth(bool retrieved) Log->print(F("Querying lock authorization: ")); result = _nukiLock.retrieveAuthorizationEntries(0, _preferences->getInt(preference_auth_max_entries, MAX_AUTH)); delay(250); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -890,7 +1007,10 @@ void NukiWrapper::updateAuth(bool retrieved) Log->print(F("Lock authorization entries: ")); Log->println(authEntries.size()); - authEntries.sort([](const NukiLock::AuthorizationEntry& a, const NukiLock::AuthorizationEntry& b) { return a.authId < b.authId; }); + authEntries.sort([](const NukiLock::AuthorizationEntry& a, const NukiLock::AuthorizationEntry& b) + { + return a.authId < b.authId; + }); if(authEntries.size() > _preferences->getInt(preference_auth_max_entries, MAX_AUTH)) { @@ -919,20 +1039,47 @@ void NukiWrapper::updateAuth(bool retrieved) void NukiWrapper::postponeBleWatchdog() { - _disableBleWatchdogTs = (esp_timer_get_time() / 1000) + 15000; + _disableBleWatchdogTs = espMillis() + 15000; } NukiLock::LockAction NukiWrapper::lockActionToEnum(const char *str) { - if(strcmp(str, "unlock") == 0 || strcmp(str, "Unlock") == 0) return NukiLock::LockAction::Unlock; - else if(strcmp(str, "lock") == 0 || strcmp(str, "Lock") == 0) return NukiLock::LockAction::Lock; - else if(strcmp(str, "unlatch") == 0 || strcmp(str, "Unlatch") == 0) return NukiLock::LockAction::Unlatch; - else if(strcmp(str, "lockNgo") == 0 || strcmp(str, "LockNgo") == 0) return NukiLock::LockAction::LockNgo; - else if(strcmp(str, "lockNgoUnlatch") == 0 || strcmp(str, "LockNgoUnlatch") == 0) return NukiLock::LockAction::LockNgoUnlatch; - else if(strcmp(str, "fullLock") == 0 || strcmp(str, "FullLock") == 0) return NukiLock::LockAction::FullLock; - else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) return NukiLock::LockAction::FobAction2; - else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) return NukiLock::LockAction::FobAction1; - else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) return NukiLock::LockAction::FobAction3; + if(strcmp(str, "unlock") == 0 || strcmp(str, "Unlock") == 0) + { + return NukiLock::LockAction::Unlock; + } + else if(strcmp(str, "lock") == 0 || strcmp(str, "Lock") == 0) + { + return NukiLock::LockAction::Lock; + } + else if(strcmp(str, "unlatch") == 0 || strcmp(str, "Unlatch") == 0) + { + return NukiLock::LockAction::Unlatch; + } + else if(strcmp(str, "lockNgo") == 0 || strcmp(str, "LockNgo") == 0) + { + return NukiLock::LockAction::LockNgo; + } + else if(strcmp(str, "lockNgoUnlatch") == 0 || strcmp(str, "LockNgoUnlatch") == 0) + { + return NukiLock::LockAction::LockNgoUnlatch; + } + else if(strcmp(str, "fullLock") == 0 || strcmp(str, "FullLock") == 0) + { + return NukiLock::LockAction::FullLock; + } + else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) + { + return NukiLock::LockAction::FobAction2; + } + else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) + { + return NukiLock::LockAction::FobAction1; + } + else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) + { + return NukiLock::LockAction::FobAction3; + } return (NukiLock::LockAction)0xff; } @@ -950,23 +1097,35 @@ LockActionResult NukiWrapper::onLockActionReceived(const char *value) if(strlen(value) > 0) { action = nukiInst->lockActionToEnum(value); - if((int)action == 0xff) return LockActionResult::UnknownAction; + if((int)action == 0xff) + { + return LockActionResult::UnknownAction; + } + } + else + { + return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; + else + { + return LockActionResult::UnknownAction; + } uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); if((action == NukiLock::LockAction::Lock && (int)aclPrefs[0] == 1) || (action == NukiLock::LockAction::Unlock && (int)aclPrefs[1] == 1) || (action == NukiLock::LockAction::Unlatch && (int)aclPrefs[2] == 1) || (action == NukiLock::LockAction::LockNgo && (int)aclPrefs[3] == 1) || (action == NukiLock::LockAction::LockNgoUnlatch && (int)aclPrefs[4] == 1) || (action == NukiLock::LockAction::FullLock && (int)aclPrefs[5] == 1) || (action == NukiLock::LockAction::FobAction1 && (int)aclPrefs[6] == 1) || (action == NukiLock::LockAction::FobAction2 && (int)aclPrefs[7] == 1) || (action == NukiLock::LockAction::FobAction3 && (int)aclPrefs[8] == 1)) { - if(!_nukiOfficial->getOffConnected()) nukiInst->_nextLockAction = action; + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->_nextLockAction = action; + } else { if(_preferences->getBool(preference_official_hybrid_actions, false)) { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); + _nukiOfficial->setOffCommandExecutedTs(espMillis() + 2000); _offCommand = action; _network->publishOffAction((int)action); } @@ -998,92 +1157,290 @@ bool NukiWrapper::offConnected() Nuki::AdvertisingMode NukiWrapper::advertisingModeToEnum(const char *str) { - if(strcmp(str, "Automatic") == 0) return Nuki::AdvertisingMode::Automatic; - else if(strcmp(str, "Normal") == 0) return Nuki::AdvertisingMode::Normal; - else if(strcmp(str, "Slow") == 0) return Nuki::AdvertisingMode::Slow; - else if(strcmp(str, "Slowest") == 0) return Nuki::AdvertisingMode::Slowest; + if(strcmp(str, "Automatic") == 0) + { + return Nuki::AdvertisingMode::Automatic; + } + else if(strcmp(str, "Normal") == 0) + { + return Nuki::AdvertisingMode::Normal; + } + else if(strcmp(str, "Slow") == 0) + { + return Nuki::AdvertisingMode::Slow; + } + else if(strcmp(str, "Slowest") == 0) + { + return Nuki::AdvertisingMode::Slowest; + } return (Nuki::AdvertisingMode)0xff; } Nuki::TimeZoneId NukiWrapper::timeZoneToEnum(const char *str) { - if(strcmp(str, "Africa/Cairo") == 0) return Nuki::TimeZoneId::Africa_Cairo; - else if(strcmp(str, "Africa/Lagos") == 0) return Nuki::TimeZoneId::Africa_Lagos; - else if(strcmp(str, "Africa/Maputo") == 0) return Nuki::TimeZoneId::Africa_Maputo; - else if(strcmp(str, "Africa/Nairobi") == 0) return Nuki::TimeZoneId::Africa_Nairobi; - else if(strcmp(str, "America/Anchorage") == 0) return Nuki::TimeZoneId::America_Anchorage; - else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; - else if(strcmp(str, "America/Chicago") == 0) return Nuki::TimeZoneId::America_Chicago; - else if(strcmp(str, "America/Denver") == 0) return Nuki::TimeZoneId::America_Denver; - else if(strcmp(str, "America/Halifax") == 0) return Nuki::TimeZoneId::America_Halifax; - else if(strcmp(str, "America/Los_Angeles") == 0) return Nuki::TimeZoneId::America_Los_Angeles; - else if(strcmp(str, "America/Manaus") == 0) return Nuki::TimeZoneId::America_Manaus; - else if(strcmp(str, "America/Mexico_City") == 0) return Nuki::TimeZoneId::America_Mexico_City; - else if(strcmp(str, "America/New_York") == 0) return Nuki::TimeZoneId::America_New_York; - else if(strcmp(str, "America/Phoenix") == 0) return Nuki::TimeZoneId::America_Phoenix; - else if(strcmp(str, "America/Regina") == 0) return Nuki::TimeZoneId::America_Regina; - else if(strcmp(str, "America/Santiago") == 0) return Nuki::TimeZoneId::America_Santiago; - else if(strcmp(str, "America/Sao_Paulo") == 0) return Nuki::TimeZoneId::America_Sao_Paulo; - else if(strcmp(str, "America/St_Johns") == 0) return Nuki::TimeZoneId::America_St_Johns; - else if(strcmp(str, "Asia/Bangkok") == 0) return Nuki::TimeZoneId::Asia_Bangkok; - else if(strcmp(str, "Asia/Dubai") == 0) return Nuki::TimeZoneId::Asia_Dubai; - else if(strcmp(str, "Asia/Hong_Kong") == 0) return Nuki::TimeZoneId::Asia_Hong_Kong; - else if(strcmp(str, "Asia/Jerusalem") == 0) return Nuki::TimeZoneId::Asia_Jerusalem; - else if(strcmp(str, "Asia/Karachi") == 0) return Nuki::TimeZoneId::Asia_Karachi; - else if(strcmp(str, "Asia/Kathmandu") == 0) return Nuki::TimeZoneId::Asia_Kathmandu; - else if(strcmp(str, "Asia/Kolkata") == 0) return Nuki::TimeZoneId::Asia_Kolkata; - else if(strcmp(str, "Asia/Riyadh") == 0) return Nuki::TimeZoneId::Asia_Riyadh; - else if(strcmp(str, "Asia/Seoul") == 0) return Nuki::TimeZoneId::Asia_Seoul; - else if(strcmp(str, "Asia/Shanghai") == 0) return Nuki::TimeZoneId::Asia_Shanghai; - else if(strcmp(str, "Asia/Tehran") == 0) return Nuki::TimeZoneId::Asia_Tehran; - else if(strcmp(str, "Asia/Tokyo") == 0) return Nuki::TimeZoneId::Asia_Tokyo; - else if(strcmp(str, "Asia/Yangon") == 0) return Nuki::TimeZoneId::Asia_Yangon; - else if(strcmp(str, "Australia/Adelaide") == 0) return Nuki::TimeZoneId::Australia_Adelaide; - else if(strcmp(str, "Australia/Brisbane") == 0) return Nuki::TimeZoneId::Australia_Brisbane; - else if(strcmp(str, "Australia/Darwin") == 0) return Nuki::TimeZoneId::Australia_Darwin; - else if(strcmp(str, "Australia/Hobart") == 0) return Nuki::TimeZoneId::Australia_Hobart; - else if(strcmp(str, "Australia/Perth") == 0) return Nuki::TimeZoneId::Australia_Perth; - else if(strcmp(str, "Australia/Sydney") == 0) return Nuki::TimeZoneId::Australia_Sydney; - else if(strcmp(str, "Europe/Berlin") == 0) return Nuki::TimeZoneId::Europe_Berlin; - else if(strcmp(str, "Europe/Helsinki") == 0) return Nuki::TimeZoneId::Europe_Helsinki; - else if(strcmp(str, "Europe/Istanbul") == 0) return Nuki::TimeZoneId::Europe_Istanbul; - else if(strcmp(str, "Europe/London") == 0) return Nuki::TimeZoneId::Europe_London; - else if(strcmp(str, "Europe/Moscow") == 0) return Nuki::TimeZoneId::Europe_Moscow; - else if(strcmp(str, "Pacific/Auckland") == 0) return Nuki::TimeZoneId::Pacific_Auckland; - else if(strcmp(str, "Pacific/Guam") == 0) return Nuki::TimeZoneId::Pacific_Guam; - else if(strcmp(str, "Pacific/Honolulu") == 0) return Nuki::TimeZoneId::Pacific_Honolulu; - else if(strcmp(str, "Pacific/Pago_Pago") == 0) return Nuki::TimeZoneId::Pacific_Pago_Pago; - else if(strcmp(str, "None") == 0) return Nuki::TimeZoneId::None; + if(strcmp(str, "Africa/Cairo") == 0) + { + return Nuki::TimeZoneId::Africa_Cairo; + } + else if(strcmp(str, "Africa/Lagos") == 0) + { + return Nuki::TimeZoneId::Africa_Lagos; + } + else if(strcmp(str, "Africa/Maputo") == 0) + { + return Nuki::TimeZoneId::Africa_Maputo; + } + else if(strcmp(str, "Africa/Nairobi") == 0) + { + return Nuki::TimeZoneId::Africa_Nairobi; + } + else if(strcmp(str, "America/Anchorage") == 0) + { + return Nuki::TimeZoneId::America_Anchorage; + } + else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) + { + return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; + } + else if(strcmp(str, "America/Chicago") == 0) + { + return Nuki::TimeZoneId::America_Chicago; + } + else if(strcmp(str, "America/Denver") == 0) + { + return Nuki::TimeZoneId::America_Denver; + } + else if(strcmp(str, "America/Halifax") == 0) + { + return Nuki::TimeZoneId::America_Halifax; + } + else if(strcmp(str, "America/Los_Angeles") == 0) + { + return Nuki::TimeZoneId::America_Los_Angeles; + } + else if(strcmp(str, "America/Manaus") == 0) + { + return Nuki::TimeZoneId::America_Manaus; + } + else if(strcmp(str, "America/Mexico_City") == 0) + { + return Nuki::TimeZoneId::America_Mexico_City; + } + else if(strcmp(str, "America/New_York") == 0) + { + return Nuki::TimeZoneId::America_New_York; + } + else if(strcmp(str, "America/Phoenix") == 0) + { + return Nuki::TimeZoneId::America_Phoenix; + } + else if(strcmp(str, "America/Regina") == 0) + { + return Nuki::TimeZoneId::America_Regina; + } + else if(strcmp(str, "America/Santiago") == 0) + { + return Nuki::TimeZoneId::America_Santiago; + } + else if(strcmp(str, "America/Sao_Paulo") == 0) + { + return Nuki::TimeZoneId::America_Sao_Paulo; + } + else if(strcmp(str, "America/St_Johns") == 0) + { + return Nuki::TimeZoneId::America_St_Johns; + } + else if(strcmp(str, "Asia/Bangkok") == 0) + { + return Nuki::TimeZoneId::Asia_Bangkok; + } + else if(strcmp(str, "Asia/Dubai") == 0) + { + return Nuki::TimeZoneId::Asia_Dubai; + } + else if(strcmp(str, "Asia/Hong_Kong") == 0) + { + return Nuki::TimeZoneId::Asia_Hong_Kong; + } + else if(strcmp(str, "Asia/Jerusalem") == 0) + { + return Nuki::TimeZoneId::Asia_Jerusalem; + } + else if(strcmp(str, "Asia/Karachi") == 0) + { + return Nuki::TimeZoneId::Asia_Karachi; + } + else if(strcmp(str, "Asia/Kathmandu") == 0) + { + return Nuki::TimeZoneId::Asia_Kathmandu; + } + else if(strcmp(str, "Asia/Kolkata") == 0) + { + return Nuki::TimeZoneId::Asia_Kolkata; + } + else if(strcmp(str, "Asia/Riyadh") == 0) + { + return Nuki::TimeZoneId::Asia_Riyadh; + } + else if(strcmp(str, "Asia/Seoul") == 0) + { + return Nuki::TimeZoneId::Asia_Seoul; + } + else if(strcmp(str, "Asia/Shanghai") == 0) + { + return Nuki::TimeZoneId::Asia_Shanghai; + } + else if(strcmp(str, "Asia/Tehran") == 0) + { + return Nuki::TimeZoneId::Asia_Tehran; + } + else if(strcmp(str, "Asia/Tokyo") == 0) + { + return Nuki::TimeZoneId::Asia_Tokyo; + } + else if(strcmp(str, "Asia/Yangon") == 0) + { + return Nuki::TimeZoneId::Asia_Yangon; + } + else if(strcmp(str, "Australia/Adelaide") == 0) + { + return Nuki::TimeZoneId::Australia_Adelaide; + } + else if(strcmp(str, "Australia/Brisbane") == 0) + { + return Nuki::TimeZoneId::Australia_Brisbane; + } + else if(strcmp(str, "Australia/Darwin") == 0) + { + return Nuki::TimeZoneId::Australia_Darwin; + } + else if(strcmp(str, "Australia/Hobart") == 0) + { + return Nuki::TimeZoneId::Australia_Hobart; + } + else if(strcmp(str, "Australia/Perth") == 0) + { + return Nuki::TimeZoneId::Australia_Perth; + } + else if(strcmp(str, "Australia/Sydney") == 0) + { + return Nuki::TimeZoneId::Australia_Sydney; + } + else if(strcmp(str, "Europe/Berlin") == 0) + { + return Nuki::TimeZoneId::Europe_Berlin; + } + else if(strcmp(str, "Europe/Helsinki") == 0) + { + return Nuki::TimeZoneId::Europe_Helsinki; + } + else if(strcmp(str, "Europe/Istanbul") == 0) + { + return Nuki::TimeZoneId::Europe_Istanbul; + } + else if(strcmp(str, "Europe/London") == 0) + { + return Nuki::TimeZoneId::Europe_London; + } + else if(strcmp(str, "Europe/Moscow") == 0) + { + return Nuki::TimeZoneId::Europe_Moscow; + } + else if(strcmp(str, "Pacific/Auckland") == 0) + { + return Nuki::TimeZoneId::Pacific_Auckland; + } + else if(strcmp(str, "Pacific/Guam") == 0) + { + return Nuki::TimeZoneId::Pacific_Guam; + } + else if(strcmp(str, "Pacific/Honolulu") == 0) + { + return Nuki::TimeZoneId::Pacific_Honolulu; + } + else if(strcmp(str, "Pacific/Pago_Pago") == 0) + { + return Nuki::TimeZoneId::Pacific_Pago_Pago; + } + else if(strcmp(str, "None") == 0) + { + return Nuki::TimeZoneId::None; + } return (Nuki::TimeZoneId)0xff; } uint8_t NukiWrapper::fobActionToInt(const char *str) { - if(strcmp(str, "No Action") == 0) return 0; - else if(strcmp(str, "Unlock") == 0) return 1; - else if(strcmp(str, "Lock") == 0) return 2; - else if(strcmp(str, "Lock n Go") == 0) return 3; - else if(strcmp(str, "Intelligent") == 0) return 4; + if(strcmp(str, "No Action") == 0) + { + return 0; + } + else if(strcmp(str, "Unlock") == 0) + { + return 1; + } + else if(strcmp(str, "Lock") == 0) + { + return 2; + } + else if(strcmp(str, "Lock n Go") == 0) + { + return 3; + } + else if(strcmp(str, "Intelligent") == 0) + { + return 4; + } return 99; } NukiLock::ButtonPressAction NukiWrapper::buttonPressActionToEnum(const char* str) { - if(strcmp(str, "No Action") == 0) return NukiLock::ButtonPressAction::NoAction; - else if(strcmp(str, "Intelligent") == 0) return NukiLock::ButtonPressAction::Intelligent; - else if(strcmp(str, "Unlock") == 0) return NukiLock::ButtonPressAction::Unlock; - else if(strcmp(str, "Lock") == 0) return NukiLock::ButtonPressAction::Lock; - else if(strcmp(str, "Unlatch") == 0) return NukiLock::ButtonPressAction::Unlatch; - else if(strcmp(str, "Lock n Go") == 0) return NukiLock::ButtonPressAction::LockNgo; - else if(strcmp(str, "Show Status") == 0) return NukiLock::ButtonPressAction::ShowStatus; + if(strcmp(str, "No Action") == 0) + { + return NukiLock::ButtonPressAction::NoAction; + } + else if(strcmp(str, "Intelligent") == 0) + { + return NukiLock::ButtonPressAction::Intelligent; + } + else if(strcmp(str, "Unlock") == 0) + { + return NukiLock::ButtonPressAction::Unlock; + } + else if(strcmp(str, "Lock") == 0) + { + return NukiLock::ButtonPressAction::Lock; + } + else if(strcmp(str, "Unlatch") == 0) + { + return NukiLock::ButtonPressAction::Unlatch; + } + else if(strcmp(str, "Lock n Go") == 0) + { + return NukiLock::ButtonPressAction::LockNgo; + } + else if(strcmp(str, "Show Status") == 0) + { + return NukiLock::ButtonPressAction::ShowStatus; + } return (NukiLock::ButtonPressAction)0xff; } Nuki::BatteryType NukiWrapper::batteryTypeToEnum(const char* str) { - if(strcmp(str, "Alkali") == 0) return Nuki::BatteryType::Alkali; - else if(strcmp(str, "Accumulators") == 0) return Nuki::BatteryType::Accumulators; - else if(strcmp(str, "Lithium") == 0) return Nuki::BatteryType::Lithium; + if(strcmp(str, "Alkali") == 0) + { + return Nuki::BatteryType::Alkali; + } + else if(strcmp(str, "Accumulators") == 0) + { + return Nuki::BatteryType::Accumulators; + } + else if(strcmp(str, "Lithium") == 0) + { + return Nuki::BatteryType::Lithium; + } return (Nuki::BatteryType)0xff; } @@ -1153,10 +1510,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) { if(strlen(jsonchar) <= 32) { - if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setName(std::string(jsonchar)); + if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setName(std::string(jsonchar)); + } + } + else + { + jsonResult[basicKeys[i]] = "valueTooLong"; } - else jsonResult[basicKeys[i]] = "valueTooLong"; } else if(strcmp(basicKeys[i], "latitude") == 0) { @@ -1164,10 +1530,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.latitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setLatitude(keyvalue); + if(_nukiConfig.latitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLatitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "longitude") == 0) { @@ -1175,10 +1550,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.longitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setLongitude(keyvalue); + if(_nukiConfig.longitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLongitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "autoUnlatch") == 0) { @@ -1186,10 +1570,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.autoUnlatch == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoUnlatch((keyvalue > 0)); + if(_nukiConfig.autoUnlatch == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoUnlatch((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "pairingEnabled") == 0) { @@ -1197,10 +1590,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.pairingEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enablePairing((keyvalue > 0)); + if(_nukiConfig.pairingEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enablePairing((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "buttonEnabled") == 0) { @@ -1208,10 +1610,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.buttonEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableButton((keyvalue > 0)); + if(_nukiConfig.buttonEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableButton((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "ledEnabled") == 0) { @@ -1219,10 +1630,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.ledEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableLedFlash((keyvalue > 0)); + if(_nukiConfig.ledEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableLedFlash((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "ledBrightness") == 0) { @@ -1230,10 +1650,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 5) { - if(_nukiConfig.ledBrightness == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setLedBrightness(keyvalue); + if(_nukiConfig.ledBrightness == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLedBrightness(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZoneOffset") == 0) { @@ -1241,10 +1670,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 60) { - if(_nukiConfig.timeZoneOffset == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setTimeZoneOffset(keyvalue); + if(_nukiConfig.timeZoneOffset == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setTimeZoneOffset(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "dstMode") == 0) { @@ -1252,10 +1690,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.dstMode == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableDst((keyvalue > 0)); + if(_nukiConfig.dstMode == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableDst((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction1") == 0) { @@ -1263,10 +1710,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(fobAct1 != 99) { - if(_nukiConfig.fobAction1 == fobAct1) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setFobAction(1, fobAct1); + if(_nukiConfig.fobAction1 == fobAct1) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setFobAction(1, fobAct1); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction2") == 0) { @@ -1274,10 +1730,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(fobAct2 != 99) { - if(_nukiConfig.fobAction2 == fobAct2) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setFobAction(2, fobAct2); + if(_nukiConfig.fobAction2 == fobAct2) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setFobAction(2, fobAct2); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction3") == 0) { @@ -1285,10 +1750,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(fobAct3 != 99) { - if(_nukiConfig.fobAction3 == fobAct3) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setFobAction(3, fobAct3); + if(_nukiConfig.fobAction3 == fobAct3) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setFobAction(3, fobAct3); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "singleLock") == 0) { @@ -1296,10 +1770,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.singleLock == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableSingleLock((keyvalue > 0)); + if(_nukiConfig.singleLock == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableSingleLock((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "advertisingMode") == 0) { @@ -1307,10 +1790,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)advmode != 0xff) { - if(_nukiConfig.advertisingMode == advmode) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setAdvertisingMode(advmode); + if(_nukiConfig.advertisingMode == advmode) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setAdvertisingMode(advmode); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZone") == 0) { @@ -1318,27 +1810,47 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)tzid != 0xff) { - if(_nukiConfig.timeZoneId == tzid) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setTimeZoneId(tzid); + if(_nukiConfig.timeZoneId == tzid) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setTimeZoneId(tzid); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + if(cmdResult != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) basicUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + basicUpdated = true; + } - if(!jsonResult[basicKeys[i]]) { + if(!jsonResult[basicKeys[i]]) + { char resultStr[15] = {0}; NukiLock::cmdResultToString(cmdResult, resultStr); jsonResult[basicKeys[i]] = resultStr; } } - else jsonResult[basicKeys[i]] = "accessDenied"; + else + { + jsonResult[basicKeys[i]] = "accessDenied"; + } } } @@ -1367,10 +1879,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -90 && keyvalue <= 180) { - if(_nukiAdvancedConfig.unlockedPositionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setUnlockedPositionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.unlockedPositionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setUnlockedPositionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "lockedPositionOffsetDegrees") == 0) { @@ -1378,10 +1899,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -180 && keyvalue <= 90) { - if(_nukiAdvancedConfig.lockedPositionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setLockedPositionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.lockedPositionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLockedPositionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "singleLockedPositionOffsetDegrees") == 0) { @@ -1389,10 +1919,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -180 && keyvalue <= 180) { - if(_nukiAdvancedConfig.singleLockedPositionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setSingleLockedPositionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.singleLockedPositionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setSingleLockedPositionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "unlockedToLockedTransitionOffsetDegrees") == 0) { @@ -1400,10 +1939,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -180 && keyvalue <= 180) { - if(_nukiAdvancedConfig.unlockedToLockedTransitionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setUnlockedToLockedTransitionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.unlockedToLockedTransitionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setUnlockedToLockedTransitionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "lockNgoTimeout") == 0) { @@ -1411,10 +1959,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 5 && keyvalue <= 60) { - if(_nukiAdvancedConfig.lockNgoTimeout == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setLockNgoTimeout(keyvalue); + if(_nukiAdvancedConfig.lockNgoTimeout == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLockNgoTimeout(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "singleButtonPressAction") == 0) { @@ -1422,10 +1979,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)sbpa != 0xff) { - if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setSingleButtonPressAction(sbpa); + if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setSingleButtonPressAction(sbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doubleButtonPressAction") == 0) { @@ -1433,10 +1999,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)dbpa != 0xff) { - if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setDoubleButtonPressAction(dbpa); + if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setDoubleButtonPressAction(dbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "detachedCylinder") == 0) { @@ -1444,10 +2019,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.detachedCylinder == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableDetachedCylinder((keyvalue > 0)); + if(_nukiAdvancedConfig.detachedCylinder == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableDetachedCylinder((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "batteryType") == 0) { @@ -1455,10 +2039,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)battype != 0xff) { - if(_nukiAdvancedConfig.batteryType == battype) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setBatteryType(battype); + if(_nukiAdvancedConfig.batteryType == battype) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setBatteryType(battype); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "automaticBatteryTypeDetection") == 0) { @@ -1466,10 +2059,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoBatteryTypeDetection((keyvalue > 0)); + if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoBatteryTypeDetection((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "unlatchDuration") == 0) { @@ -1477,10 +2079,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 1 && keyvalue <= 30) { - if(_nukiAdvancedConfig.unlatchDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setUnlatchDuration(keyvalue); + if(_nukiAdvancedConfig.unlatchDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setUnlatchDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoLockTimeOut") == 0) { @@ -1488,10 +2099,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 30 && keyvalue <= 1800) { - if(_nukiAdvancedConfig.autoLockTimeOut == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setAutoLockTimeOut(keyvalue); + if(_nukiAdvancedConfig.autoLockTimeOut == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setAutoLockTimeOut(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoUnLockDisabled") == 0) { @@ -1499,10 +2119,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.autoUnLockDisabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.disableAutoUnlock((keyvalue > 0)); + if(_nukiAdvancedConfig.autoUnLockDisabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.disableAutoUnlock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeEnabled") == 0) { @@ -1510,10 +2139,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableNightMode((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableNightMode((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeStartTime") == 0) { @@ -1523,10 +2161,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) keyvalue[1] = (uint8_t)keystr.substring(3, 5).toInt(); if(keyvalue[0] >= 0 && keyvalue[0] <= 23 && keyvalue[1] >= 0 && keyvalue[1] <= 59) { - if(_nukiAdvancedConfig.nightModeStartTime == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setNightModeStartTime(keyvalue); + if(_nukiAdvancedConfig.nightModeStartTime == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setNightModeStartTime(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeEndTime") == 0) { @@ -1536,10 +2183,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) keyvalue[1] = (uint8_t)keystr.substring(3, 5).toInt(); if(keyvalue[0] >= 0 && keyvalue[0] <= 23 && keyvalue[1] >= 0 && keyvalue[1] <= 59) { - if(_nukiAdvancedConfig.nightModeEndTime == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setNightModeEndTime(keyvalue); + if(_nukiAdvancedConfig.nightModeEndTime == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setNightModeEndTime(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeAutoLockEnabled") == 0) { @@ -1547,10 +2203,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeAutoLockEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableNightModeAutoLock((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeAutoLockEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableNightModeAutoLock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeAutoUnlockDisabled") == 0) { @@ -1558,10 +2223,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeAutoUnlockDisabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.disableNightModeAutoUnlock((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeAutoUnlockDisabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.disableNightModeAutoUnlock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeImmediateLockOnStart") == 0) { @@ -1569,10 +2243,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeImmediateLockOnStart == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableNightModeImmediateLockOnStart((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeImmediateLockOnStart == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableNightModeImmediateLockOnStart((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoLockEnabled") == 0) { @@ -1580,10 +2263,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.autoLockEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoLock((keyvalue > 0)); + if(_nukiAdvancedConfig.autoLockEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoLock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "immediateAutoLockEnabled") == 0) { @@ -1591,10 +2283,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.immediateAutoLockEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableImmediateAutoLock((keyvalue > 0)); + if(_nukiAdvancedConfig.immediateAutoLockEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableImmediateAutoLock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoUpdateEnabled") == 0) { @@ -1602,34 +2303,60 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.autoUpdateEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoUpdate((keyvalue > 0)); + if(_nukiAdvancedConfig.autoUpdateEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoUpdate((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + if(cmdResult != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) advancedUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + advancedUpdated = true; + } - if(!jsonResult[advancedKeys[j]]) { + if(!jsonResult[advancedKeys[j]]) + { char resultStr[15] = {0}; NukiLock::cmdResultToString(cmdResult, resultStr); jsonResult[advancedKeys[j]] = resultStr; } } - else jsonResult[advancedKeys[j]] = "accessDenied"; + else + { + jsonResult[advancedKeys[j]] = "accessDenied"; + } } } - if(basicUpdated || advancedUpdated) jsonResult["general"] = "success"; - else jsonResult["general"] = "noChange"; + if(basicUpdated || advancedUpdated) + { + jsonResult["general"] = "success"; + } + else + { + jsonResult["general"] = "noChange"; + } - _nextConfigUpdateTs = (esp_timer_get_time() / 1000) + 300; + _nextConfigUpdateTs = espMillis() + 300; serializeJson(jsonResult, _resbuf, sizeof(_resbuf)); _network->publishConfigCommandResult(_resbuf); @@ -1667,57 +2394,75 @@ void NukiWrapper::onGpioActionReceived(const GpioAction &action, const int &pin) { switch(action) { - case GpioAction::Lock: - if(!_nukiOfficial->getOffConnected()) nukiInst->lock(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::Lock; - _network->publishOffAction(2); - } - break; - case GpioAction::Unlock: - if(!_nukiOfficial->getOffConnected()) nukiInst->unlock(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::Unlock; - _network->publishOffAction(1); - } - break; - case GpioAction::Unlatch: - if(!_nukiOfficial->getOffConnected()) nukiInst->unlatch(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::Unlatch; - _network->publishOffAction(3); - } - break; - case GpioAction::LockNgo: - if(!_nukiOfficial->getOffConnected()) nukiInst->lockngo(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::LockNgo; - _network->publishOffAction(4); - } - break; - case GpioAction::LockNgoUnlatch: - if(!_nukiOfficial->getOffConnected()) nukiInst->lockngounlatch(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::LockNgoUnlatch; - _network->publishOffAction(5); - } - break; + case GpioAction::Lock: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->lock(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs(espMillis() + 2000); + _offCommand = NukiLock::LockAction::Lock; + _network->publishOffAction(2); + } + break; + case GpioAction::Unlock: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->unlock(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs(espMillis() + 2000); + _offCommand = NukiLock::LockAction::Unlock; + _network->publishOffAction(1); + } + break; + case GpioAction::Unlatch: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->unlatch(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs(espMillis() + 2000); + _offCommand = NukiLock::LockAction::Unlatch; + _network->publishOffAction(3); + } + break; + case GpioAction::LockNgo: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->lockngo(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs(espMillis() + 2000); + _offCommand = NukiLock::LockAction::LockNgo; + _network->publishOffAction(4); + } + break; + case GpioAction::LockNgoUnlatch: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->lockngounlatch(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs(espMillis() + 2000); + _offCommand = NukiLock::LockAction::LockNgoUnlatch; + _network->publishOffAction(5); + } + break; } } void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, const String &name, const String &code, const int& enabled) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } if(!_preferences->getBool(preference_keypad_control_enabled)) { @@ -1832,10 +2577,14 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -1901,21 +2650,57 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json.containsKey("code")) code = json["code"].as(); - else code = 12; + if(json["code"].is()) + { + code = json["code"].as(); + } + else + { + code = 12; + } - if(json.containsKey("enabled")) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json.containsKey("timeLimited")) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json.containsKey("name")) name = json["name"].as(); - if(json.containsKey("allowedFrom")) allowedFrom = json["allowedFrom"].as(); - if(json.containsKey("allowedUntil")) allowedUntil = json["allowedUntil"].as(); - if(json.containsKey("allowedWeekdays")) allowedWeekdays = json["allowedWeekdays"].as(); - if(json.containsKey("allowedFromTime")) allowedFromTime = json["allowedFromTime"].as(); - if(json.containsKey("allowedUntilTime")) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -2241,6 +3026,7 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) allowedUntilTimeAr[0] = entry.allowedUntilTimeHour; allowedUntilTimeAr[1] = entry.allowedUntilTimeMin; } + } if(!foundExisting) @@ -2386,12 +3172,27 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) String lockAction; NukiLock::LockAction timeControlLockAction; - if(json.containsKey("enabled")) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json.containsKey("weekdays")) weekdays = json["weekdays"].as(); - if(json.containsKey("time")) time = json["time"].as(); - if(json.containsKey("lockAction")) lockAction = json["lockAction"].as(); + if(json["weekdays"].is()) + { + weekdays = json["weekdays"].as(); + } + if(json["time"].is()) + { + time = json["time"].as(); + } + if(json["lockAction"].is()) + { + lockAction = json["lockAction"].as(); + } if(lockAction.length() > 0) { @@ -2418,7 +3219,8 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) while(retryCount < _nrOfRetries + 1) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiLock.removeTimeControlEntry(entryId); @@ -2458,13 +3260,34 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) } } - if(weekdays.indexOf("mon") >= 0) weekdaysInt += 64; - if(weekdays.indexOf("tue") >= 0) weekdaysInt += 32; - if(weekdays.indexOf("wed") >= 0) weekdaysInt += 16; - if(weekdays.indexOf("thu") >= 0) weekdaysInt += 8; - if(weekdays.indexOf("fri") >= 0) weekdaysInt += 4; - if(weekdays.indexOf("sat") >= 0) weekdaysInt += 2; - if(weekdays.indexOf("sun") >= 0) weekdaysInt += 1; + if(weekdays.indexOf("mon") >= 0) + { + weekdaysInt += 64; + } + if(weekdays.indexOf("tue") >= 0) + { + weekdaysInt += 32; + } + if(weekdays.indexOf("wed") >= 0) + { + weekdaysInt += 16; + } + if(weekdays.indexOf("thu") >= 0) + { + weekdaysInt += 8; + } + if(weekdays.indexOf("fri") >= 0) + { + weekdaysInt += 4; + } + if(weekdays.indexOf("sat") >= 0) + { + weekdaysInt += 2; + } + if(weekdays.indexOf("sun") >= 0) + { + weekdaysInt += 1; + } if(strcmp(action, "add") == 0) { @@ -2503,18 +3326,33 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) for(const auto& entry : timeControlEntries) { - if (entryId != entry.entryId) continue; - else foundExisting = true; + if (entryId != entry.entryId) + { + continue; + } + else + { + foundExisting = true; + } - if(enabled == 2) enabled = entry.enabled; - if(weekdays.length() < 1) weekdaysInt = entry.weekdays; + if(enabled == 2) + { + enabled = entry.enabled; + } + if(weekdays.length() < 1) + { + weekdaysInt = entry.weekdays; + } if(time.length() < 1) { time = "old"; timeAr[0] = entry.timeHour; timeAr[1] = entry.timeMin; } - if(lockAction.length() < 1) timeControlLockAction = entry.lockAction; + if(lockAction.length() < 1) + { + timeControlLockAction = entry.lockAction; + } } if(!foundExisting) @@ -2554,10 +3392,14 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -2568,7 +3410,7 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) _network->publishTimeControlCommandResult(resultStr); } - _nextConfigUpdateTs = (esp_timer_get_time() / 1000) + 300; + _nextConfigUpdateTs = espMillis() + 300; } else { @@ -2622,22 +3464,58 @@ void NukiWrapper::onAuthCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json.containsKey("remoteAllowed")) remoteAllowed = json["remoteAllowed"].as(); - else remoteAllowed = 2; + if(json["remoteAllowed"].is()) + { + remoteAllowed = json["remoteAllowed"].as(); + } + else + { + remoteAllowed = 2; + } - if(json.containsKey("enabled")) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json.containsKey("timeLimited")) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json.containsKey("name")) name = json["name"].as(); - //if(json.containsKey("sharedKey")) sharedKey = json["sharedKey"].as(); - if(json.containsKey("allowedFrom")) allowedFrom = json["allowedFrom"].as(); - if(json.containsKey("allowedUntil")) allowedUntil = json["allowedUntil"].as(); - if(json.containsKey("allowedWeekdays")) allowedWeekdays = json["allowedWeekdays"].as(); - if(json.containsKey("allowedFromTime")) allowedFromTime = json["allowedFromTime"].as(); - if(json.containsKey("allowedUntilTime")) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } + //if(json["sharedKey"].is()) sharedKey = json["sharedKey"].as(); + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -2653,7 +3531,8 @@ void NukiWrapper::onAuthCommandReceived(const char *value) while(retryCount < _nrOfRetries) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiLock.deleteAuthorizationEntry(authId); @@ -2789,13 +3668,34 @@ void NukiWrapper::onAuthCommandReceived(const char *value) } } - if(allowedWeekdays.indexOf("mon") >= 0) allowedWeekdaysInt += 64; - if(allowedWeekdays.indexOf("tue") >= 0) allowedWeekdaysInt += 32; - if(allowedWeekdays.indexOf("wed") >= 0) allowedWeekdaysInt += 16; - if(allowedWeekdays.indexOf("thu") >= 0) allowedWeekdaysInt += 8; - if(allowedWeekdays.indexOf("fri") >= 0) allowedWeekdaysInt += 4; - if(allowedWeekdays.indexOf("sat") >= 0) allowedWeekdaysInt += 2; - if(allowedWeekdays.indexOf("sun") >= 0) allowedWeekdaysInt += 1; + if(allowedWeekdays.indexOf("mon") >= 0) + { + allowedWeekdaysInt += 64; + } + if(allowedWeekdays.indexOf("tue") >= 0) + { + allowedWeekdaysInt += 32; + } + if(allowedWeekdays.indexOf("wed") >= 0) + { + allowedWeekdaysInt += 16; + } + if(allowedWeekdays.indexOf("thu") >= 0) + { + allowedWeekdaysInt += 8; + } + if(allowedWeekdays.indexOf("fri") >= 0) + { + allowedWeekdaysInt += 4; + } + if(allowedWeekdays.indexOf("sat") >= 0) + { + allowedWeekdaysInt += 2; + } + if(allowedWeekdays.indexOf("sun") >= 0) + { + allowedWeekdaysInt += 1; + } } if(strcmp(action, "add") == 0) @@ -2885,17 +3785,32 @@ void NukiWrapper::onAuthCommandReceived(const char *value) for(const auto& entry : entries) { - if (authId != entry.authId) continue; - else foundExisting = true; + if (authId != entry.authId) + { + continue; + } + else + { + foundExisting = true; + } if(name.length() < 1) { memset(oldName, 0, sizeof(oldName)); memcpy(oldName, entry.name, sizeof(entry.name)); } - if(remoteAllowed == 2) remoteAllowed = entry.remoteAllowed; - if(enabled == 2) enabled = entry.enabled; - if(timeLimited == 2) timeLimited = entry.timeLimited; + if(remoteAllowed == 2) + { + remoteAllowed = entry.remoteAllowed; + } + if(enabled == 2) + { + enabled = entry.enabled; + } + if(timeLimited == 2) + { + timeLimited = entry.timeLimited; + } if(allowedFrom.length() < 1) { allowedFrom = "old"; @@ -2916,7 +3831,10 @@ void NukiWrapper::onAuthCommandReceived(const char *value) allowedUntilAr[4] = entry.allowedUntilMinute; allowedUntilAr[5] = entry.allowedUntilSecond; } - if(allowedWeekdays.length() < 1) allowedWeekdaysInt = entry.allowedWeekdays; + if(allowedWeekdays.length() < 1) + { + allowedWeekdaysInt = entry.allowedWeekdays; + } if(allowedFromTime.length() < 1) { allowedFromTime = "old"; @@ -3015,10 +3933,14 @@ void NukiWrapper::onAuthCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } updateAuth(false); @@ -3057,7 +3979,7 @@ void NukiWrapper::notify(Nuki::EventType eventType) { if(!_nukiOfficial->getOffConnected()) { - if(_nukiOfficial->getOffEnabled() && _intervalHybridLockstate > 0 && (esp_timer_get_time() / 1000) > (_intervalHybridLockstate * 1000)) + if(_nukiOfficial->getOffEnabled() && _intervalHybridLockstate > 0 && espMillis() > (_intervalHybridLockstate * 1000)) { Log->println("OffKeyTurnerStatusUpdated"); _statusUpdated = true; @@ -3068,7 +3990,7 @@ void NukiWrapper::notify(Nuki::EventType eventType) { Log->println("KeyTurnerStatusUpdated"); _statusUpdated = true; - _statusUpdatedTs = esp_timer_get_time() / 1000; + _statusUpdatedTs = espMillis(); _network->publishStatusUpdated(_statusUpdated); } } @@ -3090,12 +4012,16 @@ void NukiWrapper::readConfig() Log->print(F("Lock config result: ")); Log->println(resultStr); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; Log->println("Failed to retrieve lock config, retrying in 1s"); delay(1000); } - else break; + else + { + break; + } } } @@ -3106,7 +4032,7 @@ void NukiWrapper::readAdvancedConfig() while(retryCount < _nrOfRetries + 1) { - result = _nukiLock.requestAdvancedConfig(&_nukiAdvancedConfig); + result = _nukiLock.requestAdvancedConfig(&_nukiAdvancedConfig); _nukiAdvancedConfigValid = result == Nuki::CmdResult::Success; char resultStr[20]; @@ -3114,19 +4040,29 @@ void NukiWrapper::readAdvancedConfig() Log->print(F("Lock advanced config result: ")); Log->println(resultStr); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; Log->println("Failed to retrieve lock advanced config, retrying in 1s"); delay(1000); } - else break; + else + { + break; + } } } void NukiWrapper::setupHASS() { - if(!_nukiConfigValid) return; - if(_preferences->getUInt(preference_nuki_id_lock, 0) != _nukiConfig.nukiId) return; + if(!_nukiConfigValid) + { + return; + } + if(_preferences->getUInt(preference_nuki_id_lock, 0) != _nukiConfig.nukiId) + { + return; + } String baseTopic = _preferences->getString(preference_mqtt_lock_path); char uidString[20]; @@ -3191,15 +4127,15 @@ void NukiWrapper::updateGpioOutputs() { switch(entry.role) { - case PinRole::OutputHighLocked: - _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? HIGH : LOW); - break; - case PinRole::OutputHighUnlocked: - _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? LOW : HIGH); - break; - case PinRole::OutputHighMotorBlocked: - _gpio->setPinOutput(entry.pin, lockState == LockState::MotorBlocked ? HIGH : LOW); - break; + case PinRole::OutputHighLocked: + _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? HIGH : LOW); + break; + case PinRole::OutputHighUnlocked: + _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? LOW : HIGH); + break; + case PinRole::OutputHighMotorBlocked: + _gpio->setPinOutput(entry.pin, lockState == LockState::MotorBlocked ? HIGH : LOW); + break; } } } diff --git a/src/NukiWrapper.h b/src/NukiWrapper.h index 0cf886b..28443d2 100644 --- a/src/NukiWrapper.h +++ b/src/NukiWrapper.h @@ -9,6 +9,7 @@ #include "LockActionResult.h" #include "NukiDeviceId.h" #include "NukiOfficial.h" +#include "EspMillis.h" class NukiWrapper : public Nuki::SmartlockEventHandler { diff --git a/src/PreferencesKeys.h b/src/PreferencesKeys.h index 7edc997..81d7bb6 100644 --- a/src/PreferencesKeys.h +++ b/src/PreferencesKeys.h @@ -52,9 +52,10 @@ #define preference_update_from_mqtt (char*)"updMqtt" #define preference_disable_non_json (char*)"disnonjson" #define preference_official_hybrid_enabled (char*)"offHybrid" +#define preference_wifi_ssid (char*)"wifiSSID" +#define preference_wifi_pass (char*)"wifiPass" // CHANGE DOES NOT REQUIRE REBOOT TO TAKE EFFECT -#define preference_find_best_rssi (char*)"nwbestrssi" #define preference_ntw_reconfigure (char*)"ntwRECONF" #define preference_auth_max_entries (char*)"authmaxentry" #define preference_auth_info_enabled (char*)"authInfoEna" @@ -88,14 +89,12 @@ #define preference_command_retry_delay (char*)"rtryDelay" #define preference_query_interval_hybrid_lockstate (char*)"hybridTimer" #define preference_mqtt_hass_cu_url (char*)"hassConfigUrl" -#define preference_network_wifi_fallback_disabled (char*)"nwwififb" #define preference_check_updates (char*)"checkupdates" #define preference_opener_continuous_mode (char*)"openercont" #define preference_rssi_publish_interval (char*)"rssipb" #define preference_network_timeout (char*)"nettmout" #define preference_restart_on_disconnect (char*)"restdisc" #define preference_publish_debug_info (char*)"pubdbg" -#define preference_recon_netw_on_mqtt_discon (char*)"recNtwMqttDis" #define preference_official_hybrid_actions (char*)"hybridAct" #define preference_official_hybrid_retry (char*)"hybridRtry" #define preference_keypad_check_code_enabled (char*)"kpChkEna" @@ -119,12 +118,14 @@ #define preference_lock_max_timecontrol_entry_count (char*)"maxtc" #define preference_opener_max_timecontrol_entry_count (char*)"opmaxtc" #define preference_latest_version (char*)"latest" +#define preference_wifi_converted (char*)"wifiConv" //OBSOLETE #define preference_access_level (char*)"accLvl" #define preference_gpio_locking_enabled (char*)"gpiolck" #define preference_network_hardware_gpio (char*)"nwhwdt" #define preference_presence_detection_timeout (char*)"prdtimeout" +#define preference_network_wifi_fallback_disabled (char*)"nwwififb" inline bool initPreferences(Preferences* preferences) { @@ -249,9 +250,15 @@ inline bool initPreferences(Preferences* preferences) if (configVer < 901) { #if defined(CONFIG_IDF_TARGET_ESP32S3) - if (preferences->getInt(preference_network_hardware) == 3) preferences->putInt(preference_network_hardware, 10); + if (preferences->getInt(preference_network_hardware) == 3) + { + preferences->putInt(preference_network_hardware, 10); + } #endif - if (preferences->getInt(preference_network_hardware) == 2) preferences->putInt(preference_network_hardware, 3); + if (preferences->getInt(preference_network_hardware) == 2) + { + preferences->putInt(preference_network_hardware, 3); + } } preferences->putInt(preference_config_version, atof(NUKI_HUB_VERSION) * 100); @@ -272,8 +279,8 @@ private: 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_ip_subnet, preference_ip_gateway, preference_ip_dns_server, preference_network_hardware, + preference_rssi_publish_interval, preference_hostname, 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, @@ -281,26 +288,26 @@ private: preference_cred_password, preference_disable_non_json, preference_publish_authdata, preference_publish_debug_info, preference_official_hybrid_enabled, preference_query_interval_hybrid_lockstate, preference_official_hybrid_actions, preference_official_hybrid_retry, 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, preference_ble_tx_power, preference_recon_netw_on_mqtt_discon, preference_webserial_enabled, + preference_update_from_mqtt, preference_show_secrets, preference_ble_tx_power, preference_webserial_enabled, preference_network_custom_mdc, preference_network_custom_clk, preference_network_custom_phy, preference_network_custom_addr, preference_network_custom_irq, preference_network_custom_rst, preference_network_custom_cs, preference_network_custom_sck, preference_network_custom_miso, preference_network_custom_mosi, preference_network_custom_pwr, preference_network_custom_mdio, preference_ntw_reconfigure, preference_lock_max_auth_entry_count, preference_opener_max_auth_entry_count, - preference_auth_control_enabled, preference_auth_topic_per_entry, preference_auth_info_enabled, preference_auth_max_entries, preference_keypad_check_code_enabled + preference_auth_control_enabled, preference_auth_topic_per_entry, preference_auth_info_enabled, preference_auth_max_entries, preference_keypad_check_code_enabled, preference_wifi_ssid, preference_wifi_pass }; 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_nuki_id_lock, preference_nuki_id_opener, + preference_nuki_id_lock, preference_nuki_id_opener, preference_wifi_pass }; 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_timecontrol_topic_per_entry, preference_keypad_topic_per_entry, preference_enable_bootloop_reset, preference_webserver_enabled, 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_publish_debug_info, preference_network_wifi_fallback_disabled, preference_official_hybrid_enabled, + preference_publish_authdata, preference_publish_debug_info, preference_official_hybrid_enabled, preference_official_hybrid_actions, preference_official_hybrid_retry, preference_conf_info_enabled, preference_disable_non_json, preference_update_from_mqtt, - preference_auth_control_enabled, preference_auth_topic_per_entry, preference_auth_info_enabled, preference_recon_netw_on_mqtt_discon, preference_webserial_enabled, + preference_auth_control_enabled, preference_auth_topic_per_entry, preference_auth_info_enabled, preference_webserial_enabled, preference_ntw_reconfigure, preference_keypad_check_code_enabled }; std::vector _bytePrefs = diff --git a/src/RestartReason.h b/src/RestartReason.h index de62376..9d7857d 100644 --- a/src/RestartReason.h +++ b/src/RestartReason.h @@ -33,12 +33,9 @@ enum class RestartReason extern int restartReason; extern uint64_t restartReasonValidDetect; extern bool rebuildGpioRequested; - extern RestartReason currentRestartReason; - extern bool restartReason_isValid; - inline static void restartEsp(RestartReason reason) { if(reason == RestartReason::GpioConfigurationUpdated) diff --git a/src/WebCfgServer.cpp b/src/WebCfgServer.cpp index ea5d492..5c22910 100644 --- a/src/WebCfgServer.cpp +++ b/src/WebCfgServer.cpp @@ -9,6 +9,7 @@ #endif #ifndef CONFIG_IDF_TARGET_ESP32H2 #include +#include #endif #include @@ -20,22 +21,22 @@ extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_ #include #include "ArduinoJson.h" -WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, AsyncWebServer* asyncServer) -: _nuki(nuki), - _nukiOpener(nukiOpener), - _network(network), - _gpio(gpio), - _preferences(preferences), - _allowRestartToPortal(allowRestartToPortal), - _partitionType(partitionType), - _asyncServer(asyncServer) +WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, PsychicHttpServer* psychicServer) + : _nuki(nuki), + _nukiOpener(nukiOpener), + _network(network), + _gpio(gpio), + _preferences(preferences), + _allowRestartToPortal(allowRestartToPortal), + _partitionType(partitionType), + _psychicServer(psychicServer) #else -WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, AsyncWebServer* asyncServer) -: _network(network), - _preferences(preferences), - _allowRestartToPortal(allowRestartToPortal), - _partitionType(partitionType), - _asyncServer(asyncServer) +WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, PsychicHttpServer* psychicServer) + : _network(network), + _preferences(preferences), + _allowRestartToPortal(allowRestartToPortal), + _partitionType(partitionType), + _psychicServer(psychicServer) #endif { _hostname = _preferences->getString(preference_hostname, ""); @@ -57,7 +58,7 @@ WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool _confirmCode = generateConfirmCode(); - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER _pinsConfigured = true; if(_nuki != nullptr && !_nuki->isPinSet()) @@ -70,390 +71,891 @@ WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool } _brokerConfigured = _preferences->getString(preference_mqtt_broker).length() > 0 && _preferences->getInt(preference_mqtt_broker_port) > 0; - #endif +#endif } void WebCfgServer::initialize() { - _response.reserve(8192); - - _asyncServer->on("/", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - #ifndef NUKI_HUB_UPDATER - buildHtml(request); - #else - buildOtaHtml(request); - #endif - }); - _asyncServer->on("/style.css", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - sendCss(request); - }); - _asyncServer->on("/favicon.ico", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - sendFavicon(request); - }); - #ifndef NUKI_HUB_UPDATER - _asyncServer->on("/import", HTTP_POST, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - String message = ""; - bool restart = processImport(request, message); - buildConfirmHtml(request, message, 3, true); - }); - _asyncServer->on("/export", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - sendSettings(request); - }); - _asyncServer->on("/impexpcfg", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildImportExportHtml(request); - }); - _asyncServer->on("/status", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildStatusHtml(request); - }); - _asyncServer->on("/acclvl", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildAccLvlHtml(request); - }); - _asyncServer->on("/custntw", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildCustomNetworkConfigHtml(request); - }); - _asyncServer->on("/advanced", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildAdvancedConfigHtml(request); - }); - _asyncServer->on("/cred", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildCredHtml(request); - }); - _asyncServer->on("/mqttconfig", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildMqttConfigHtml(request); - }); - _asyncServer->on("/nukicfg", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildNukiConfigHtml(request); - }); - _asyncServer->on("/gpiocfg", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildGpioConfigHtml(request); - }); - #ifndef CONFIG_IDF_TARGET_ESP32H2 - _asyncServer->on("/wifi", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildConfigureWifiHtml(request); - }); - _asyncServer->on("/wifimanager", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - if(_allowRestartToPortal) + _psychicServer->on("/", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + if(!_network->isApOpen()) { - buildConfirmHtml(request, "Restarting. Connect to ESP access point to reconfigure Wi-Fi.", 0); - waitAndProcess(false, 1000); - _network->reconfigureDevice(); +#ifndef NUKI_HUB_UPDATER + return buildHtml(request); +#else + return buildOtaHtml(request); +#endif } +#ifndef CONFIG_IDF_TARGET_ESP32H2 + else + { + return buildWifiConnectHtml(request); + } +#endif }); - #endif - _asyncServer->on("/unpairlock", HTTP_POST, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - processUnpair(request, false); + + _psychicServer->on("/style.css", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return sendCss(request); }); - _asyncServer->on("/unpairopener", HTTP_POST, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - processUnpair(request, true); + _psychicServer->on("/favicon.ico", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return sendFavicon(request); }); - _asyncServer->on("/factoryreset", HTTP_POST, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - processFactoryReset(request); - }); - _asyncServer->on("/info", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildInfoHtml(request); - }); - _asyncServer->on("/debugon", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - _preferences->putBool(preference_publish_debug_info, true); - buildConfirmHtml(request, "Debug On", 3, true); - }); - _asyncServer->on("/debugoff", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - _preferences->putBool(preference_publish_debug_info, false); - buildConfirmHtml(request, "Debug Off", 3, true); - }); - _asyncServer->on("/savecfg", HTTP_POST, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - String message = ""; - bool restart = processArgs(request, message); - buildConfirmHtml(request, message, 3, true); - }); - _asyncServer->on("/savegpiocfg", HTTP_POST, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - processGpioArgs(request); - buildConfirmHtml(request, "Saving GPIO configuration. Restarting.", 3, true); - Log->println(F("Restarting")); - waitAndProcess(true, 1000); - restartEsp(RestartReason::GpioConfigurationUpdated); - }); - #endif - _asyncServer->on("/ota", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildOtaHtml(request); - }); - _asyncServer->on("/otadebug", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildOtaHtml(request, true); - }); - _asyncServer->on("/reboottoota", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildConfirmHtml(request, "Rebooting to other partition", 2, true); - waitAndProcess(true, 1000); - esp_ota_set_boot_partition(esp_ota_get_next_update_partition(NULL)); - restartEsp(RestartReason::OTAReboot); - }); - _asyncServer->on("/reboot", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - buildConfirmHtml(request, "Rebooting", 2, true); + _psychicServer->on("/reboot", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + + String value = ""; + if(request->hasParam("CONFIRMTOKEN")) + { + const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); + if(p->value() != "") + { + value = p->value(); + } + } + else + { + return buildConfirmHtml(request, "No confirm code set.", 3, true); + } + + if(value != _confirmCode) + { + return request->redirect("/"); + } + esp_err_t res = buildConfirmHtml(request, "Rebooting...", 2, true); waitAndProcess(true, 1000); restartEsp(RestartReason::RequestedViaWebServer); + return res; }); - _asyncServer->on("/autoupdate", HTTP_GET, [&](AsyncWebServerRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - #ifndef NUKI_HUB_UPDATER - processUpdate(request); - #else - request->redirect("/"); - #endif - }); - _asyncServer->on("/uploadota", HTTP_POST, - [&](AsyncWebServerRequest *request) {}, - [&](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) - { - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(); - handleOtaUpload(request, filename, index, data, len, final); - } - ); - //Update.onProgress(printProgress); + + if(_network->isApOpen()) + { +#ifndef CONFIG_IDF_TARGET_ESP32H2 + _psychicServer->on("/ssidlist", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildSSIDListHtml(request); + }); + _psychicServer->on("/savewifi", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + String message = ""; + bool connected = processWiFi(request, message); + esp_err_t res = buildConfirmHtml(request, message, 10, true); + + if(connected) + { + waitAndProcess(true, 3000); + restartEsp(RestartReason::ReconfigureWifi); + //abort(); + } + return res; + }); +#endif + } + else + { +#ifndef NUKI_HUB_UPDATER + _psychicServer->on("/import", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + String message = ""; + bool restart = processImport(request, message); + return buildConfirmHtml(request, message, 3, true); + }); + _psychicServer->on("/export", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return sendSettings(request); + }); + _psychicServer->on("/impexpcfg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildImportExportHtml(request); + }); + _psychicServer->on("/status", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildStatusHtml(request); + }); + _psychicServer->on("/acclvl", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildAccLvlHtml(request); + }); + _psychicServer->on("/custntw", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildCustomNetworkConfigHtml(request); + }); + _psychicServer->on("/advanced", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildAdvancedConfigHtml(request); + }); + _psychicServer->on("/cred", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildCredHtml(request); + }); + _psychicServer->on("/mqttconfig", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildMqttConfigHtml(request); + }); + _psychicServer->on("/nukicfg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildNukiConfigHtml(request); + }); + _psychicServer->on("/gpiocfg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildGpioConfigHtml(request); + }); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + _psychicServer->on("/wifi", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildConfigureWifiHtml(request); + }); + _psychicServer->on("/wifimanager", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + if(_allowRestartToPortal) + { + esp_err_t res = buildConfirmHtml(request, "Restarting. Connect to ESP access point (\"NukiHub\" with password \"NukiHubESP32\") to reconfigure Wi-Fi.", 0); + waitAndProcess(false, 1000); + _network->reconfigureDevice(); + return res; + } + return(ESP_OK); + }); +#endif + _psychicServer->on("/unpairlock", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return processUnpair(request, false); + }); + _psychicServer->on("/unpairopener", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return processUnpair(request, true); + }); + _psychicServer->on("/factoryreset", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return processFactoryReset(request); + }); + _psychicServer->on("/infopg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildInfoHtml(request); + }); + _psychicServer->on("/debugon", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + _preferences->putBool(preference_publish_debug_info, true); + return buildConfirmHtml(request, "Debug On", 3, true); + }); + _psychicServer->on("/debugoff", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + _preferences->putBool(preference_publish_debug_info, false); + return buildConfirmHtml(request, "Debug Off", 3, true); + }); + _psychicServer->on("/savecfg", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + String message = ""; + bool restart = processArgs(request, message); + return buildConfirmHtml(request, message, 3, true); + }); + _psychicServer->on("/savegpiocfg", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + processGpioArgs(request); + esp_err_t res = buildConfirmHtml(request, "Saving GPIO configuration. Restarting.", 3, true); + Log->println(F("Restarting")); + waitAndProcess(true, 1000); + restartEsp(RestartReason::GpioConfigurationUpdated); + return res; + }); +#endif + _psychicServer->on("/ota", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildOtaHtml(request); + }); + _psychicServer->on("/otadebug", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return buildOtaHtml(request, true); + }); + _psychicServer->on("/reboottoota", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + String value = ""; + if(request->hasParam("CONFIRMTOKEN")) + { + const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); + if(p->value() != "") + { + value = p->value(); + } + } + else + { + return buildConfirmHtml(request, "No confirm code set.", 3, true); + } + + if(value != _confirmCode) + { + return request->redirect("/"); + } + esp_err_t res = buildConfirmHtml(request, "Rebooting to other partition...", 2, true); + waitAndProcess(true, 1000); + esp_ota_set_boot_partition(esp_ota_get_next_update_partition(NULL)); + restartEsp(RestartReason::OTAReboot); + return res; + }); + _psychicServer->on("/autoupdate", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } +#ifndef NUKI_HUB_UPDATER + return processUpdate(request); +#else + return request->redirect("/"); +#endif + }); + + PsychicUploadHandler *updateHandler = new PsychicUploadHandler(); + updateHandler->onUpload([&](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return handleOtaUpload(request, filename, index, data, len, final); + } + ); + + updateHandler->onRequest([&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + + String result; + if (!Update.hasError()) + { + Log->print("Update code or data OK Update.errorString() "); + Log->println(Update.errorString()); + result = "Update OK."; + esp_err_t res = request->reply(200,"text/html",result.c_str()); + restartEsp(RestartReason::OTACompleted); + return res; + } + else + { + result = " Update.errorString() " + String(Update.errorString()); + Log->print("ERROR : error "); + Log->println(result.c_str()); + esp_err_t res = request->reply(500, "text/html", result.c_str()); + restartEsp(RestartReason::OTAAborted); + return res; + } + }); + + _psychicServer->on("/uploadota", HTTP_POST, updateHandler); + //Update.onProgress(printProgress); + } } -void WebCfgServer::sendResponse(AsyncWebServerRequest *request) +void WebCfgServer::printCheckBox(PsychicStreamResponse *response, const char *token, const char *description, const bool value, const char *htmlClass) { - AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", - [&](uint8_t *buffer, size_t maxlen, size_t index) -> size_t { - size_t len = min(maxlen, _response.length() - index); - memcpy(buffer, _response.c_str() + index, len); - return len; - }); + response->print(""); + response->print(description); + response->print(""); - request->send(response); + response->print("print(token); + response->print("\" value=\"0\""); + response->print("/>"); + + response->print("print(token); + + response->print("\" class=\""); + response->print(htmlClass); + + response->print("\" value=\"1\""); + response->print(value ? " checked=\"checked\"" : ""); + response->print("/>"); } -void WebCfgServer::buildOtaHtml(AsyncWebServerRequest *request, bool debug) +#ifndef CONFIG_IDF_TARGET_ESP32H2 +esp_err_t WebCfgServer::buildSSIDListHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); + _network->scan(true, false); + createSsidList(); + + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + + for (int i = 0; i < _ssidList.size(); i++) + { + response.print("" + _ssidList[i] + String(F(" (")) + String(_rssiList[i]) + String(F(" %)")) + ""); + } + return response.endSend(); +} + +void WebCfgServer::createSsidList() +{ + int _foundNetworks = WiFi.scanComplete(); + std::vector _tmpSsidList; + std::vector _tmpRssiList; + + for (int i = 0; i < _foundNetworks; i++) + { + int rssi = constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100); + auto it1 = std::find(_ssidList.begin(), _ssidList.end(), WiFi.SSID(i)); + auto it2 = std::find(_tmpSsidList.begin(), _tmpSsidList.end(), WiFi.SSID(i)); + + if(it1 == _ssidList.end()) + { + _ssidList.push_back(WiFi.SSID(i)); + _rssiList.push_back(rssi); + _tmpSsidList.push_back(WiFi.SSID(i)); + _tmpRssiList.push_back(rssi); + } + else if (it2 == _tmpSsidList.end()) + { + _tmpSsidList.push_back(WiFi.SSID(i)); + _tmpRssiList.push_back(rssi); + int index = it1 - _ssidList.begin(); + _rssiList[index] = rssi; + } + else + { + int index = it1 - _ssidList.begin(); + int index2 = it2 - _tmpSsidList.begin(); + if (_tmpRssiList[index2] < rssi) + { + _tmpRssiList[index2] = rssi; + _rssiList[index] = rssi; + } + } + } +} + +esp_err_t WebCfgServer::buildWifiConnectHtml(PsychicRequest *request) +{ + String header = ""; + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response, header); + response.print("

Available WiFi networks

"); + response.print(""); + createSsidList(); + for (int i = 0; i < _ssidList.size(); i++) + { + response.print(""); + } + response.print("
" + _ssidList[i] + String(F(" (")) + String(_rssiList[i]) + String(F(" %)")) + "
"); + response.print("
"); + response.print("

WiFi credentials

"); + response.print(""); + printInputField(&response, "WIFISSID", "SSID", "", 32, "id=\"inputssid\"", false, true); + printInputField(&response, "WIFIPASS", "Secret key", "", 63, "id=\"inputpass\"", false, true); + response.print("
"); + response.print("

IP Address assignment

"); + response.print(""); + printCheckBox(&response, "DHCPENA", "Enable DHCP", _preferences->getBool(preference_ip_dhcp_enabled), ""); + printInputField(&response, "IPADDR", "Static IP address", _preferences->getString(preference_ip_address).c_str(), 15, ""); + printInputField(&response, "IPSUB", "Subnet", _preferences->getString(preference_ip_subnet).c_str(), 15, ""); + printInputField(&response, "IPGTW", "Default gateway", _preferences->getString(preference_ip_gateway).c_str(), 15, ""); + printInputField(&response, "DNSSRV", "DNS Server", _preferences->getString(preference_ip_dns_server).c_str(), 15, ""); + response.print("
"); + response.print("
"); + response.print("
"); + response.print("

"); + response.print(""); + return response.endSend(); +} + +bool WebCfgServer::processWiFi(PsychicRequest *request, String& message) +{ + bool res = false; + int params = request->params(); + String ssid; + String pass; + + for(int index = 0; index < params; index++) + { + const PsychicWebParameter* p = request->getParam(index); + String key = p->name(); + String value = p->value(); + + + if(index < params -1) + { + const PsychicWebParameter* next = request->getParam(index+1); + if(key == next->name()) + { + continue; + } + } + + if(key == "WIFISSID") + { + ssid = value; + } + else if(key == "WIFIPASS") + { + pass = value; + } + else if(key == "DHCPENA") + { + if(_preferences->getBool(preference_ip_dhcp_enabled, true) != (value == "1")) + { + _preferences->putBool(preference_ip_dhcp_enabled, (value == "1")); + } + } + else if(key == "IPADDR") + { + if(_preferences->getString(preference_ip_address, "") != value) + { + _preferences->putString(preference_ip_address, value); + } + } + else if(key == "IPSUB") + { + if(_preferences->getString(preference_ip_subnet, "") != value) + { + _preferences->putString(preference_ip_subnet, value); + } + } + else if(key == "IPGTW") + { + if(_preferences->getString(preference_ip_gateway, "") != value) + { + _preferences->putString(preference_ip_gateway, value); + } + } + else if(key == "DNSSRV") + { + if(_preferences->getString(preference_ip_dns_server, "") != value) + { + _preferences->putString(preference_ip_dns_server, value); + } + } + } + + ssid.trim(); + pass.trim(); + + if (ssid.length() > 0 && pass.length() > 0) + { + if (_preferences->getBool(preference_ip_dhcp_enabled, true) && _preferences->getString(preference_ip_address, "").length() <= 0) + { + const IPConfiguration* _ipConfiguration = new IPConfiguration(_preferences); + + if(!_ipConfiguration->dhcpEnabled()) + { + WiFi.config(_ipConfiguration->ipAddress(), _ipConfiguration->dnsServer(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet()); + } + } + + WiFi.begin(ssid, pass); + + int loop = 0; + while(!_network->isConnected() && loop < 150) + { + delay(100); + loop++; + } + + if (!_network->isConnected()) + { + message = "Failed to connect to the given SSID with the given secret key, credentials not saved
"; + return res; + } + else + { + if(_network->isConnected()) + { + message = "Connection successful. Rebooting Nuki Hub.
"; + _preferences->putString(preference_wifi_ssid, ssid); + _preferences->putString(preference_wifi_pass, pass); + res = true; + } + else + { + message = "Failed to connect to the given SSID, no IP received, credentials not saved
"; + return res; + } + } + } + else + { + message = "No SSID or secret key entered, credentials not saved
"; + return res; + } + + return res; +} +#endif + +esp_err_t WebCfgServer::buildOtaHtml(PsychicRequest *request, bool debug) +{ + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + + buildHtmlHeader(&response); bool errored = false; if(request->hasParam("errored")) { - const AsyncWebParameter* p = request->getParam("errored"); - if(p->value() != "") errored = true; + const PsychicWebParameter* p = request->getParam("errored"); + if(p->value() != "") + { + errored = true; + } } - if(errored) _response.concat("
Over-the-air update errored. Please check the logs for more info

"); + if(errored) + { + response.print("
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 9.00 or higher. Please check GitHub for instructions on how to update to 9.00 and the new partition scheme

"); - _response.concat(""); - return; + response.print("

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

"); + response.print(""); + return response.endSend(); } - _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("

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("
"); - - String release_type; - - if(debug) release_type = "debug"; - else release_type = "release"; - - #ifndef DEBUG_NUKIHUB - String build_type = "release"; - #else - String build_type = "debug"; - #endif - _response.concat("

"); - _response.concat("

"); - _response.concat("

"); - _response.concat("

"); - - _response.concat("Current version: "); - _response.concat(NUKI_HUB_VERSION); - _response.concat(" ("); - _response.concat(NUKI_HUB_BUILD); - _response.concat("), "); - _response.concat(NUKI_HUB_DATE); - _response.concat("
"); - - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER bool manifestSuccess = false; JsonDocument doc; - NetworkClientSecure *client = new NetworkClientSecure; - if (client) { - client->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); + NetworkClientSecure *clientOTAUpdate = new NetworkClientSecure; + if (clientOTAUpdate) + { + clientOTAUpdate->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); { - HTTPClient https; - https.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); - https.setTimeout(2500); - https.useHTTP10(true); + HTTPClient httpsOTAClient; + httpsOTAClient.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); + httpsOTAClient.setTimeout(2500); + httpsOTAClient.useHTTP10(true); - if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) { - int http_responseCode = https.GET(); + if (httpsOTAClient.begin(*clientOTAUpdate, GITHUB_OTA_MANIFEST_URL)) + { + int httpResponseCodeOTA = httpsOTAClient.GET(); - if (http_responseCode == HTTP_CODE_OK || http_responseCode == HTTP_CODE_MOVED_PERMANENTLY) + if (httpResponseCodeOTA == HTTP_CODE_OK || httpResponseCodeOTA == HTTP_CODE_MOVED_PERMANENTLY) { - DeserializationError jsonError = deserializeJson(doc, https.getStream()); - if (!jsonError) { manifestSuccess = true; } + DeserializationError jsonError = deserializeJson(doc, httpsOTAClient.getStream()); + if (!jsonError) + { + manifestSuccess = true; + } } - https.end(); + httpsOTAClient.end(); } } - delete client; + delete clientOTAUpdate; } - if(!manifestSuccess) + response.print("
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.print("

Update Nuki Hub

"); + response.print("Click on the button to reboot and automatically update Nuki Hub and the Nuki Hub updater to the latest versions from GitHub"); + response.print("
"); + + String release_type; + + if(debug) { - _response.concat("currentverlatestverdevverbetaver"); + release_type = "debug"; } else { - _response.concat("Latest release version: "); - _response.concat(doc["release"]["fullversion"].as()); - _response.concat(" ("); - _response.concat(doc["release"]["build"].as()); - _response.concat("), "); - _response.concat(doc["release"]["time"].as()); - _response.concat("
"); - _response.concat("Latest beta version: "); + release_type = "release"; + } + +#ifndef DEBUG_NUKIHUB + String build_type = "release"; +#else + String build_type = "debug"; +#endif + response.print("

"); + response.print("

"); + response.print("

"); + response.print("

"); + + response.print("Current version: "); + response.print(NUKI_HUB_VERSION); + response.print(" ("); + response.print(NUKI_HUB_BUILD); + response.print("), "); + response.print(NUKI_HUB_DATE); + response.print("
"); + + if(!manifestSuccess) + { + response.print("currentverlatestverdevverbetaver"); + } + else + { + response.print("Latest release version: "); + response.print(doc["release"]["fullversion"].as()); + response.print(" ("); + response.print(doc["release"]["build"].as()); + response.print("), "); + response.print(doc["release"]["time"].as()); + response.print("
"); + response.print("Latest beta version: "); if(doc["beta"]["fullversion"] != "No beta available") { - _response.concat(doc["beta"]["fullversion"].as()); - _response.concat(" ("); - _response.concat(doc["beta"]["build"].as()); - _response.concat("), "); - _response.concat(doc["beta"]["time"].as()); + response.print(doc["beta"]["fullversion"].as()); + response.print(" ("); + response.print(doc["beta"]["build"].as()); + response.print(")
, "); + response.print(doc["beta"]["time"].as()); } else { - _response.concat(doc["beta"]["fullversion"].as()); - _response.concat(""); + response.print(doc["beta"]["fullversion"].as()); + response.print(""); } - _response.concat("
"); - _response.concat("Latest development version: "); - _response.concat(doc["master"]["fullversion"].as()); - _response.concat(" ("); - _response.concat(doc["master"]["build"].as()); - _response.concat("), "); - _response.concat(doc["master"]["time"].as()); - _response.concat("
"); + response.print("
"); + response.print("Latest development version: "); + response.print(doc["master"]["fullversion"].as()); + response.print(" ("); + response.print(doc["master"]["build"].as()); + response.print("), "); + response.print(doc["master"]["time"].as()); + response.print("
"); String currentVersion = NUKI_HUB_VERSION; const char* latestVersion; - if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) latestVersion = doc["release"]["fullversion"]; - else if(currentVersion.indexOf("beta") > 0) latestVersion = doc["beta"]["fullversion"]; - else if(currentVersion.indexOf("master") > 0) latestVersion = doc["master"]["fullversion"]; - else latestVersion = doc["release"]["fullversion"]; + if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) + { + latestVersion = doc["release"]["fullversion"]; + } + else if(currentVersion.indexOf("beta") > 0) + { + latestVersion = doc["beta"]["fullversion"]; + } + else if(currentVersion.indexOf("master") > 0) + { + latestVersion = doc["master"]["fullversion"]; + } + else + { + latestVersion = doc["release"]["fullversion"]; + } - if(strcmp(latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) _preferences->putString(preference_latest_version, latestVersion); + if(strcmp(latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) + { + _preferences->putString(preference_latest_version, latestVersion); + } } - #endif - _response.concat("
"); +#endif + response.print("
"); if(_partitionType == 1) { - _response.concat("

Manually update Nuki Hub

"); - _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:
"); + response.print("

Manually update Nuki Hub

"); + response.print("

Reboot to Nuki Hub Updater

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


"); + response.print("

Update Nuki Hub Updater

"); + response.print("Select the latest Nuki Hub updater binary to update the Nuki Hub updater"); + response.print("
Choose the nuki_hub_updater.bin file to upload:
"); } else { - _response.concat("
"); - _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.print("
"); + response.print("

Reboot to Nuki Hub

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


"); + response.print("

Update Nuki Hub

"); + response.print("Select the latest Nuki Hub binary to update Nuki Hub"); + response.print("
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(""); - sendResponse(request); + response.print("


"); + response.print("
"); + response.print("

GitHub


"); + response.print(""); + response.print("

"); + response.print("

"); + response.print(""); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildOtaCompletedHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildOtaCompletedHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); - _response.concat("
Over-the-air update completed.
You will be forwarded automatically.
"); - _response.concat(""); - _response.concat(""); - sendResponse(request); + response.print("
Over-the-air update completed.
You will be forwarded automatically.
"); + response.print(""); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildHtmlHeader(String additionalHeader) +void WebCfgServer::buildHtmlHeader(PsychicStreamResponse *response, String additionalHeader) { - _response.concat(""); - _response.concat(""); - if(strcmp(additionalHeader.c_str(), "") != 0) _response.concat(additionalHeader); - _response.concat(""); - _response.concat("Nuki Hub"); + response->print(""); + response->print(""); + if(strcmp(additionalHeader.c_str(), "") != 0) + { + response->print(additionalHeader); + } + response->print(""); + response->print("Nuki Hub"); } void WebCfgServer::waitAndProcess(const bool blocking, const uint32_t duration) @@ -472,95 +974,131 @@ void WebCfgServer::waitAndProcess(const bool blocking, const uint32_t duration) } } -void WebCfgServer::printProgress(size_t prg, size_t sz) { - Log->printf("Progress: %d%%\n", (prg*100)/_otaContentLen); +void WebCfgServer::printProgress(size_t prg, size_t sz) +{ + Log->printf("Progress: %d%%\n", (prg*100)/_otaContentLen); } -void WebCfgServer::handleOtaUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) +esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final) { - if(!request->url().endsWith("/uploadota")) return; + if(!request->url().endsWith("/uploadota")) + { + return(ESP_FAIL); + } if(filename == "") { Log->println("Invalid file for OTA upload"); - return; + return(ESP_FAIL); } - if (!index) + if (!Update.hasError()) { - Log->println("Starting manual OTA update"); - _otaContentLen = request->contentLength(); + if (!index) + { + Update.clearError(); - if(_partitionType == 1 && _otaContentLen > 1600000) - { - 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 && _otaContentLen < 1600000) - { - 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; + Log->println("Starting manual OTA update"); + _otaContentLen = request->contentLength(); + + if(_partitionType == 1 && _otaContentLen > 1600000) + { + Log->println("Uploaded OTA file too large, are you trying to upload a Nuki Hub binary instead of a Nuki Hub updater binary?"); + return(ESP_FAIL); + } + else if(_partitionType == 2 && _otaContentLen < 1600000) + { + 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(ESP_FAIL); + } + + _otaStartTs = espMillis(); + esp_task_wdt_config_t twdt_config = + { + .timeout_ms = 30000, + .idle_core_mask = 0, + .trigger_panic = false, + }; + esp_task_wdt_reconfigure(&twdt_config); + +#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); + + if (!Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH)) + { + if (!Update.hasError()) + { + Update.abort(); + } + Log->print("ERROR : update.begin error Update.errorString() "); + Log->println(Update.errorString()); + return(ESP_FAIL); + } } - int cmd = U_FLASH; - if (!Update.begin(UPDATE_SIZE_UNKNOWN, cmd)) { - Update.printError(Serial); + if ((len) && (!Update.hasError())) + { + if (Update.write(data, len) != len) + { + if (!Update.hasError()) + { + Update.abort(); + } + Log->print("ERROR : update.write error Update.errorString() "); + Log->println(Update.errorString()); + return(ESP_FAIL); + } } - _otaStartTs = esp_timer_get_time() / 1000; - esp_task_wdt_config_t twdt_config = { - .timeout_ms = 30000, - .idle_core_mask = 0, - .trigger_panic = false, - }; - esp_task_wdt_reconfigure(&twdt_config); - - #ifndef NUKI_HUB_UPDATER - _network->disableAutoRestarts(); - _network->disableMqtt(); - if(_nuki != nullptr) + if ((final) && (!Update.hasError())) { - _nuki->disableWatchdog(); + if (Update.end(true)) + { + Log->print("Update Success: "); + Log->print(index+len); + Log->println(" written"); + } + else + { + if (!Update.hasError()) + { + Update.abort(); + } + Log->print("ERROR : update end error Update.errorString() "); + Log->println(Update.errorString()); + return(ESP_FAIL); + } } - if(_nukiOpener != nullptr) - { - _nukiOpener->disableWatchdog(); - } - #endif - Log->print("handleFileUpload Name: "); - Log->println(filename); + Log->print(F("Progress: 100%")); + Log->println(); + Log->print("handleFileUpload Total Size: "); + Log->println(index+len); + Log->println("Update complete"); + Log->flush(); + return(ESP_OK); } - - if (_otaContentLen == 0) return; - - if (Update.write(data, len) != len) { - Update.printError(Serial); - restartEsp(RestartReason::OTAAborted); - } - - if (final) { - AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "Please wait while the device reboots"); - response->addHeader("Refresh", "20"); - response->addHeader("Location", "/"); - request->send(response); - if (!Update.end(true)){ - Update.printError(Serial); - restartEsp(RestartReason::OTAAborted); - } else { - Log->print(F("Progress: 100%")); - Log->println(); - Log->print("handleFileUpload Total Size: "); - Log->println(index+len); - Log->println("Update complete"); - Log->flush(); - restartEsp(RestartReason::OTACompleted); - } + else + { + return(ESP_FAIL); } } -void WebCfgServer::buildConfirmHtml(AsyncWebServerRequest *request, const String &message, uint32_t redirectDelay, bool redirect) +esp_err_t WebCfgServer::buildConfirmHtml(PsychicRequest *request, const String &message, uint32_t redirectDelay, bool redirect) { - _response = ""; + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); String header; if(!redirect) @@ -573,25 +1111,31 @@ void WebCfgServer::buildConfirmHtml(AsyncWebServerRequest *request, const String String delay(redirectDelay * 1000); header = ""; } - buildHtmlHeader(header); - _response.concat(message); - _response.concat(""); - sendResponse(request); + buildHtmlHeader(&response, header); + response.print(message); + response.print(""); + return response.endSend(); } -void WebCfgServer::sendCss(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::sendCss(PsychicRequest *request) { // escaped by https://www.cescaper.com/ - AsyncWebServerResponse *asyncResponse = request->beginResponse(200, "text/css", (const uint8_t*)stylecss, sizeof(stylecss)); - asyncResponse ->addHeader("Cache-Control", "public, max-age=3600"); - request->send(asyncResponse); + PsychicResponse response(request); + response.addHeader("Cache-Control", "public, max-age=3600"); + response.setCode(200); + response.setContentType("text/css"); + response.setContent(stylecss); + return response.send(); } -void WebCfgServer::sendFavicon(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::sendFavicon(PsychicRequest *request) { - AsyncWebServerResponse *asyncResponse = request->beginResponse(200, "image/png", (const uint8_t*)favicon_32x32, sizeof(favicon_32x32)); - asyncResponse->addHeader("Cache-Control", "public, max-age=604800"); - request->send(asyncResponse); + PsychicResponse response(request); + response.addHeader("Cache-Control", "public, max-age=604800"); + response.setCode(200); + response.setContentType("image/png"); + response.setContent((const char*)favicon_32x32); + return response.send(); } String WebCfgServer::generateConfirmCode() @@ -600,21 +1144,83 @@ String WebCfgServer::generateConfirmCode() return String(code); } +void WebCfgServer::printInputField(PsychicStreamResponse *response, + const char *token, + const char *description, + const char *value, + const size_t& maxLength, + const char *args, + const bool& isPassword, + const bool& showLengthRestriction) +{ + char maxLengthStr[20]; + + itoa(maxLength, maxLengthStr, 10); + + response->print(""); + response->print(description); + + if(showLengthRestriction) + { + response->print(" (Max. "); + response->print(maxLength); + response->print(" characters)"); + } + + response->print(""); + response->print("print(" "); + response->print(args); + } + if(strcmp(value, "") != 0) + { + response->print(" value=\""); + response->print(value); + } + response->print("\" name=\""); + response->print(token); + response->print("\" size=\"25\" maxlength=\""); + response->print(maxLengthStr); + response->print("\"/>"); + response->print(""); +} + +void WebCfgServer::printInputField(PsychicStreamResponse *response, + const char *token, + const char *description, + const int value, + size_t maxLength, + const char *args) +{ + char valueStr[20]; + itoa(value, valueStr, 10); + printInputField(response, token, description, valueStr, maxLength, args); +} + #ifndef NUKI_HUB_UPDATER -void WebCfgServer::sendSettings(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::sendSettings(PsychicRequest *request) { bool redacted = false; bool pairing = false; if(request->hasParam("redacted")) { - const AsyncWebParameter* p = request->getParam("redacted"); - if(p->value() == "1") redacted = true; + const PsychicWebParameter* p = request->getParam("redacted"); + if(p->value() == "1") + { + redacted = true; + } } if(request->hasParam("pairing")) { - const AsyncWebParameter* p = request->getParam("pairing"); - if(p->value() == "1") pairing = true; + const PsychicWebParameter* p = request->getParam("pairing"); + if(p->value() == "1") + { + pairing = true; + } } JsonDocument json; @@ -629,47 +1235,68 @@ void WebCfgServer::sendSettings(AsyncWebServerRequest *request) 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_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(!_preferences->isKey(key)) json[key] = ""; - else if(std::find(boolPrefs.begin(), boolPrefs.end(), key) != boolPrefs.end()) json[key] = _preferences->getBool(key) ? "1" : "0"; + if(strcmp(key, preference_show_secrets) == 0) + { + continue; + } + if(strcmp(key, preference_latest_version) == 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(!_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; + 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; } } } @@ -691,21 +1318,24 @@ void WebCfgServer::sendSettings(AsyncWebServerRequest *request) nukiBlePref.end(); char text[255]; text[0] = '\0'; - for(int i = 0 ; i < 6 ; i++) { + 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++) { + 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++) { + for(int i = 0 ; i < 4 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", authorizationId[i]); } @@ -728,21 +1358,24 @@ void WebCfgServer::sendSettings(AsyncWebServerRequest *request) nukiBlePref.end(); char text[255]; text[0] = '\0'; - for(int i = 0 ; i < 6 ; i++) { + 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++) { + 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++) { + for(int i = 0 ; i < 4 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", authorizationIdOpn[i]); } @@ -755,14 +1388,21 @@ void WebCfgServer::sendSettings(AsyncWebServerRequest *request) for(const auto& key : bytePrefs) { size_t storedLength = _preferences->getBytesLength(key); - if(storedLength == 0) continue; + 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; + if(size == 0) + { + continue; + } char text[255]; text[0] = '\0'; - for(int i = 0 ; i < size ; i++) { + for(int i = 0 ; i < size ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", serialized[i]); } @@ -772,17 +1412,10 @@ void WebCfgServer::sendSettings(AsyncWebServerRequest *request) serializeJsonPretty(json, jsonPretty); - AsyncWebServerResponse *response = request->beginChunkedResponse("application/json", - [&](uint8_t *buffer, size_t maxlen, size_t index) -> size_t { - size_t len = min(maxlen, jsonPretty.length() - index); - memcpy(buffer, jsonPretty.c_str() + index, len); - return len; - }); - - request->send(response); + return request->reply(200, "application/json", jsonPretty.c_str()); } -bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) +bool WebCfgServer::processArgs(PsychicRequest *request, String& message) { bool configChanged = false; bool aclLvlChanged = false; @@ -812,14 +1445,17 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) for(int index = 0; index < params; index++) { - const AsyncWebParameter* p = request->getParam(index); + const PsychicWebParameter* p = request->getParam(index); String key = p->name(); String value = p->value(); if(index < params -1) { - const AsyncWebParameter* next = request->getParam(index+1); - if(key == next->name()) continue; + const PsychicWebParameter* next = request->getParam(index+1); + if(key == next->name()) + { + continue; + } } if(key == "MQTTSERVER") @@ -929,7 +1565,10 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) if(value.toInt() > 1) { networkReconfigure = true; - if(value.toInt() != 11) _preferences->putInt(preference_network_custom_phy, 0); + if(value.toInt() != 11) + { + _preferences->putInt(preference_network_custom_phy, 0); + } } _preferences->putInt(preference_network_hardware, value.toInt()); Log->print(F("Setting changed: ")); @@ -1093,8 +1732,14 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) { if(_preferences->getString(preference_mqtt_hass_discovery, "") != value) { - if (_nuki != nullptr) _nuki->disableHASS(); - if (_nukiOpener != nullptr) _nukiOpener->disableHASS(); + if (_nuki != nullptr) + { + _nuki->disableHASS(); + } + if (_nukiOpener != nullptr) + { + _nukiOpener->disableHASS(); + } _preferences->putString(preference_mqtt_hass_discovery, value); Log->print(F("Setting changed: ")); Log->println(key); @@ -1121,16 +1766,6 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) //configChanged = true; } } - else if(key == "BESTRSSI") - { - if(_preferences->getBool(preference_find_best_rssi, false) != (value == "1")) - { - _preferences->putBool(preference_find_best_rssi, (value == "1")); - Log->print(F("Setting changed: ")); - Log->println(key); - //configChanged = true; - } - } else if(key == "HOSTNAME") { if(_preferences->getString(preference_hostname, "") != value) @@ -1161,16 +1796,6 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) //configChanged = true; } } - else if(key == "RECNWTMQTTDIS") - { - if(_preferences->getBool(preference_recon_netw_on_mqtt_discon, false) != (value == "1")) - { - _preferences->putBool(preference_recon_netw_on_mqtt_discon, (value == "1")); - Log->print(F("Setting changed: ")); - Log->println(key); - //configChanged = true; - } - } else if(key == "MQTTLOG") { if(_preferences->getBool(preference_mqtt_log_enabled, false) != (value == "1")) @@ -1216,7 +1841,10 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) if(_preferences->getBool(preference_official_hybrid_enabled, false) != (value == "1")) { _preferences->putBool(preference_official_hybrid_enabled, (value == "1")); - if((value == "1")) _preferences->putBool(preference_register_as_app, true); + if((value == "1")) + { + _preferences->putBool(preference_register_as_app, true); + } Log->print(F("Setting changed: ")); Log->println(key); configChanged = true; @@ -1227,7 +1855,10 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) if(_preferences->getBool(preference_official_hybrid_actions, false) != (value == "1")) { _preferences->putBool(preference_official_hybrid_actions, (value == "1")); - if(value == "1") _preferences->putBool(preference_register_as_app, true); + if(value == "1") + { + _preferences->putBool(preference_register_as_app, true); + } Log->print(F("Setting changed: ")); Log->println(key); //configChanged = true; @@ -2136,27 +2767,45 @@ bool WebCfgServer::processArgs(AsyncWebServerRequest *request, String& message) } else if(key == "LCKBLEADDR") { - if(value.length() == 12) for(int i=0; igetParam(index); + const PsychicWebParameter* p = request->getParam(index); if(p->name() == "importjson") { JsonDocument doc; @@ -2372,26 +3021,59 @@ bool WebCfgServer::processImport(AsyncWebServerRequest *request, String& message 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_device_id_lock) == 0) continue; - if(strcmp(key, preference_device_id_opener) == 0) continue; + 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_device_id_lock) == 0) + { + continue; + } + if(strcmp(key, preference_device_id_opener) == 0) + { + 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); + 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); + 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); + if (doc[key].as().length() > 0) + { + _preferences->putString(key, doc[key].as()); + } + else + { + _preferences->remove(key); + } } for(const auto& key : bytePrefs) @@ -2400,7 +3082,10 @@ bool WebCfgServer::processImport(AsyncWebServerRequest *request, String& message { 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)); } @@ -2414,7 +3099,10 @@ bool WebCfgServer::processImport(AsyncWebServerRequest *request, String& message if (doc["bleAddressLock"].as().length() == 12) { String value = doc["bleAddressLock"].as(); - for(int i=0; i().length() == 64) { String value = doc["secretKeyKLock"].as(); - for(int i=0; i().length() == 8) { String value = doc["authorizationIdLock"].as(); - for(int i=0; i().length() > 0) _nuki->setPin(doc["securityPinCodeLock"].as()); - else _nuki->setPin(0xffff); + if(doc["securityPinCodeLock"].as().length() > 0) + { + _nuki->setPin(doc["securityPinCodeLock"].as()); + } + else + { + _nuki->setPin(0xffff); + } } nukiBlePref.begin("NukiHubopener", false); if(!doc["bleAddressOpener"].isNull()) @@ -2448,7 +3148,10 @@ bool WebCfgServer::processImport(AsyncWebServerRequest *request, String& message if (doc["bleAddressOpener"].as().length() == 12) { String value = doc["bleAddressOpener"].as(); - for(int i=0; i().length() == 64) { String value = doc["secretKeyKOpener"].as(); - for(int i=0; i().length() == 8) { String value = doc["authorizationIdOpener"].as(); - for(int i=0; i().length() > 0) _nukiOpener->setPin(doc["securityPinCodeOpener"].as()); - else _nukiOpener->setPin(0xffff); + if(doc["securityPinCodeOpener"].as().length() > 0) + { + _nukiOpener->setPin(doc["securityPinCodeOpener"].as()); + } + else + { + _nukiOpener->setPin(0xffff); + } } configChanged = true; @@ -2494,14 +3209,14 @@ bool WebCfgServer::processImport(AsyncWebServerRequest *request, String& message return configChanged; } -void WebCfgServer::processGpioArgs(AsyncWebServerRequest *request) +void WebCfgServer::processGpioArgs(PsychicRequest *request) { int params = request->params(); std::vector pinConfiguration; for(int index = 0; index < params; index++) { - const AsyncWebParameter* p = request->getParam(index); + const PsychicWebParameter* p = request->getParam(index); PinRole role = (PinRole)p->value().toInt(); if(role != PinRole::Disabled) { @@ -2515,87 +3230,90 @@ void WebCfgServer::processGpioArgs(AsyncWebServerRequest *request) _gpio->savePinConfiguration(pinConfiguration); } -void WebCfgServer::buildImportExportHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildImportExportHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - - _response.concat("

Import configuration

"); - _response.concat("

"); - _response.concat("


"); - _response.concat("
"); - _response.concat("

Export configuration


"); - _response.concat(""); - _response.concat("

"); - _response.concat("

"); - _response.concat("
"); - sendResponse(request); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print("

Import configuration

"); + response.print("

"); + response.print("


"); + response.print("
"); + response.print("

Export configuration


"); + response.print(""); + response.print("

"); + response.print("

"); + response.print("
"); + return response.endSend(); } -void WebCfgServer::buildCustomNetworkConfigHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildCustomNetworkConfigHtml(PsychicRequest *request) { String header = ""; - _response = ""; - buildHtmlHeader(header); - _response.concat("
"); - _response.concat("

Custom Ethernet Configuration

"); - _response.concat(""); - printDropDown("NWCUSTPHY", "PHY", String(_preferences->getInt(preference_network_custom_phy)), getNetworkCustomPHYOptions(), ""); - printInputField("NWCUSTADDR", "ADDR", _preferences->getInt(preference_network_custom_addr, 1), 6, ""); - #if defined(CONFIG_IDF_TARGET_ESP32) - printDropDown("NWCUSTCLK", "CLK", String(_preferences->getInt(preference_network_custom_clk, 0)), getNetworkCustomCLKOptions(), "internalopt"); - printInputField("NWCUSTPWR", "PWR", _preferences->getInt(preference_network_custom_pwr, 12), 6, "class=\"internalopt\""); - printInputField("NWCUSTMDIO", "MDIO", _preferences->getInt(preference_network_custom_mdio), 6, "class=\"internalopt\""); - printInputField("NWCUSTMDC", "MDC", _preferences->getInt(preference_network_custom_mdc), 6, "class=\"internalopt\""); - #endif - printInputField("NWCUSTIRQ", "IRQ", _preferences->getInt(preference_network_custom_irq, -1), 6, "class=\"externalopt\""); - printInputField("NWCUSTRST", "RST", _preferences->getInt(preference_network_custom_rst, -1), 6, "class=\"externalopt\""); - printInputField("NWCUSTCS", "CS", _preferences->getInt(preference_network_custom_cs, -1), 6, "class=\"externalopt\""); - printInputField("NWCUSTSCK", "SCK", _preferences->getInt(preference_network_custom_sck, -1), 6, "class=\"externalopt\""); - printInputField("NWCUSTMISO", "MISO", _preferences->getInt(preference_network_custom_miso, -1), 6, "class=\"externalopt\""); - printInputField("NWCUSTMOSI", "MOSI", _preferences->getInt(preference_network_custom_mosi, -1), 6, "class=\"externalopt\""); - - _response.concat("
"); - - _response.concat("
"); - _response.concat("
"); - _response.concat(""); - sendResponse(request); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response, header); + response.print("
"); + response.print("

Custom Ethernet Configuration

"); + response.print(""); + printDropDown(&response, "NWCUSTPHY", "PHY", String(_preferences->getInt(preference_network_custom_phy)), getNetworkCustomPHYOptions(), ""); + printInputField(&response, "NWCUSTADDR", "ADDR", _preferences->getInt(preference_network_custom_addr, 1), 6, ""); +#if defined(CONFIG_IDF_TARGET_ESP32) + printDropDown(&response, "NWCUSTCLK", "CLK", String(_preferences->getInt(preference_network_custom_clk, 0)), getNetworkCustomCLKOptions(), "internalopt"); + printInputField(&response, "NWCUSTPWR", "PWR", _preferences->getInt(preference_network_custom_pwr, 12), 6, "class=\"internalopt\""); + printInputField(&response, "NWCUSTMDIO", "MDIO", _preferences->getInt(preference_network_custom_mdio), 6, "class=\"internalopt\""); + printInputField(&response, "NWCUSTMDC", "MDC", _preferences->getInt(preference_network_custom_mdc), 6, "class=\"internalopt\""); +#endif + printInputField(&response, "NWCUSTIRQ", "IRQ", _preferences->getInt(preference_network_custom_irq, -1), 6, "class=\"externalopt\""); + printInputField(&response, "NWCUSTRST", "RST", _preferences->getInt(preference_network_custom_rst, -1), 6, "class=\"externalopt\""); + printInputField(&response, "NWCUSTCS", "CS", _preferences->getInt(preference_network_custom_cs, -1), 6, "class=\"externalopt\""); + printInputField(&response, "NWCUSTSCK", "SCK", _preferences->getInt(preference_network_custom_sck, -1), 6, "class=\"externalopt\""); + printInputField(&response, "NWCUSTMISO", "MISO", _preferences->getInt(preference_network_custom_miso, -1), 6, "class=\"externalopt\""); + printInputField(&response, "NWCUSTMOSI", "MOSI", _preferences->getInt(preference_network_custom_mosi, -1), 6, "class=\"externalopt\""); + response.print("
"); + response.print("
"); + response.print("
"); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildHtml(PsychicRequest *request) { String header = ""; - _response = ""; - buildHtmlHeader(header); - - if(_rebootRequired) _response.concat("
REBOOT REQUIRED TO APPLY SETTINGS
"); - if(_preferences->getBool(preference_webserial_enabled, false)) _response.concat("
WEBSERIAL IS ENABLED, ONLY ENABLE WHEN DEBUGGING AND DISABLE ASAP
"); - #ifdef DEBUG_NUKIHUB - _response.concat("
RUNNING DEBUG BUILD, SWITCH TO RELEASE BUILD ASAP
"); - #endif - - _response.concat("

Info


"); - _response.concat(""); - - printParameter("Hostname", _hostname.c_str(), "", "hostname"); - printParameter("MQTT Connected", _network->mqttConnectionState() > 0 ? "Yes" : "No", "", "mqttState"); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response, header); + if(_rebootRequired) + { + response.print("
REBOOT REQUIRED TO APPLY SETTINGS
"); + } + if(_preferences->getBool(preference_webserial_enabled, false)) + { + response.print("
WEBSERIAL IS ENABLED, ONLY ENABLE WHEN DEBUGGING AND DISABLE ASAP
"); + } +#ifdef DEBUG_NUKIHUB + response.print("
RUNNING DEBUG BUILD, SWITCH TO RELEASE BUILD ASAP
"); +#endif + response.print("

Info


"); + response.print(""); + printParameter(&response, "Hostname", _hostname.c_str(), "", "hostname"); + printParameter(&response, "MQTT Connected", _network->mqttConnectionState() > 0 ? "Yes" : "No", "", "mqttState"); if(_nuki != nullptr) { char lockStateArr[20]; NukiLock::lockstateToString(_nuki->keyTurnerState().lockState, lockStateArr); - printParameter("Nuki Lock paired", _nuki->isPaired() ? ("Yes (BLE Address " + _nuki->getBleAddress().toString() + ")").c_str() : "No", "", "lockPaired"); - printParameter("Nuki Lock state", lockStateArr, "", "lockState"); + printParameter(&response, "Nuki Lock paired", _nuki->isPaired() ? ("Yes (BLE Address " + _nuki->getBleAddress().toString() + ")").c_str() : "No", "", "lockPaired"); + printParameter(&response, "Nuki Lock state", lockStateArr, "", "lockState"); if(_nuki->isPaired()) { String lockState = pinStateToString(_preferences->getInt(preference_lock_pin_status, 4)); - printParameter("Nuki Lock PIN status", lockState.c_str(), "", "lockPin"); + printParameter(&response, "Nuki Lock PIN status", lockState.c_str(), "", "lockPin"); if(_preferences->getBool(preference_official_hybrid_enabled, false)) { String offConnected = _nuki->offConnected() ? "Yes": "No"; - printParameter("Nuki Lock hybrid mode connected", offConnected.c_str(), "", "lockHybrid"); + printParameter(&response, "Nuki Lock hybrid mode connected", offConnected.c_str(), "", "lockHybrid"); } } } @@ -2603,234 +3321,247 @@ void WebCfgServer::buildHtml(AsyncWebServerRequest *request) { char openerStateArr[20]; NukiOpener::lockstateToString(_nukiOpener->keyTurnerState().lockState, openerStateArr); - printParameter("Nuki Opener paired", _nukiOpener->isPaired() ? ("Yes (BLE Address " + _nukiOpener->getBleAddress().toString() + ")").c_str() : "No", "", "openerPaired"); - - if(_nukiOpener->keyTurnerState().nukiState == NukiOpener::State::ContinuousMode) printParameter("Nuki Opener state", "Open (Continuous Mode)", "", "openerState"); - else printParameter("Nuki Opener state", openerStateArr, "", "openerState"); + printParameter(&response, "Nuki Opener paired", _nukiOpener->isPaired() ? ("Yes (BLE Address " + _nukiOpener->getBleAddress().toString() + ")").c_str() : "No", "", "openerPaired"); + if(_nukiOpener->keyTurnerState().nukiState == NukiOpener::State::ContinuousMode) + { + printParameter(&response, "Nuki Opener state", "Open (Continuous Mode)", "", "openerState"); + } + else + { + printParameter(&response, "Nuki Opener state", openerStateArr, "", "openerState"); + } if(_nukiOpener->isPaired()) { String openerState = pinStateToString(_preferences->getInt(preference_opener_pin_status, 4)); - printParameter("Nuki Opener PIN status", openerState.c_str(), "", "openerPin"); + printParameter(&response, "Nuki Opener PIN status", openerState.c_str(), "", "openerPin"); } } - printParameter("Firmware", NUKI_HUB_VERSION, "/info", "firmware"); - if(_preferences->getBool(preference_check_updates)) printParameter("Latest Firmware", _preferences->getString(preference_latest_version).c_str(), "/ota", "ota"); - _response.concat("

"); - _response.concat("
    "); - buildNavigationMenuEntry("MQTT and Network Configuration", "/mqttconfig", _brokerConfigured ? "" : "Please configure MQTT broker"); - buildNavigationMenuEntry("Nuki Configuration", "/nukicfg"); - buildNavigationMenuEntry("Access Level Configuration", "/acclvl"); - buildNavigationMenuEntry("Credentials", "/cred", _pinsConfigured ? "" : "Please configure PIN"); - buildNavigationMenuEntry("GPIO Configuration", "/gpiocfg"); - buildNavigationMenuEntry("Firmware update", "/ota"); - buildNavigationMenuEntry("Import/Export Configuration", "/impexpcfg"); + printParameter(&response, "Firmware", NUKI_HUB_VERSION, "/infopg", "firmware"); + if(_preferences->getBool(preference_check_updates)) + { + printParameter(&response, "Latest Firmware", _preferences->getString(preference_latest_version).c_str(), "/ota", "ota"); + } + response.print("
    "); + response.print("
      "); + buildNavigationMenuEntry(&response, "MQTT and Network Configuration", "/mqttconfig", _brokerConfigured ? "" : "Please configure MQTT broker"); + buildNavigationMenuEntry(&response, "Nuki Configuration", "/nukicfg"); + buildNavigationMenuEntry(&response, "Access Level Configuration", "/acclvl"); + buildNavigationMenuEntry(&response, "Credentials", "/cred", _pinsConfigured ? "" : "Please configure PIN"); + buildNavigationMenuEntry(&response, "GPIO Configuration", "/gpiocfg"); + buildNavigationMenuEntry(&response, "Firmware update", "/ota"); + buildNavigationMenuEntry(&response, "Import/Export Configuration", "/impexpcfg"); if(_preferences->getInt(preference_network_hardware, 0) == 11) { - buildNavigationMenuEntry("Custom Ethernet Configuration", "/custntw"); + buildNavigationMenuEntry(&response, "Custom Ethernet Configuration", "/custntw"); } if (_preferences->getBool(preference_publish_debug_info, false)) { - buildNavigationMenuEntry("Advanced Configuration", "/advanced"); + buildNavigationMenuEntry(&response, "Advanced Configuration", "/advanced"); } if(_preferences->getBool(preference_webserial_enabled, false)) { - buildNavigationMenuEntry("Open Webserial", "/webserial"); + buildNavigationMenuEntry(&response, "Open Webserial", "/webserial"); } - #ifndef CONFIG_IDF_TARGET_ESP32H2 - if(_allowRestartToPortal) buildNavigationMenuEntry("Configure Wi-Fi", "/wifi"); - #endif - buildNavigationMenuEntry("Reboot Nuki Hub", "/reboot"); - _response.concat("
    "); - sendResponse(request); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + if(_allowRestartToPortal) + { + buildNavigationMenuEntry(&response, "Configure Wi-Fi", "/wifi"); + } +#endif + String rebooturl = "/reboot?CONFIRMTOKEN=" + _confirmCode; + buildNavigationMenuEntry(&response, "Reboot Nuki Hub", rebooturl.c_str()); + response.print("
"); + return response.endSend(); } -void WebCfgServer::buildCredHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildCredHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - _response.concat("
"); - _response.concat("

Credentials

"); - _response.concat(""); - printInputField("CREDUSER", "User (# to clear)", _preferences->getString(preference_cred_user).c_str(), 30, "id=\"inputuser\"", false, true); - printInputField("CREDPASS", "Password", "*", 30, "id=\"inputpass\"", true, true); - printInputField("CREDPASSRE", "Retype password", "*", 30, "", true); - _response.concat("
"); - _response.concat("
"); - _response.concat("
"); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print("
"); + response.print("

Credentials

"); + response.print(""); + printInputField(&response, "CREDUSER", "User (# to clear)", _preferences->getString(preference_cred_user).c_str(), 30, "", false, true); + printInputField(&response, "CREDPASS", "Password", "*", 30, "", true, true); + printInputField(&response, "CREDPASSRE", "Retype password", "*", 30, "", true); + response.print("
"); + response.print("
"); + response.print("
"); if(_nuki != nullptr) { - _response.concat("

"); - _response.concat("

Nuki Lock PIN

"); - _response.concat(""); - printInputField("NUKIPIN", "PIN Code (# to clear)", "*", 20, "", true); - _response.concat("
"); - _response.concat("
"); - _response.concat("
"); + response.print("

"); + response.print("

Nuki Lock PIN

"); + response.print(""); + printInputField(&response, "NUKIPIN", "PIN Code (# to clear)", "*", 20, "", true); + response.print("
"); + response.print("
"); + response.print("
"); } if(_nukiOpener != nullptr) { - _response.concat("

"); - _response.concat("

Nuki Opener PIN

"); - _response.concat(""); - printInputField("NUKIOPPIN", "PIN Code (# to clear)", "*", 20, "", true); - _response.concat("
"); - _response.concat("
"); - _response.concat("
"); + response.print("

"); + response.print("

Nuki Opener PIN

"); + response.print(""); + printInputField(&response, "NUKIOPPIN", "PIN Code (# to clear)", "*", 20, "", true); + response.print("
"); + response.print("
"); + response.print("
"); } if(_nuki != nullptr) { - _response.concat("

Unpair Nuki Lock

"); - _response.concat("
"); - _response.concat(""); + response.print("

Unpair Nuki Lock

"); + response.print(""); + response.print("
"); String message = "Type "; message.concat(_confirmCode); message.concat(" to confirm unpair"); - printInputField("CONFIRMTOKEN", message.c_str(), "", 10, ""); - _response.concat("
"); - _response.concat("
"); + printInputField(&response, "CONFIRMTOKEN", message.c_str(), "", 10, ""); + response.print(""); + response.print("
"); } if(_nukiOpener != nullptr) { - _response.concat("

Unpair Nuki Opener

"); - _response.concat("
"); - _response.concat(""); + response.print("

Unpair Nuki Opener

"); + response.print(""); + response.print("
"); String message = "Type "; message.concat(_confirmCode); message.concat(" to confirm unpair"); - printInputField("CONFIRMTOKEN", message.c_str(), "", 10, ""); - _response.concat("
"); - _response.concat("
"); + printInputField(&response, "CONFIRMTOKEN", message.c_str(), "", 10, ""); + response.print(""); + response.print("
"); } - _response.concat("

Factory reset Nuki Hub

"); - _response.concat("

This will reset all settings to default and unpair Nuki Lock and/or Opener."); - #ifndef CONFIG_IDF_TARGET_ESP32H2 - _response.concat("Optionally will also reset WiFi settings and reopen WiFi manager portal."); - #endif - _response.concat("

"); - _response.concat("
"); - _response.concat(""); + response.print("

Factory reset Nuki Hub

"); + response.print("

This will reset all settings to default and unpair Nuki Lock and/or Opener."); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + response.print("Optionally will also reset WiFi settings and reopen WiFi manager portal."); +#endif + response.print("

"); + response.print(""); + response.print("
"); String message = "Type "; message.concat(_confirmCode); message.concat(" to confirm factory reset"); - printInputField("CONFIRMTOKEN", message.c_str(), "", 10, ""); - #ifndef CONFIG_IDF_TARGET_ESP32H2 - printCheckBox("WIFI", "Also reset WiFi settings", false, ""); - #endif - _response.concat("
"); - _response.concat("
"); - _response.concat(""); - sendResponse(request); + printInputField(&response, "CONFIRMTOKEN", message.c_str(), "", 10, ""); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + printCheckBox(&response, "WIFI", "Also reset WiFi settings", false, ""); +#endif + response.print(""); + response.print("
"); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildMqttConfigHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildMqttConfigHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - _response.concat("
"); - _response.concat("

Basic MQTT and Network Configuration

"); - _response.concat(""); - printInputField("HOSTNAME", "Host name", _preferences->getString(preference_hostname).c_str(), 100, ""); - printInputField("MQTTSERVER", "MQTT Broker", _preferences->getString(preference_mqtt_broker).c_str(), 100, ""); - printInputField("MQTTPORT", "MQTT Broker port", _preferences->getInt(preference_mqtt_broker_port), 5, ""); - printInputField("MQTTUSER", "MQTT User (# to clear)", _preferences->getString(preference_mqtt_user).c_str(), 30, "", false, true); - printInputField("MQTTPASS", "MQTT Password", "*", 30, "", true, true); - _response.concat("

"); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print(""); + response.print("

Basic MQTT and Network Configuration

"); + response.print(""); + printInputField(&response, "HOSTNAME", "Host name", _preferences->getString(preference_hostname).c_str(), 100, ""); + printInputField(&response, "MQTTSERVER", "MQTT Broker", _preferences->getString(preference_mqtt_broker).c_str(), 100, ""); + printInputField(&response, "MQTTPORT", "MQTT Broker port", _preferences->getInt(preference_mqtt_broker_port), 5, ""); + printInputField(&response, "MQTTUSER", "MQTT User (# to clear)", _preferences->getString(preference_mqtt_user).c_str(), 30, "", false, true); + printInputField(&response, "MQTTPASS", "MQTT Password", "*", 30, "", true, true); + response.print("

"); - _response.concat("

Advanced MQTT and Network Configuration

"); - _response.concat(""); - printInputField("HASSDISCOVERY", "Home Assistant discovery topic (empty to disable; usually homeassistant)", _preferences->getString(preference_mqtt_hass_discovery).c_str(), 30, ""); - printInputField("HASSCUURL", "Home Assistant device configuration URL (empty to use http://LOCALIP; fill when using a reverse proxy for example)", _preferences->getString(preference_mqtt_hass_cu_url).c_str(), 261, ""); - if(_preferences->getBool(preference_opener_enabled, false)) printCheckBox("OPENERCONT", "Set Nuki Opener Lock/Unlock action in Home Assistant to Continuous mode", _preferences->getBool(preference_opener_continuous_mode), ""); - printTextarea("MQTTCA", "MQTT SSL CA Certificate (*, optional)", _preferences->getString(preference_mqtt_ca).c_str(), TLS_CA_MAX_SIZE, _network->encryptionSupported(), true); - printTextarea("MQTTCRT", "MQTT SSL Client Certificate (*, optional)", _preferences->getString(preference_mqtt_crt).c_str(), TLS_CERT_MAX_SIZE, _network->encryptionSupported(), true); - printTextarea("MQTTKEY", "MQTT SSL Client Key (*, optional)", _preferences->getString(preference_mqtt_key).c_str(), TLS_KEY_MAX_SIZE, _network->encryptionSupported(), true); - printDropDown("NWHW", "Network hardware", String(_preferences->getInt(preference_network_hardware)), getNetworkDetectionOptions(), ""); - #ifndef CONFIG_IDF_TARGET_ESP32H2 - printCheckBox("NWHWWIFIFB", "Disable fallback to Wi-Fi / Wi-Fi config portal", _preferences->getBool(preference_network_wifi_fallback_disabled), ""); - printCheckBox("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("RSSI", "RSSI Publish interval (seconds; -1 to disable)", _preferences->getInt(preference_rssi_publish_interval), 6, ""); - #endif - printInputField("NETTIMEOUT", "MQTT Timeout until restart (seconds; -1 to disable)", _preferences->getInt(preference_network_timeout), 5, ""); - printCheckBox("RSTDISC", "Restart on disconnect", _preferences->getBool(preference_restart_on_disconnect), ""); - printCheckBox("RECNWTMQTTDIS", "Reconnect network on MQTT connection failure", _preferences->getBool(preference_recon_netw_on_mqtt_discon), ""); - printCheckBox("MQTTLOG", "Enable MQTT logging", _preferences->getBool(preference_mqtt_log_enabled), ""); - printCheckBox("CHECKUPDATE", "Check for Firmware Updates every 24h", _preferences->getBool(preference_check_updates), ""); - printCheckBox("UPDATEMQTT", "Allow updating using MQTT", _preferences->getBool(preference_update_from_mqtt), ""); - printCheckBox("DISNONJSON", "Disable some extraneous non-JSON topics", _preferences->getBool(preference_disable_non_json), ""); - printCheckBox("OFFHYBRID", "Enable hybrid official MQTT and Nuki Hub setup", _preferences->getBool(preference_official_hybrid_enabled), ""); - printCheckBox("HYBRIDACT", "Enable sending actions through official MQTT", _preferences->getBool(preference_official_hybrid_actions), ""); - printInputField("HYBRIDTIMER", "Time between status updates when official MQTT is offline (seconds)", _preferences->getInt(preference_query_interval_hybrid_lockstate), 5, ""); - // printCheckBox("HYBRIDRETRY", "Retry command sent using official MQTT over BLE if failed", _preferences->getBool(preference_official_hybrid_retry), ""); // NOT IMPLEMENTED (YET?) - _response.concat("
"); - _response.concat("* If no encryption is configured for the MQTT broker, leave empty.

"); - - _response.concat("

IP Address assignment

"); - _response.concat(""); - printCheckBox("DHCPENA", "Enable DHCP", _preferences->getBool(preference_ip_dhcp_enabled), ""); - printInputField("IPADDR", "Static IP address", _preferences->getString(preference_ip_address).c_str(), 15, ""); - printInputField("IPSUB", "Subnet", _preferences->getString(preference_ip_subnet).c_str(), 15, ""); - printInputField("IPGTW", "Default gateway", _preferences->getString(preference_ip_gateway).c_str(), 15, ""); - printInputField("DNSSRV", "DNS Server", _preferences->getString(preference_ip_dns_server).c_str(), 15, ""); - _response.concat("
"); - _response.concat("
"); - _response.concat("
"); - _response.concat(""); - sendResponse(request); + response.print("

Advanced MQTT and Network Configuration

"); + response.print(""); + printInputField(&response, "HASSDISCOVERY", "Home Assistant discovery topic (empty to disable; usually homeassistant)", _preferences->getString(preference_mqtt_hass_discovery).c_str(), 30, ""); + printInputField(&response, "HASSCUURL", "Home Assistant device configuration URL (empty to use http://LOCALIP; fill when using a reverse proxy for example)", _preferences->getString(preference_mqtt_hass_cu_url).c_str(), 261, ""); + if(_preferences->getBool(preference_opener_enabled, false)) + { + printCheckBox(&response, "OPENERCONT", "Set Nuki Opener Lock/Unlock action in Home Assistant to Continuous mode", _preferences->getBool(preference_opener_continuous_mode), ""); + } + printTextarea(&response, "MQTTCA", "MQTT SSL CA Certificate (*, optional)", _preferences->getString(preference_mqtt_ca).c_str(), TLS_CA_MAX_SIZE, true, true); + printTextarea(&response, "MQTTCRT", "MQTT SSL Client Certificate (*, optional)", _preferences->getString(preference_mqtt_crt).c_str(), TLS_CERT_MAX_SIZE, true, true); + printTextarea(&response, "MQTTKEY", "MQTT SSL Client Key (*, optional)", _preferences->getString(preference_mqtt_key).c_str(), TLS_KEY_MAX_SIZE, true, true); + printDropDown(&response, "NWHW", "Network hardware", String(_preferences->getInt(preference_network_hardware)), getNetworkDetectionOptions(), ""); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + printInputField(&response, "RSSI", "RSSI Publish interval (seconds; -1 to disable)", _preferences->getInt(preference_rssi_publish_interval), 6, ""); +#endif + 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_enabled), ""); + 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), ""); // NOT IMPLEMENTED (YET?) + response.print("
"); + response.print("* If no encryption is configured for the MQTT broker, leave empty.

"); + response.print("

IP Address assignment

"); + response.print(""); + printCheckBox(&response, "DHCPENA", "Enable DHCP", _preferences->getBool(preference_ip_dhcp_enabled), ""); + printInputField(&response, "IPADDR", "Static IP address", _preferences->getString(preference_ip_address).c_str(), 15, ""); + printInputField(&response, "IPSUB", "Subnet", _preferences->getString(preference_ip_subnet).c_str(), 15, ""); + printInputField(&response, "IPGTW", "Default gateway", _preferences->getString(preference_ip_gateway).c_str(), 15, ""); + printInputField(&response, "DNSSRV", "DNS Server", _preferences->getString(preference_ip_dns_server).c_str(), 15, ""); + response.print("
"); + response.print("
"); + response.print(""); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildAdvancedConfigHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildAdvancedConfigHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - _response.concat("
"); - _response.concat("

Advanced Configuration

"); - _response.concat("

Warning: Changing these settings can lead to bootloops that might require you to erase the ESP32 and reflash nukihub using USB/serial

"); - _response.concat(""); - _response.concat(""); - printCheckBox("WEBLOG", "Enable WebSerial logging", _preferences->getBool(preference_webserial_enabled), ""); - printCheckBox("BTLPRST", "Enable Bootloop prevention (Try to reset these settings to default on bootloop)", true, ""); - printInputField("BUFFSIZE", "Char buffer size (min 4096, max 32768)", _preferences->getInt(preference_buffer_size, CHAR_BUFFER_SIZE), 6, ""); - _response.concat(""); - printInputField("TSKNTWK", "Task size Network (min 12288, max 32768)", _preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), 6, ""); - _response.concat(""); - printInputField("TSKNUKI", "Task size Nuki (min 8192, max 32768)", _preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), 6, ""); - printInputField("ALMAX", "Max auth log entries (min 1, max 50)", _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 3, "id=\"inputmaxauthlog\""); - printInputField("KPMAX", "Max keypad entries (min 1, max 100)", _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD), 3, "id=\"inputmaxkeypad\""); - printInputField("TCMAX", "Max timecontrol entries (min 1, max 50)", _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL), 3, "id=\"inputmaxtimecontrol\""); - printInputField("AUTHMAX", "Max authorization entries (min 1, max 50)", _preferences->getInt(preference_auth_max_entries, MAX_AUTH), 3, "id=\"inputmaxauth\""); - printCheckBox("SHOWSECRETS", "Show Pairing secrets on Info page", _preferences->getBool(preference_show_secrets), ""); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print(""); + response.print("

Advanced Configuration

"); + response.print("

Warning: Changing these settings can lead to bootloops that might require you to erase the ESP32 and reflash nukihub using USB/serial

"); + response.print("
Current bootloop prevention state"); - _response.concat(_preferences->getBool(preference_enable_bootloop_reset, false) ? "Enabled" : "Disabled"); - _response.concat("
Advised minimum char buffer size based on current settings
Advised minimum network task size based on current settings
"); + response.print(""); + printCheckBox(&response, "WEBLOG", "Enable WebSerial logging", _preferences->getBool(preference_webserial_enabled), ""); + 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.print(""); + printInputField(&response, "TSKNTWK", "Task size Network (min 12288, max 32768)", _preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), 6, ""); + response.print(""); + 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, "id=\"inputmaxauthlog\""); + printInputField(&response, "KPMAX", "Max keypad entries (min 1, max 100)", _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD), 3, "id=\"inputmaxkeypad\""); + printInputField(&response, "TCMAX", "Max timecontrol entries (min 1, max 50)", _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL), 3, "id=\"inputmaxtimecontrol\""); + printInputField(&response, "AUTHMAX", "Max authorization entries (min 1, max 50)", _preferences->getInt(preference_auth_max_entries, MAX_AUTH), 3, "id=\"inputmaxauth\""); + printCheckBox(&response, "SHOWSECRETS", "Show Pairing secrets on Info page", _preferences->getBool(preference_show_secrets), ""); if(_preferences->getBool(preference_lock_enabled, true)) { - printCheckBox("LCKMANPAIR", "Manually set lock pairing data (enable to save values below)", false, ""); - printInputField("LCKBLEADDR", "currentBleAddress", "", 12, ""); - printInputField("LCKSECRETK", "secretKeyK", "", 64, ""); - printInputField("LCKAUTHID", "authorizationId", "", 8, ""); + 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(_preferences->getBool(preference_opener_enabled, false)) { - printCheckBox("OPNMANPAIR", "Manually set opener pairing data (enable to save values below)", false, ""); - printInputField("OPNBLEADDR", "currentBleAddress", "", 12, ""); - printInputField("OPNSECRETK", "secretKeyK", "", 64, ""); - printInputField("OPNAUTHID", "authorizationId", "", 8, ""); + 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("OTAUPD", "Custom URL to update Nuki Hub updater", "", 255, ""); - printInputField("OTAMAIN", "Custom URL to update Nuki Hub", "", 255, ""); - _response.concat("
Current bootloop prevention state"); + response.print(_preferences->getBool(preference_enable_bootloop_reset, false) ? "Enabled" : "Disabled"); + response.print("
Advised minimum char buffer size based on current settings
Advised minimum network task size based on current settings
"); + printInputField(&response, "OTAUPD", "Custom URL to update Nuki Hub updater", "", 255, ""); + printInputField(&response, "OTAMAIN", "Custom URL to update Nuki Hub", "", 255, ""); + response.print(""); - _response.concat("
"); - _response.concat("
"); - _response.concat(""); - sendResponse(request); + response.print("
"); + response.print(""); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildStatusHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildStatusHtml(PsychicRequest *request) { - _response = ""; JsonDocument json; - char _resbuf[2048]; + String jsonStr; bool mqttDone = false; bool lockDone = false; bool openerDone = false; @@ -2843,7 +3574,10 @@ void WebCfgServer::buildStatusHtml(AsyncWebServerRequest *request) json["mqttState"] = "Yes"; mqttDone = true; } - else json["mqttState"] = "No"; + else + { + json["mqttState"] = "No"; + } if(_nuki != nullptr) { @@ -2857,11 +3591,20 @@ void WebCfgServer::buildStatusHtml(AsyncWebServerRequest *request) if(_nuki->isPaired()) { json["lockPin"] = pinStateToString(_preferences->getInt(preference_lock_pin_status, 4)); - if(strcmp(lockStateArr, "undefined") != 0) lockDone = true; + if(strcmp(lockStateArr, "undefined") != 0) + { + lockDone = true; + } + } + else + { + json["lockPin"] = "Not Paired"; } - else json["lockPin"] = "Not Paired"; } - else lockDone = true; + else + { + lockDone = true; + } if(_nukiOpener != nullptr) { char openerStateArr[20]; @@ -2870,77 +3613,99 @@ void WebCfgServer::buildStatusHtml(AsyncWebServerRequest *request) String openerPaired = (_nukiOpener->isPaired() ? ("Yes (BLE Address " + _nukiOpener->getBleAddress().toString() + ")").c_str() : "No"); json["openerPaired"] = openerPaired; - if(_nukiOpener->keyTurnerState().nukiState == NukiOpener::State::ContinuousMode) json["openerState"] = "Open (Continuous Mode)"; - else json["openerState"] = openerState; + if(_nukiOpener->keyTurnerState().nukiState == NukiOpener::State::ContinuousMode) + { + json["openerState"] = "Open (Continuous Mode)"; + } + else + { + json["openerState"] = openerState; + } if(_nukiOpener->isPaired()) { json["openerPin"] = pinStateToString(_preferences->getInt(preference_opener_pin_status, 4)); - if(strcmp(openerStateArr, "undefined") != 0) openerDone = true; + if(strcmp(openerStateArr, "undefined") != 0) + { + openerDone = true; + } + } + else + { + json["openerPin"] = "Not Paired"; } - else json["openerPin"] = "Not Paired"; } - else openerDone = true; + else + { + openerDone = true; + } if(_preferences->getBool(preference_check_updates)) { json["latestFirmware"] = _preferences->getString(preference_latest_version); latestDone = true; } - else latestDone = true; + else + { + latestDone = true; + } - if(mqttDone && lockDone && openerDone && latestDone) json["stop"] = 1; + if(mqttDone && lockDone && openerDone && latestDone) + { + json["stop"] = 1; + } - serializeJson(json, _resbuf, sizeof(_resbuf)); - _response.concat(_resbuf); - sendResponse(request); + serializeJson(json, jsonStr); + return request->reply(200, "application/json", jsonStr.c_str()); } -String WebCfgServer::pinStateToString(uint8_t value) { +String WebCfgServer::pinStateToString(uint8_t value) +{ switch(value) { - case 0: - return (String)"PIN not set"; - case 1: - return (String)"PIN valid"; - case 2: - return (String)"PIN set but invalid";; - default: - return (String)"Unknown"; + case 0: + return String("PIN not set"); + case 1: + return String("PIN valid"); + case 2: + return String("PIN set but invalid"); + default: + return String("Unknown"); } } -void WebCfgServer::buildAccLvlHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildAccLvlHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); - _response.concat("
"); - _response.concat(""); - _response.concat("

Nuki General Access Control

"); - _response.concat(""); - printCheckBox("CONFPUB", "Publish Nuki configuration information", _preferences->getBool(preference_conf_info_enabled, true), ""); + response.print(""); + response.print(""); + response.print("

Nuki General Access Control

"); + response.print("
SettingEnabled
"); + printCheckBox(&response, "CONFPUB", "Publish Nuki configuration information", _preferences->getBool(preference_conf_info_enabled, true), ""); if((_nuki != nullptr && _nuki->hasKeypad()) || (_nukiOpener != nullptr && _nukiOpener->hasKeypad())) { - printCheckBox("KPPUB", "Publish keypad entries information", _preferences->getBool(preference_keypad_info_enabled), ""); - printCheckBox("KPPER", "Publish a topic per keypad entry and create HA sensor", _preferences->getBool(preference_keypad_topic_per_entry), ""); - printCheckBox("KPCODE", "Also publish keypad codes (Disadvised for security reasons)", _preferences->getBool(preference_keypad_publish_code, false), ""); - printCheckBox("KPCHECK", "Allow checking if keypad codes are valid (Disadvised for security reasons)", _preferences->getBool(preference_keypad_check_code_enabled, false), ""); - printCheckBox("KPENA", "Add, modify and delete keypad codes", _preferences->getBool(preference_keypad_control_enabled), ""); + 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, "KPENA", "Add, modify and delete keypad codes", _preferences->getBool(preference_keypad_control_enabled), ""); + printCheckBox(&response, "KPCHECK", "Allow checking if keypad codes are valid (Disadvised for security reasons)", _preferences->getBool(preference_keypad_check_code_enabled, false), ""); } - printCheckBox("TCPUB", "Publish time control entries information", _preferences->getBool(preference_timecontrol_info_enabled), ""); - printCheckBox("TCPER", "Publish a topic per time control entry and create HA sensor", _preferences->getBool(preference_timecontrol_topic_per_entry), ""); - printCheckBox("TCENA", "Add, modify and delete time control entries", _preferences->getBool(preference_timecontrol_control_enabled), ""); - printCheckBox("AUTHPUB", "Publish authorization entries information", _preferences->getBool(preference_auth_info_enabled), ""); - printCheckBox("AUTHPER", "Publish a topic per authorization entry and create HA sensor", _preferences->getBool(preference_auth_topic_per_entry), ""); - printCheckBox("AUTHENA", "Modify and delete authorization entries", _preferences->getBool(preference_auth_control_enabled), ""); - printCheckBox("PUBAUTH", "Publish authorization log", _preferences->getBool(preference_publish_authdata), ""); - _response.concat("
SettingEnabled

"); - _response.concat("
"); + printCheckBox(&response, "TCPUB", "Publish time control entries information", _preferences->getBool(preference_timecontrol_info_enabled), ""); + printCheckBox(&response, "TCPER", "Publish a topic per time control entry and create HA sensor", _preferences->getBool(preference_timecontrol_topic_per_entry), ""); + printCheckBox(&response, "TCENA", "Add, modify and delete time control entries", _preferences->getBool(preference_timecontrol_control_enabled), ""); + printCheckBox(&response, "AUTHPUB", "Publish authorization entries information", _preferences->getBool(preference_auth_info_enabled), ""); + printCheckBox(&response, "AUTHPER", "Publish a topic per authorization entry and create HA sensor", _preferences->getBool(preference_auth_topic_per_entry), ""); + printCheckBox(&response, "AUTHENA", "Modify and delete authorization entries", _preferences->getBool(preference_auth_control_enabled), ""); + printCheckBox(&response, "PUBAUTH", "Publish authorization log", _preferences->getBool(preference_publish_authdata), ""); + response.print("
"); + response.print("
"); if(_nuki != nullptr) { @@ -2949,72 +3714,72 @@ void WebCfgServer::buildAccLvlHtml(AsyncWebServerRequest *request) uint32_t advancedLockConfigAclPrefs[22]; _preferences->getBytes(preference_conf_lock_advanced_acl, &advancedLockConfigAclPrefs, sizeof(advancedLockConfigAclPrefs)); - _response.concat("

Nuki Lock Access Control

"); - _response.concat(""); - _response.concat(""); - _response.concat(""); + response.print("

Nuki Lock Access Control

"); + response.print(""); + response.print(""); + response.print("
ActionAllowed
"); - printCheckBox("ACLLCKLCK", "Lock", ((int)aclPrefs[0] == 1), "chk_access_lock"); - printCheckBox("ACLLCKUNLCK", "Unlock", ((int)aclPrefs[1] == 1), "chk_access_lock"); - printCheckBox("ACLLCKUNLTCH", "Unlatch", ((int)aclPrefs[2] == 1), "chk_access_lock"); - printCheckBox("ACLLCKLNG", "Lock N Go", ((int)aclPrefs[3] == 1), "chk_access_lock"); - printCheckBox("ACLLCKLNGU", "Lock N Go Unlatch", ((int)aclPrefs[4] == 1), "chk_access_lock"); - printCheckBox("ACLLCKFLLCK", "Full Lock", ((int)aclPrefs[5] == 1), "chk_access_lock"); - printCheckBox("ACLLCKFOB1", "Fob Action 1", ((int)aclPrefs[6] == 1), "chk_access_lock"); - printCheckBox("ACLLCKFOB2", "Fob Action 2", ((int)aclPrefs[7] == 1), "chk_access_lock"); - printCheckBox("ACLLCKFOB3", "Fob Action 3", ((int)aclPrefs[8] == 1), "chk_access_lock"); - _response.concat("
ActionAllowed

"); + printCheckBox(&response, "ACLLCKLCK", "Lock", ((int)aclPrefs[0] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKUNLCK", "Unlock", ((int)aclPrefs[1] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKUNLTCH", "Unlatch", ((int)aclPrefs[2] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKLNG", "Lock N Go", ((int)aclPrefs[3] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKLNGU", "Lock N Go Unlatch", ((int)aclPrefs[4] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKFLLCK", "Full Lock", ((int)aclPrefs[5] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKFOB1", "Fob Action 1", ((int)aclPrefs[6] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKFOB2", "Fob Action 2", ((int)aclPrefs[7] == 1), "chk_access_lock"); + printCheckBox(&response, "ACLLCKFOB3", "Fob Action 3", ((int)aclPrefs[8] == 1), "chk_access_lock"); + response.print("
"); - _response.concat("

Nuki Lock Config Control (Requires PIN to be set)

"); - _response.concat(""); - _response.concat(""); - _response.concat(""); + response.print("

Nuki Lock Config Control (Requires PIN to be set)

"); + response.print(""); + response.print(""); + response.print("
ChangeAllowed
"); - printCheckBox("CONFLCKNAME", "Name", ((int)basicLockConfigAclPrefs[0] == 1), "chk_config_lock"); - printCheckBox("CONFLCKLAT", "Latitude", ((int)basicLockConfigAclPrefs[1] == 1), "chk_config_lock"); - printCheckBox("CONFLCKLONG", "Longitude", ((int)basicLockConfigAclPrefs[2] == 1), "chk_config_lock"); - printCheckBox("CONFLCKAUNL", "Auto unlatch", ((int)basicLockConfigAclPrefs[3] == 1), "chk_config_lock"); - printCheckBox("CONFLCKPRENA", "Pairing enabled", ((int)basicLockConfigAclPrefs[4] == 1), "chk_config_lock"); - printCheckBox("CONFLCKBTENA", "Button enabled", ((int)basicLockConfigAclPrefs[5] == 1), "chk_config_lock"); - printCheckBox("CONFLCKLEDENA", "LED flash enabled", ((int)basicLockConfigAclPrefs[6] == 1), "chk_config_lock"); - printCheckBox("CONFLCKLEDBR", "LED brightness", ((int)basicLockConfigAclPrefs[7] == 1), "chk_config_lock"); - printCheckBox("CONFLCKTZOFF", "Timezone offset", ((int)basicLockConfigAclPrefs[8] == 1), "chk_config_lock"); - printCheckBox("CONFLCKDSTM", "DST mode", ((int)basicLockConfigAclPrefs[9] == 1), "chk_config_lock"); - printCheckBox("CONFLCKFOB1", "Fob Action 1", ((int)basicLockConfigAclPrefs[10] == 1), "chk_config_lock"); - printCheckBox("CONFLCKFOB2", "Fob Action 2", ((int)basicLockConfigAclPrefs[11] == 1), "chk_config_lock"); - printCheckBox("CONFLCKFOB3", "Fob Action 3", ((int)basicLockConfigAclPrefs[12] == 1), "chk_config_lock"); - printCheckBox("CONFLCKSGLLCK", "Single Lock", ((int)basicLockConfigAclPrefs[13] == 1), "chk_config_lock"); - printCheckBox("CONFLCKADVM", "Advertising Mode", ((int)basicLockConfigAclPrefs[14] == 1), "chk_config_lock"); - printCheckBox("CONFLCKTZID", "Timezone ID", ((int)basicLockConfigAclPrefs[15] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNAME", "Name", ((int)basicLockConfigAclPrefs[0] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKLAT", "Latitude", ((int)basicLockConfigAclPrefs[1] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKLONG", "Longitude", ((int)basicLockConfigAclPrefs[2] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKAUNL", "Auto unlatch", ((int)basicLockConfigAclPrefs[3] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKPRENA", "Pairing enabled", ((int)basicLockConfigAclPrefs[4] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKBTENA", "Button enabled", ((int)basicLockConfigAclPrefs[5] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKLEDENA", "LED flash enabled", ((int)basicLockConfigAclPrefs[6] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKLEDBR", "LED brightness", ((int)basicLockConfigAclPrefs[7] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKTZOFF", "Timezone offset", ((int)basicLockConfigAclPrefs[8] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKDSTM", "DST mode", ((int)basicLockConfigAclPrefs[9] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKFOB1", "Fob Action 1", ((int)basicLockConfigAclPrefs[10] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKFOB2", "Fob Action 2", ((int)basicLockConfigAclPrefs[11] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKFOB3", "Fob Action 3", ((int)basicLockConfigAclPrefs[12] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKSGLLCK", "Single Lock", ((int)basicLockConfigAclPrefs[13] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKADVM", "Advertising Mode", ((int)basicLockConfigAclPrefs[14] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKTZID", "Timezone ID", ((int)basicLockConfigAclPrefs[15] == 1), "chk_config_lock"); - printCheckBox("CONFLCKUPOD", "Unlocked Position Offset Degrees", ((int)advancedLockConfigAclPrefs[0] == 1), "chk_config_lock"); - printCheckBox("CONFLCKLPOD", "Locked Position Offset Degrees", ((int)advancedLockConfigAclPrefs[1] == 1), "chk_config_lock"); - printCheckBox("CONFLCKSLPOD", "Single Locked Position Offset Degrees", ((int)advancedLockConfigAclPrefs[2] == 1), "chk_config_lock"); - printCheckBox("CONFLCKUTLTOD", "Unlocked To Locked Transition Offset Degrees", ((int)advancedLockConfigAclPrefs[3] == 1), "chk_config_lock"); - printCheckBox("CONFLCKLNGT", "Lock n Go timeout", ((int)advancedLockConfigAclPrefs[4] == 1), "chk_config_lock"); - printCheckBox("CONFLCKSBPA", "Single button press action", ((int)advancedLockConfigAclPrefs[5] == 1), "chk_config_lock"); - printCheckBox("CONFLCKDBPA", "Double button press action", ((int)advancedLockConfigAclPrefs[6] == 1), "chk_config_lock"); - printCheckBox("CONFLCKDC", "Detached cylinder", ((int)advancedLockConfigAclPrefs[7] == 1), "chk_config_lock"); - printCheckBox("CONFLCKBATT", "Battery type", ((int)advancedLockConfigAclPrefs[8] == 1), "chk_config_lock"); - printCheckBox("CONFLCKABTD", "Automatic battery type detection", ((int)advancedLockConfigAclPrefs[9] == 1), "chk_config_lock"); - printCheckBox("CONFLCKUNLD", "Unlatch duration", ((int)advancedLockConfigAclPrefs[10] == 1), "chk_config_lock"); - printCheckBox("CONFLCKALT", "Auto lock timeout", ((int)advancedLockConfigAclPrefs[11] == 1), "chk_config_lock"); - printCheckBox("CONFLCKAUNLD", "Auto unlock disabled", ((int)advancedLockConfigAclPrefs[12] == 1), "chk_config_lock"); - printCheckBox("CONFLCKNMENA", "Nightmode enabled", ((int)advancedLockConfigAclPrefs[13] == 1), "chk_config_lock"); - printCheckBox("CONFLCKNMST", "Nightmode start time", ((int)advancedLockConfigAclPrefs[14] == 1), "chk_config_lock"); - printCheckBox("CONFLCKNMET", "Nightmode end time", ((int)advancedLockConfigAclPrefs[15] == 1), "chk_config_lock"); - printCheckBox("CONFLCKNMALENA", "Nightmode auto lock enabled", ((int)advancedLockConfigAclPrefs[16] == 1), "chk_config_lock"); - printCheckBox("CONFLCKNMAULD", "Nightmode auto unlock disabled", ((int)advancedLockConfigAclPrefs[17] == 1), "chk_config_lock"); - printCheckBox("CONFLCKNMLOS", "Nightmode immediate lock on start", ((int)advancedLockConfigAclPrefs[18] == 1), "chk_config_lock"); - printCheckBox("CONFLCKALENA", "Auto lock enabled", ((int)advancedLockConfigAclPrefs[19] == 1), "chk_config_lock"); - printCheckBox("CONFLCKIALENA", "Immediate auto lock enabled", ((int)advancedLockConfigAclPrefs[20] == 1), "chk_config_lock"); - printCheckBox("CONFLCKAUENA", "Auto update enabled", ((int)advancedLockConfigAclPrefs[21] == 1), "chk_config_lock"); - _response.concat("
ChangeAllowed

"); - _response.concat("
"); + printCheckBox(&response, "CONFLCKUPOD", "Unlocked Position Offset Degrees", ((int)advancedLockConfigAclPrefs[0] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKLPOD", "Locked Position Offset Degrees", ((int)advancedLockConfigAclPrefs[1] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKSLPOD", "Single Locked Position Offset Degrees", ((int)advancedLockConfigAclPrefs[2] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKUTLTOD", "Unlocked To Locked Transition Offset Degrees", ((int)advancedLockConfigAclPrefs[3] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKLNGT", "Lock n Go timeout", ((int)advancedLockConfigAclPrefs[4] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKSBPA", "Single button press action", ((int)advancedLockConfigAclPrefs[5] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKDBPA", "Double button press action", ((int)advancedLockConfigAclPrefs[6] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKDC", "Detached cylinder", ((int)advancedLockConfigAclPrefs[7] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKBATT", "Battery type", ((int)advancedLockConfigAclPrefs[8] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKABTD", "Automatic battery type detection", ((int)advancedLockConfigAclPrefs[9] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKUNLD", "Unlatch duration", ((int)advancedLockConfigAclPrefs[10] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKALT", "Auto lock timeout", ((int)advancedLockConfigAclPrefs[11] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKAUNLD", "Auto unlock disabled", ((int)advancedLockConfigAclPrefs[12] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNMENA", "Nightmode enabled", ((int)advancedLockConfigAclPrefs[13] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNMST", "Nightmode start time", ((int)advancedLockConfigAclPrefs[14] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNMET", "Nightmode end time", ((int)advancedLockConfigAclPrefs[15] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNMALENA", "Nightmode auto lock enabled", ((int)advancedLockConfigAclPrefs[16] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNMAULD", "Nightmode auto unlock disabled", ((int)advancedLockConfigAclPrefs[17] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKNMLOS", "Nightmode immediate lock on start", ((int)advancedLockConfigAclPrefs[18] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKALENA", "Auto lock enabled", ((int)advancedLockConfigAclPrefs[19] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKIALENA", "Immediate auto lock enabled", ((int)advancedLockConfigAclPrefs[20] == 1), "chk_config_lock"); + printCheckBox(&response, "CONFLCKAUENA", "Auto update enabled", ((int)advancedLockConfigAclPrefs[21] == 1), "chk_config_lock"); + response.print("
"); + response.print("
"); } if(_nukiOpener != nullptr) { @@ -3023,116 +3788,130 @@ void WebCfgServer::buildAccLvlHtml(AsyncWebServerRequest *request) uint32_t advancedOpenerConfigAclPrefs[20]; _preferences->getBytes(preference_conf_opener_advanced_acl, &advancedOpenerConfigAclPrefs, sizeof(advancedOpenerConfigAclPrefs)); - _response.concat("

Nuki Opener Access Control

"); - _response.concat(""); - _response.concat(""); - _response.concat(""); + response.print("

Nuki Opener Access Control

"); + response.print(""); + response.print(""); + response.print("
ActionAllowed
"); - printCheckBox("ACLOPNUNLCK", "Activate Ring-to-Open", ((int)aclPrefs[9] == 1), "chk_access_opener"); - printCheckBox("ACLOPNLCK", "Deactivate Ring-to-Open", ((int)aclPrefs[10] == 1), "chk_access_opener"); - printCheckBox("ACLOPNUNLTCH", "Electric Strike Actuation", ((int)aclPrefs[11] == 1), "chk_access_opener"); - printCheckBox("ACLOPNUNLCKCM", "Activate Continuous Mode", ((int)aclPrefs[12] == 1), "chk_access_opener"); - printCheckBox("ACLOPNLCKCM", "Deactivate Continuous Mode", ((int)aclPrefs[13] == 1), "chk_access_opener"); - printCheckBox("ACLOPNFOB1", "Fob Action 1", ((int)aclPrefs[14] == 1), "chk_access_opener"); - printCheckBox("ACLOPNFOB2", "Fob Action 2", ((int)aclPrefs[15] == 1), "chk_access_opener"); - printCheckBox("ACLOPNFOB3", "Fob Action 3", ((int)aclPrefs[16] == 1), "chk_access_opener"); - _response.concat("
ActionAllowed

"); + printCheckBox(&response, "ACLOPNUNLCK", "Activate Ring-to-Open", ((int)aclPrefs[9] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNLCK", "Deactivate Ring-to-Open", ((int)aclPrefs[10] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNUNLTCH", "Electric Strike Actuation", ((int)aclPrefs[11] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNUNLCKCM", "Activate Continuous Mode", ((int)aclPrefs[12] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNLCKCM", "Deactivate Continuous Mode", ((int)aclPrefs[13] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNFOB1", "Fob Action 1", ((int)aclPrefs[14] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNFOB2", "Fob Action 2", ((int)aclPrefs[15] == 1), "chk_access_opener"); + printCheckBox(&response, "ACLOPNFOB3", "Fob Action 3", ((int)aclPrefs[16] == 1), "chk_access_opener"); + response.print("
"); - _response.concat("

Nuki Opener Config Control (Requires PIN to be set)

"); - _response.concat(""); - _response.concat(""); - _response.concat(""); + response.print("

Nuki Opener Config Control (Requires PIN to be set)

"); + response.print(""); + response.print(""); + response.print("
ChangeAllowed
"); - printCheckBox("CONFOPNNAME", "Name", ((int)basicOpenerConfigAclPrefs[0] == 1), "chk_config_opener"); - printCheckBox("CONFOPNLAT", "Latitude", ((int)basicOpenerConfigAclPrefs[1] == 1), "chk_config_opener"); - printCheckBox("CONFOPNLONG", "Longitude", ((int)basicOpenerConfigAclPrefs[2] == 1), "chk_config_opener"); - printCheckBox("CONFOPNPRENA", "Pairing enabled", ((int)basicOpenerConfigAclPrefs[3] == 1), "chk_config_opener"); - printCheckBox("CONFOPNBTENA", "Button enabled", ((int)basicOpenerConfigAclPrefs[4] == 1), "chk_config_opener"); - printCheckBox("CONFOPNLEDENA", "LED flash enabled", ((int)basicOpenerConfigAclPrefs[5] == 1), "chk_config_opener"); - printCheckBox("CONFOPNTZOFF", "Timezone offset", ((int)basicOpenerConfigAclPrefs[6] == 1), "chk_config_opener"); - printCheckBox("CONFOPNDSTM", "DST mode", ((int)basicOpenerConfigAclPrefs[7] == 1), "chk_config_opener"); - printCheckBox("CONFOPNFOB1", "Fob Action 1", ((int)basicOpenerConfigAclPrefs[8] == 1), "chk_config_opener"); - printCheckBox("CONFOPNFOB2", "Fob Action 2", ((int)basicOpenerConfigAclPrefs[9] == 1), "chk_config_opener"); - printCheckBox("CONFOPNFOB3", "Fob Action 3", ((int)basicOpenerConfigAclPrefs[10] == 1), "chk_config_opener"); - printCheckBox("CONFOPNOPM", "Operating Mode", ((int)basicOpenerConfigAclPrefs[11] == 1), "chk_config_opener"); - printCheckBox("CONFOPNADVM", "Advertising Mode", ((int)basicOpenerConfigAclPrefs[12] == 1), "chk_config_opener"); - printCheckBox("CONFOPNTZID", "Timezone ID", ((int)basicOpenerConfigAclPrefs[13] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNNAME", "Name", ((int)basicOpenerConfigAclPrefs[0] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNLAT", "Latitude", ((int)basicOpenerConfigAclPrefs[1] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNLONG", "Longitude", ((int)basicOpenerConfigAclPrefs[2] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNPRENA", "Pairing enabled", ((int)basicOpenerConfigAclPrefs[3] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNBTENA", "Button enabled", ((int)basicOpenerConfigAclPrefs[4] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNLEDENA", "LED flash enabled", ((int)basicOpenerConfigAclPrefs[5] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNTZOFF", "Timezone offset", ((int)basicOpenerConfigAclPrefs[6] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNDSTM", "DST mode", ((int)basicOpenerConfigAclPrefs[7] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNFOB1", "Fob Action 1", ((int)basicOpenerConfigAclPrefs[8] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNFOB2", "Fob Action 2", ((int)basicOpenerConfigAclPrefs[9] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNFOB3", "Fob Action 3", ((int)basicOpenerConfigAclPrefs[10] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNOPM", "Operating Mode", ((int)basicOpenerConfigAclPrefs[11] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNADVM", "Advertising Mode", ((int)basicOpenerConfigAclPrefs[12] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNTZID", "Timezone ID", ((int)basicOpenerConfigAclPrefs[13] == 1), "chk_config_opener"); - printCheckBox("CONFOPNICID", "Intercom ID", ((int)advancedOpenerConfigAclPrefs[0] == 1), "chk_config_opener"); - printCheckBox("CONFOPNBUSMS", "BUS mode Switch", ((int)advancedOpenerConfigAclPrefs[1] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSCDUR", "Short Circuit Duration", ((int)advancedOpenerConfigAclPrefs[2] == 1), "chk_config_opener"); - printCheckBox("CONFOPNESD", "Eletric Strike Delay", ((int)advancedOpenerConfigAclPrefs[3] == 1), "chk_config_opener"); - printCheckBox("CONFOPNRESD", "Random Electric Strike Delay", ((int)advancedOpenerConfigAclPrefs[4] == 1), "chk_config_opener"); - printCheckBox("CONFOPNESDUR", "Electric Strike Duration", ((int)advancedOpenerConfigAclPrefs[5] == 1), "chk_config_opener"); - printCheckBox("CONFOPNDRTOAR", "Disable RTO after ring", ((int)advancedOpenerConfigAclPrefs[6] == 1), "chk_config_opener"); - printCheckBox("CONFOPNRTOT", "RTO timeout", ((int)advancedOpenerConfigAclPrefs[7] == 1), "chk_config_opener"); - printCheckBox("CONFOPNDRBSUP", "Doorbell suppression", ((int)advancedOpenerConfigAclPrefs[8] == 1), "chk_config_opener"); - printCheckBox("CONFOPNDRBSUPDUR", "Doorbell suppression duration", ((int)advancedOpenerConfigAclPrefs[9] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSRING", "Sound Ring", ((int)advancedOpenerConfigAclPrefs[10] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSOPN", "Sound Open", ((int)advancedOpenerConfigAclPrefs[11] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSRTO", "Sound RTO", ((int)advancedOpenerConfigAclPrefs[12] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSCM", "Sound CM", ((int)advancedOpenerConfigAclPrefs[13] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSCFRM", "Sound confirmation", ((int)advancedOpenerConfigAclPrefs[14] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSLVL", "Sound level", ((int)advancedOpenerConfigAclPrefs[15] == 1), "chk_config_opener"); - printCheckBox("CONFOPNSBPA", "Single button press action", ((int)advancedOpenerConfigAclPrefs[16] == 1), "chk_config_opener"); - printCheckBox("CONFOPNDBPA", "Double button press action", ((int)advancedOpenerConfigAclPrefs[17] == 1), "chk_config_opener"); - printCheckBox("CONFOPNBATT", "Battery type", ((int)advancedOpenerConfigAclPrefs[18] == 1), "chk_config_opener"); - printCheckBox("CONFOPNABTD", "Automatic battery type detection", ((int)advancedOpenerConfigAclPrefs[19] == 1), "chk_config_opener"); - _response.concat("
ChangeAllowed

"); - _response.concat("
"); + printCheckBox(&response, "CONFOPNICID", "Intercom ID", ((int)advancedOpenerConfigAclPrefs[0] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNBUSMS", "BUS mode Switch", ((int)advancedOpenerConfigAclPrefs[1] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSCDUR", "Short Circuit Duration", ((int)advancedOpenerConfigAclPrefs[2] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNESD", "Eletric Strike Delay", ((int)advancedOpenerConfigAclPrefs[3] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNRESD", "Random Electric Strike Delay", ((int)advancedOpenerConfigAclPrefs[4] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNESDUR", "Electric Strike Duration", ((int)advancedOpenerConfigAclPrefs[5] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNDRTOAR", "Disable RTO after ring", ((int)advancedOpenerConfigAclPrefs[6] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNRTOT", "RTO timeout", ((int)advancedOpenerConfigAclPrefs[7] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNDRBSUP", "Doorbell suppression", ((int)advancedOpenerConfigAclPrefs[8] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNDRBSUPDUR", "Doorbell suppression duration", ((int)advancedOpenerConfigAclPrefs[9] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSRING", "Sound Ring", ((int)advancedOpenerConfigAclPrefs[10] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSOPN", "Sound Open", ((int)advancedOpenerConfigAclPrefs[11] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSRTO", "Sound RTO", ((int)advancedOpenerConfigAclPrefs[12] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSCM", "Sound CM", ((int)advancedOpenerConfigAclPrefs[13] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSCFRM", "Sound confirmation", ((int)advancedOpenerConfigAclPrefs[14] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSLVL", "Sound level", ((int)advancedOpenerConfigAclPrefs[15] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNSBPA", "Single button press action", ((int)advancedOpenerConfigAclPrefs[16] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNDBPA", "Double button press action", ((int)advancedOpenerConfigAclPrefs[17] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNBATT", "Battery type", ((int)advancedOpenerConfigAclPrefs[18] == 1), "chk_config_opener"); + printCheckBox(&response, "CONFOPNABTD", "Automatic battery type detection", ((int)advancedOpenerConfigAclPrefs[19] == 1), "chk_config_opener"); + response.print("
"); + response.print("
"); } - _response.concat("
"); - _response.concat(""); - sendResponse(request); + response.print(""); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildNukiConfigHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildNukiConfigHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - _response.concat("
"); - _response.concat("

Basic Nuki Configuration

"); - _response.concat(""); - printCheckBox("LOCKENA", "Nuki Lock enabled", _preferences->getBool(preference_lock_enabled), ""); - if(_preferences->getBool(preference_lock_enabled)) printInputField("MQTTPATH", "MQTT Nuki Lock Path", _preferences->getString(preference_mqtt_lock_path).c_str(), 180, ""); - printCheckBox("OPENA", "Nuki Opener enabled", _preferences->getBool(preference_opener_enabled), ""); - if(_preferences->getBool(preference_opener_enabled)) printInputField("MQTTOPPATH", "MQTT Nuki Opener Path", _preferences->getString(preference_mqtt_opener_path).c_str(), 180, ""); - _response.concat("

"); - _response.concat("

Advanced Nuki Configuration

"); - _response.concat(""); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print(""); + response.print("

Basic Nuki Configuration

"); + response.print("
"); + printCheckBox(&response, "LOCKENA", "Nuki Lock enabled", _preferences->getBool(preference_lock_enabled), ""); + if(_preferences->getBool(preference_lock_enabled)) + { + printInputField(&response, "MQTTPATH", "MQTT Nuki Lock Path", _preferences->getString(preference_mqtt_lock_path).c_str(), 180, ""); + } + printCheckBox(&response, "OPENA", "Nuki Opener enabled", _preferences->getBool(preference_opener_enabled), ""); + if(_preferences->getBool(preference_opener_enabled)) + { + printInputField(&response, "MQTTOPPATH", "MQTT Nuki Opener Path", _preferences->getString(preference_mqtt_opener_path).c_str(), 180, ""); + } + response.print("

"); + response.print("

Advanced Nuki Configuration

"); + response.print(""); - printInputField("LSTINT", "Query interval lock state (seconds)", _preferences->getInt(preference_query_interval_lockstate), 10, ""); - printInputField("CFGINT", "Query interval configuration (seconds)", _preferences->getInt(preference_query_interval_configuration), 10, ""); - printInputField("BATINT", "Query interval battery (seconds)", _preferences->getInt(preference_query_interval_battery), 10, ""); + printInputField(&response, "LSTINT", "Query interval lock state (seconds)", _preferences->getInt(preference_query_interval_lockstate), 10, ""); + printInputField(&response, "CFGINT", "Query interval configuration (seconds)", _preferences->getInt(preference_query_interval_configuration), 10, ""); + printInputField(&response, "BATINT", "Query interval battery (seconds)", _preferences->getInt(preference_query_interval_battery), 10, ""); if((_nuki != nullptr && _nuki->hasKeypad()) || (_nukiOpener != nullptr && _nukiOpener->hasKeypad())) { - printInputField("KPINT", "Query interval keypad (seconds)", _preferences->getInt(preference_query_interval_keypad), 10, ""); + printInputField(&response, "KPINT", "Query interval keypad (seconds)", _preferences->getInt(preference_query_interval_keypad), 10, ""); } - printInputField("NRTRY", "Number of retries if command failed", _preferences->getInt(preference_command_nr_of_retries), 10, ""); - printInputField("TRYDLY", "Delay between retries (milliseconds)", _preferences->getInt(preference_command_retry_delay), 10, ""); - if(_preferences->getBool(preference_lock_enabled, true)) printCheckBox("REGAPP", "Lock: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_as_app), ""); - if(_preferences->getBool(preference_opener_enabled, false)) printCheckBox("REGAPPOPN", "Opener: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_opener_as_app), ""); - printInputField("RSBC", "Restart if bluetooth beacons not received (seconds; -1 to disable)", _preferences->getInt(preference_restart_ble_beacon_lost), 10, ""); - printInputField("TXPWR", "BLE transmit power in dB (minimum -12, maximum 9)", _preferences->getInt(preference_ble_tx_power, 9), 10, ""); + printInputField(&response, "NRTRY", "Number of retries if command failed", _preferences->getInt(preference_command_nr_of_retries), 10, ""); + printInputField(&response, "TRYDLY", "Delay between retries (milliseconds)", _preferences->getInt(preference_command_retry_delay), 10, ""); + if(_preferences->getBool(preference_lock_enabled, true)) + { + printCheckBox(&response, "REGAPP", "Lock: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_as_app), ""); + } + if(_preferences->getBool(preference_opener_enabled, false)) + { + printCheckBox(&response, "REGAPPOPN", "Opener: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_opener_as_app), ""); + } + printInputField(&response, "RSBC", "Restart if bluetooth beacons not received (seconds; -1 to disable)", _preferences->getInt(preference_restart_ble_beacon_lost), 10, ""); + printInputField(&response, "TXPWR", "BLE transmit power in dB (minimum -12, maximum 9)", _preferences->getInt(preference_ble_tx_power, 9), 10, ""); - _response.concat("
"); - _response.concat("
"); - _response.concat("
"); - _response.concat(""); - sendResponse(request); + response.print(""); + response.print("
"); + response.print(""); + response.print(""); + return response.endSend(); } -void WebCfgServer::buildGpioConfigHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildGpioConfigHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - _response.concat("
"); - _response.concat("

GPIO Configuration

"); - _response.concat(""); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print(""); + response.print("

GPIO Configuration

"); + response.print("
"); std::vector> options; String gpiopreselects = "var gpio = []; "; @@ -3143,7 +3922,7 @@ void WebCfgServer::buildGpioConfigHtml(AsyncWebServerRequest *request) { String pinStr = String(pin); String pinDesc = "Gpio " + pinStr; - printDropDown(pinStr.c_str(), pinDesc.c_str(), "", options, "gpioselect"); + printDropDown(&response, pinStr.c_str(), pinDesc.c_str(), "", options, "gpioselect"); if(std::find(disabledPins.begin(), disabledPins.end(), pin) != disabledPins.end()) { gpiopreselects.concat("gpio[" + pinStr + "] = '21';"); @@ -3154,423 +3933,443 @@ void WebCfgServer::buildGpioConfigHtml(AsyncWebServerRequest *request) } } - _response.concat("
"); - _response.concat("
"); - _response.concat("
"); + response.print(""); + response.print("
"); + response.print(""); options = getGpioOptions(); - _response.concat(""); - _response.concat(""); - sendResponse(request); + response.print("'; var gpioselects = document.getElementsByClassName('gpioselect'); for (let i = 0; i < gpioselects.length; i++) { gpioselects[i].options.length = 0; gpioselects[i].innerHTML = gpiooptions; gpioselects[i].value = gpio[gpioselects[i].name]; if(gpioselects[i].value == 21) { gpioselects[i].disabled = true; } }"); + response.print(""); + return response.endSend(); } #ifndef CONFIG_IDF_TARGET_ESP32H2 -void WebCfgServer::buildConfigureWifiHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildConfigureWifiHtml(PsychicRequest *request) { - _response = ""; - buildHtmlHeader(); - _response.concat("

Wi-Fi

"); - _response.concat("Click confirm to restart ESP into Wi-Fi configuration mode. After restart, connect to ESP access point to reconfigure Wi-Fi.

"); - buildNavigationButton("Confirm", "/wifimanager"); - _response.concat(""); - sendResponse(request); + PsychicStreamResponse response(request, "text/plain"); + response.beginSend(); + buildHtmlHeader(&response); + response.print("

Wi-Fi

"); + response.print("Click confirm to remove saved WiFi settings and restart ESP into Wi-Fi configuration mode. After restart, connect to ESP access point to reconfigure Wi-Fi.

"); + buildNavigationButton(&response, "Confirm", "/wifimanager"); + response.print(""); + return response.endSend(); } #endif -void WebCfgServer::buildInfoHtml(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) { - _response = ""; uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); - buildHtmlHeader(); - _response.concat("

System Information

");
-    _response.concat("------------ NUKI HUB ------------");
-    _response.concat("\nVersion: ");
-    _response.concat(NUKI_HUB_VERSION);
-    _response.concat("\nBuild: ");
-    _response.concat(NUKI_HUB_BUILD);
-    #ifndef DEBUG_NUKIHUB
-    _response.concat("\nBuild type: Release");
-    #else
-    _response.concat("\nBuild type: Debug");
-    #endif
-    _response.concat("\nBuild date: ");
-    _response.concat(NUKI_HUB_DATE);
-    _response.concat("\nUpdater version: ");
-    _response.concat(_preferences->getString(preference_updater_version, ""));
-    _response.concat("\nUpdater build: ");
-    _response.concat(_preferences->getString(preference_updater_build, ""));
-    _response.concat("\nUpdater build date: ");
-    _response.concat(_preferences->getString(preference_updater_date, ""));
-    _response.concat("\nUptime (min): ");
-    _response.concat(esp_timer_get_time() / 1000 / 1000 / 60);
-    _response.concat("\nConfig version: ");
-    _response.concat(_preferences->getInt(preference_config_version));
-    _response.concat("\nLast restart reason FW: ");
-    _response.concat(getRestartReason());
-    _response.concat("\nLast restart reason ESP: ");
-    _response.concat(getEspRestartReason());
-    _response.concat("\nFree internal heap: ");
-    _response.concat(ESP.getFreeHeap());
-    _response.concat("\nTotal internal heap: ");
-    _response.concat(ESP.getHeapSize());
-    #ifdef CONFIG_SOC_SPIRAM_SUPPORTED
+    PsychicStreamResponse response(request, "text/plain");
+    response.beginSend();
+    buildHtmlHeader(&response);
+    response.print("

System Information

");
+    response.print("------------ NUKI HUB ------------");
+    response.print("\nVersion: ");
+    response.print(NUKI_HUB_VERSION);
+    response.print("\nBuild: ");
+    response.print(NUKI_HUB_BUILD);
+#ifndef DEBUG_NUKIHUB
+    response.print("\nBuild type: Release");
+#else
+    response.print("\nBuild type: Debug");
+#endif
+    response.print("\nBuild date: ");
+    response.print(NUKI_HUB_DATE);
+    response.print("\nUpdater version: ");
+    response.print(_preferences->getString(preference_updater_version, ""));
+    response.print("\nUpdater build: ");
+    response.print(_preferences->getString(preference_updater_build, ""));
+    response.print("\nUpdater build date: ");
+    response.print(_preferences->getString(preference_updater_date, ""));
+    response.print("\nUptime (min): ");
+    response.print(espMillis() / 1000 / 60);
+    response.print("\nConfig version: ");
+    response.print(_preferences->getInt(preference_config_version));
+    response.print("\nLast restart reason FW: ");
+    response.print(getRestartReason());
+    response.print("\nLast restart reason ESP: ");
+    response.print(getEspRestartReason());
+    response.print("\nFree internal heap: ");
+    response.print(ESP.getFreeHeap());
+    response.print("\nTotal internal heap: ");
+    response.print(ESP.getHeapSize());
+#ifdef CONFIG_SOC_SPIRAM_SUPPORTED
     if(esp_psram_get_size() > 0)
     {
-        _response.concat("\nPSRAM Available: Yes");
-        _response.concat("\nTotal PSRAM: ");
-        _response.concat(esp_psram_get_size());
-        _response.concat("\nFree PSRAM: ");
-        _response.concat((esp_get_free_heap_size() - ESP.getFreeHeap()));
-        _response.concat("\nTotal free heap: ");
-        _response.concat(esp_get_free_heap_size());
+        response.print("\nPSRAM Available: Yes");
+        response.print("\nTotal PSRAM: ");
+        response.print(esp_psram_get_size());
+        response.print("\nFree PSRAM: ");
+        response.print((esp_get_free_heap_size() - ESP.getFreeHeap()));
+        response.print("\nTotal free heap: ");
+        response.print(esp_get_free_heap_size());
     }
     else
     {
-        _response.concat("\nPSRAM Available: No");
+        response.print("\nPSRAM Available: No");
     }
-    #else
-    _response.concat("\nPSRAM Available: No");
-    #endif
-    _response.concat("\nNetwork task stack high watermark: ");
-    _response.concat(uxTaskGetStackHighWaterMark(networkTaskHandle));
-    _response.concat("\nNuki task stack high watermark: ");
-    _response.concat(uxTaskGetStackHighWaterMark(nukiTaskHandle));
-    _response.concat("\n\n------------ GENERAL SETTINGS ------------");
-    _response.concat("\nNetwork task stack size: ");
-    _response.concat(_preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE));
-    _response.concat("\nNuki task stack size: ");
-    _response.concat(_preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE));
-    _response.concat("\nCheck for updates: ");
-    _response.concat(_preferences->getBool(preference_check_updates, false) ? "Yes" : "No");
-    _response.concat("\nLatest version: ");
-    _response.concat(_preferences->getString(preference_latest_version, ""));
-    _response.concat("\nAllow update from MQTT: ");
-    _response.concat(_preferences->getBool(preference_update_from_mqtt, false) ? "Yes" : "No");
-    _response.concat("\nWeb configurator username: ");
-    _response.concat(_preferences->getString(preference_cred_user, "").length() > 0 ? "***" : "Not set");
-    _response.concat("\nWeb configurator password: ");
-    _response.concat(_preferences->getString(preference_cred_password, "").length() > 0 ? "***" : "Not set");
-    _response.concat("\nWeb configurator enabled: ");
-    _response.concat(_preferences->getBool(preference_webserver_enabled, true) ? "Yes" : "No");
-    _response.concat("\nPublish debug information enabled: ");
-    _response.concat(_preferences->getBool(preference_publish_debug_info, false) ? "Yes" : "No");
-    _response.concat("\nMQTT log enabled: ");
-    _response.concat(_preferences->getBool(preference_mqtt_log_enabled, false) ? "Yes" : "No");
-    _response.concat("\nWebserial enabled: ");
-    _response.concat(_preferences->getBool(preference_webserial_enabled, false) ? "Yes" : "No");
-    _response.concat("\nBootloop protection enabled: ");
-    _response.concat(_preferences->getBool(preference_enable_bootloop_reset, false) ? "Yes" : "No");
-    _response.concat("\n\n------------ NETWORK ------------");
-    _response.concat("\nNetwork device: ");
-    _response.concat(_network->networkDeviceName());
-    _response.concat("\nNetwork connected: ");
-    _response.concat(_network->isConnected() ? "Yes" : "No");
+#else
+    response.print("\nPSRAM Available: No");
+#endif
+    response.print("\nNetwork task stack high watermark: ");
+    response.print(uxTaskGetStackHighWaterMark(networkTaskHandle));
+    response.print("\nNuki task stack high watermark: ");
+    response.print(uxTaskGetStackHighWaterMark(nukiTaskHandle));
+    response.print("\n\n------------ GENERAL SETTINGS ------------");
+    response.print("\nNetwork task stack size: ");
+    response.print(_preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE));
+    response.print("\nNuki task stack size: ");
+    response.print(_preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE));
+    response.print("\nCheck for updates: ");
+    response.print(_preferences->getBool(preference_check_updates, false) ? "Yes" : "No");
+    response.print("\nLatest version: ");
+    response.print(_preferences->getString(preference_latest_version, ""));
+    response.print("\nAllow update from MQTT: ");
+    response.print(_preferences->getBool(preference_update_from_mqtt, false) ? "Yes" : "No");
+    response.print("\nWeb configurator username: ");
+    response.print(_preferences->getString(preference_cred_user, "").length() > 0 ? "***" : "Not set");
+    response.print("\nWeb configurator password: ");
+    response.print(_preferences->getString(preference_cred_password, "").length() > 0 ? "***" : "Not set");
+    response.print("\nWeb configurator enabled: ");
+    response.print(_preferences->getBool(preference_webserver_enabled, true) ? "Yes" : "No");
+    response.print("\nPublish debug information enabled: ");
+    response.print(_preferences->getBool(preference_publish_debug_info, false) ? "Yes" : "No");
+    response.print("\nMQTT log enabled: ");
+    response.print(_preferences->getBool(preference_mqtt_log_enabled, false) ? "Yes" : "No");
+    response.print("\nWebserial enabled: ");
+    response.print(_preferences->getBool(preference_webserial_enabled, false) ? "Yes" : "No");
+    response.print("\nBootloop protection enabled: ");
+    response.print(_preferences->getBool(preference_enable_bootloop_reset, false) ? "Yes" : "No");
+    response.print("\n\n------------ NETWORK ------------");
+    response.print("\nNetwork device: ");
+    response.print(_network->networkDeviceName());
+    response.print("\nNetwork connected: ");
+    response.print(_network->isConnected() ? "Yes" : "No");
     if(_network->isConnected())
     {
-        _response.concat("\nIP Address: ");
-        _response.concat(_network->localIP());
+        response.print("\nIP Address: ");
+        response.print(_network->localIP());
 
         if(_network->networkDeviceName() == "Built-in Wi-Fi")
         {
-            #ifndef CONFIG_IDF_TARGET_ESP32H2
-            _response.concat("\nSSID: ");
-            _response.concat(WiFi.SSID());
-            _response.concat("\nBSSID of AP: ");
-            _response.concat(_network->networkBSSID());
-            _response.concat("\nESP32 MAC address: ");
-            _response.concat(WiFi.macAddress());
-            #endif
+#ifndef CONFIG_IDF_TARGET_ESP32H2
+            response.print("\nSSID: ");
+            response.print(WiFi.SSID());
+            response.print("\nBSSID of AP: ");
+            response.print(_network->networkBSSID());
+            response.print("\nESP32 MAC address: ");
+            response.print(WiFi.macAddress());
+#endif
         }
         else
         {
             //Ethernet info
         }
     }
-    _response.concat("\n\n------------ NETWORK SETTINGS ------------");
-    _response.concat("\nNuki Hub hostname: ");
-    _response.concat(_preferences->getString(preference_hostname, ""));
-    if(_preferences->getBool(preference_ip_dhcp_enabled, true)) _response.concat("\nDHCP enabled: Yes");
+    response.print("\n\n------------ NETWORK SETTINGS ------------");
+    response.print("\nNuki Hub hostname: ");
+    response.print(_preferences->getString(preference_hostname, ""));
+    if(_preferences->getBool(preference_ip_dhcp_enabled, true))
+    {
+        response.print("\nDHCP enabled: Yes");
+    }
     else
     {
-        _response.concat("\nDHCP enabled: No");
-        _response.concat("\nStatic IP address: ");
-        _response.concat(_preferences->getString(preference_ip_address, ""));
-        _response.concat("\nStatic IP subnet: ");
-        _response.concat(_preferences->getString(preference_ip_subnet, ""));
-        _response.concat("\nStatic IP gateway: ");
-        _response.concat(_preferences->getString(preference_ip_gateway, ""));
-        _response.concat("\nStatic IP DNS server: ");
-        _response.concat(_preferences->getString(preference_ip_dns_server, ""));
+        response.print("\nDHCP enabled: No");
+        response.print("\nStatic IP address: ");
+        response.print(_preferences->getString(preference_ip_address, ""));
+        response.print("\nStatic IP subnet: ");
+        response.print(_preferences->getString(preference_ip_subnet, ""));
+        response.print("\nStatic IP gateway: ");
+        response.print(_preferences->getString(preference_ip_gateway, ""));
+        response.print("\nStatic IP DNS server: ");
+        response.print(_preferences->getString(preference_ip_dns_server, ""));
     }
 
-    #ifndef CONFIG_IDF_TARGET_ESP32H2
-    _response.concat("\nFallback to Wi-Fi / Wi-Fi config portal disabled: ");
-    _response.concat(_preferences->getBool(preference_network_wifi_fallback_disabled, false) ? "Yes" : "No");
+#ifndef CONFIG_IDF_TARGET_ESP32H2
     if(_network->networkDeviceName() == "Built-in Wi-Fi")
     {
-        _response.concat("\nConnect to AP with the best signal enabled: ");
-        _response.concat(_preferences->getBool(preference_find_best_rssi, false) ? "Yes" : "No");
-        _response.concat("\nRSSI Publish interval (s): ");
+        response.print("\nRSSI Publish interval (s): ");
 
-        if(_preferences->getInt(preference_rssi_publish_interval, 60) < 0) _response.concat("Disabled");
-        else _response.concat(_preferences->getInt(preference_rssi_publish_interval, 60));
+        if(_preferences->getInt(preference_rssi_publish_interval, 60) < 0)
+        {
+            response.print("Disabled");
+        }
+        else
+        {
+            response.print(_preferences->getInt(preference_rssi_publish_interval, 60));
+        }
     }
-    #endif
-    _response.concat("\nRestart ESP32 on network disconnect enabled: ");
-    _response.concat(_preferences->getBool(preference_restart_on_disconnect, false) ? "Yes" : "No");
-    _response.concat("\nReconnect network on MQTT connection failure enabled: ");
-    _response.concat(_preferences->getBool(preference_recon_netw_on_mqtt_discon, false) ? "Yes" : "No");
-    _response.concat("\nMQTT Timeout until restart (s): ");
-    if(_preferences->getInt(preference_network_timeout, 60) < 0) _response.concat("Disabled");
-    else _response.concat(_preferences->getInt(preference_network_timeout, 60));
-    _response.concat("\n\n------------ MQTT ------------");
-    _response.concat("\nMQTT connected: ");
-    _response.concat(_network->mqttConnectionState() > 0 ? "Yes" : "No");
-    _response.concat("\nMQTT broker address: ");
-    _response.concat(_preferences->getString(preference_mqtt_broker, ""));
-    _response.concat("\nMQTT broker port: ");
-    _response.concat(_preferences->getInt(preference_mqtt_broker_port, 1883));
-    _response.concat("\nMQTT username: ");
-    _response.concat(_preferences->getString(preference_mqtt_user, "").length() > 0 ? "***" : "Not set");
-    _response.concat("\nMQTT password: ");
-    _response.concat(_preferences->getString(preference_mqtt_password, "").length() > 0 ? "***" : "Not set");
+#endif
+    response.print("\nRestart ESP32 on network disconnect enabled: ");
+    response.print(_preferences->getBool(preference_restart_on_disconnect, false) ? "Yes" : "No");
+    response.print("\nMQTT Timeout until restart (s): ");
+    if(_preferences->getInt(preference_network_timeout, 60) < 0)
+    {
+        response.print("Disabled");
+    }
+    else
+    {
+        response.print(_preferences->getInt(preference_network_timeout, 60));
+    }
+    response.print("\n\n------------ MQTT ------------");
+    response.print("\nMQTT connected: ");
+    response.print(_network->mqttConnectionState() > 0 ? "Yes" : "No");
+    response.print("\nMQTT broker address: ");
+    response.print(_preferences->getString(preference_mqtt_broker, ""));
+    response.print("\nMQTT broker port: ");
+    response.print(_preferences->getInt(preference_mqtt_broker_port, 1883));
+    response.print("\nMQTT username: ");
+    response.print(_preferences->getString(preference_mqtt_user, "").length() > 0 ? "***" : "Not set");
+    response.print("\nMQTT password: ");
+    response.print(_preferences->getString(preference_mqtt_password, "").length() > 0 ? "***" : "Not set");
     if(_preferences->getBool(preference_lock_enabled, true))
     {
-        _response.concat("\nMQTT lock base topic: ");
-        _response.concat(_preferences->getString(preference_mqtt_lock_path, ""));
+        response.print("\nMQTT lock base topic: ");
+        response.print(_preferences->getString(preference_mqtt_lock_path, ""));
     }
     if(_preferences->getBool(preference_opener_enabled, false))
     {
-        _response.concat("\nMQTT opener base topic: ");
-        _response.concat(_preferences->getString(preference_mqtt_lock_path, ""));
+        response.print("\nMQTT opener base topic: ");
+        response.print(_preferences->getString(preference_mqtt_lock_path, ""));
     }
-    _response.concat("\nMQTT SSL CA: ");
-    _response.concat(_preferences->getString(preference_mqtt_ca, "").length() > 0 ? "***" : "Not set");
-    _response.concat("\nMQTT SSL CRT: ");
-    _response.concat(_preferences->getString(preference_mqtt_crt, "").length() > 0 ? "***" : "Not set");
-    _response.concat("\nMQTT SSL Key: ");
-    _response.concat(_preferences->getString(preference_mqtt_key, "").length() > 0 ? "***" : "Not set");
-    _response.concat("\n\n------------ BLUETOOTH ------------");
-    _response.concat("\nBluetooth TX power (dB): ");
-    _response.concat(_preferences->getInt(preference_ble_tx_power, 9));
-    _response.concat("\nBluetooth command nr of retries: ");
-    _response.concat(_preferences->getInt(preference_command_nr_of_retries, 3));
-    _response.concat("\nBluetooth command retry delay (ms): ");
-    _response.concat(_preferences->getInt(preference_command_retry_delay, 100));
-    _response.concat("\nSeconds until reboot when no BLE beacons recieved: ");
-    _response.concat(_preferences->getInt(preference_restart_ble_beacon_lost, 60));
-    _response.concat("\n\n------------ QUERY / PUBLISH SETTINGS ------------");
-    _response.concat("\nLock/Opener state query interval (s): ");
-    _response.concat(_preferences->getInt(preference_query_interval_lockstate, 1800));
-    _response.concat("\nPublish Nuki device authorization log: ");
-    _response.concat(_preferences->getBool(preference_publish_authdata, false) ? "Yes" : "No");
-    _response.concat("\nMax authorization log entries to retrieve: ");
-    _response.concat(_preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG));
-    _response.concat("\nBattery state query interval (s): ");
-    _response.concat(_preferences->getInt(preference_query_interval_battery, 1800));
-    _response.concat("\nMost non-JSON MQTT topics disabled: ");
-    _response.concat(_preferences->getBool(preference_disable_non_json, false) ? "Yes" : "No");
-    _response.concat("\nPublish Nuki device config: ");
-    _response.concat(_preferences->getBool(preference_conf_info_enabled, false) ? "Yes" : "No");
-    _response.concat("\nConfig query interval (s): ");
-    _response.concat(_preferences->getInt(preference_query_interval_configuration, 3600));
-    _response.concat("\nPublish Keypad info: ");
-    _response.concat(_preferences->getBool(preference_keypad_info_enabled, false) ? "Yes" : "No");
-    _response.concat("\nKeypad query interval (s): ");
-    _response.concat(_preferences->getInt(preference_query_interval_keypad, 1800));
-    _response.concat("\nEnable Keypad control: ");
-    _response.concat(_preferences->getBool(preference_keypad_control_enabled, false) ? "Yes" : "No");
-    _response.concat("\nPublish Keypad topic per entry: ");
-    _response.concat(_preferences->getBool(preference_keypad_topic_per_entry, false) ? "Yes" : "No");
-    _response.concat("\nPublish Keypad codes: ");
-    _response.concat(_preferences->getBool(preference_keypad_publish_code, false) ? "Yes" : "No");
-    _response.concat("\nAllow checking Keypad codes: ");
-    _response.concat(_preferences->getBool(preference_keypad_check_code_enabled, false) ? "Yes" : "No");
-    _response.concat("\nMax keypad entries to retrieve: ");
-    _response.concat(_preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD));
-    _response.concat("\nPublish timecontrol info: ");
-    _response.concat(_preferences->getBool(preference_timecontrol_info_enabled, false) ? "Yes" : "No");
-    _response.concat("\nKeypad query interval (s): ");
-    _response.concat(_preferences->getInt(preference_query_interval_keypad, 1800));
-    _response.concat("\nEnable timecontrol control: ");
-    _response.concat(_preferences->getBool(preference_timecontrol_control_enabled, false) ? "Yes" : "No");
-    _response.concat("\nPublish timecontrol topic per entry: ");
-    _response.concat(_preferences->getBool(preference_timecontrol_topic_per_entry, false) ? "Yes" : "No");
-    _response.concat("\nMax timecontrol entries to retrieve: ");
-    _response.concat(_preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL));
-    _response.concat("\n\n------------ HOME ASSISTANT ------------");
-    _response.concat("\nHome Assistant auto discovery enabled: ");
+    response.print("\nMQTT SSL CA: ");
+    response.print(_preferences->getString(preference_mqtt_ca, "").length() > 0 ? "***" : "Not set");
+    response.print("\nMQTT SSL CRT: ");
+    response.print(_preferences->getString(preference_mqtt_crt, "").length() > 0 ? "***" : "Not set");
+    response.print("\nMQTT SSL Key: ");
+    response.print(_preferences->getString(preference_mqtt_key, "").length() > 0 ? "***" : "Not set");
+    response.print("\n\n------------ BLUETOOTH ------------");
+    response.print("\nBluetooth TX power (dB): ");
+    response.print(_preferences->getInt(preference_ble_tx_power, 9));
+    response.print("\nBluetooth command nr of retries: ");
+    response.print(_preferences->getInt(preference_command_nr_of_retries, 3));
+    response.print("\nBluetooth command retry delay (ms): ");
+    response.print(_preferences->getInt(preference_command_retry_delay, 100));
+    response.print("\nSeconds until reboot when no BLE beacons recieved: ");
+    response.print(_preferences->getInt(preference_restart_ble_beacon_lost, 60));
+    response.print("\n\n------------ QUERY / PUBLISH SETTINGS ------------");
+    response.print("\nLock/Opener state query interval (s): ");
+    response.print(_preferences->getInt(preference_query_interval_lockstate, 1800));
+    response.print("\nPublish Nuki device authorization log: ");
+    response.print(_preferences->getBool(preference_publish_authdata, false) ? "Yes" : "No");
+    response.print("\nMax authorization log entries to retrieve: ");
+    response.print(_preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG));
+    response.print("\nBattery state query interval (s): ");
+    response.print(_preferences->getInt(preference_query_interval_battery, 1800));
+    response.print("\nMost non-JSON MQTT topics disabled: ");
+    response.print(_preferences->getBool(preference_disable_non_json, false) ? "Yes" : "No");
+    response.print("\nPublish Nuki device config: ");
+    response.print(_preferences->getBool(preference_conf_info_enabled, false) ? "Yes" : "No");
+    response.print("\nConfig query interval (s): ");
+    response.print(_preferences->getInt(preference_query_interval_configuration, 3600));
+    response.print("\nPublish Keypad info: ");
+    response.print(_preferences->getBool(preference_keypad_info_enabled, false) ? "Yes" : "No");
+    response.print("\nKeypad query interval (s): ");
+    response.print(_preferences->getInt(preference_query_interval_keypad, 1800));
+    response.print("\nEnable Keypad control: ");
+    response.print(_preferences->getBool(preference_keypad_control_enabled, false) ? "Yes" : "No");
+    response.print("\nPublish Keypad topic per entry: ");
+    response.print(_preferences->getBool(preference_keypad_topic_per_entry, false) ? "Yes" : "No");
+    response.print("\nPublish Keypad codes: ");
+    response.print(_preferences->getBool(preference_keypad_publish_code, false) ? "Yes" : "No");
+    response.print("\nAllow checking Keypad codes: ");
+    response.print(_preferences->getBool(preference_keypad_check_code_enabled, false) ? "Yes" : "No");
+    response.print("\nMax keypad entries to retrieve: ");
+    response.print(_preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD));
+    response.print("\nPublish timecontrol info: ");
+    response.print(_preferences->getBool(preference_timecontrol_info_enabled, false) ? "Yes" : "No");
+    response.print("\nKeypad query interval (s): ");
+    response.print(_preferences->getInt(preference_query_interval_keypad, 1800));
+    response.print("\nEnable timecontrol control: ");
+    response.print(_preferences->getBool(preference_timecontrol_control_enabled, false) ? "Yes" : "No");
+    response.print("\nPublish timecontrol topic per entry: ");
+    response.print(_preferences->getBool(preference_timecontrol_topic_per_entry, false) ? "Yes" : "No");
+    response.print("\nMax timecontrol entries to retrieve: ");
+    response.print(_preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL));
+    response.print("\n\n------------ HOME ASSISTANT ------------");
+    response.print("\nHome Assistant auto discovery enabled: ");
     if(_preferences->getString(preference_mqtt_hass_discovery, "").length() > 0)
     {
-        _response.concat("Yes");
-        _response.concat("\nHome Assistant auto discovery topic: ");
-        _response.concat(_preferences->getString(preference_mqtt_hass_discovery, "") + "/");
-        _response.concat("\nNuki Hub configuration URL for HA: ");
-        _response.concat(_preferences->getString(preference_mqtt_hass_cu_url, "").length() > 0 ? _preferences->getString(preference_mqtt_hass_cu_url, "") : "http://" + _network->localIP());
+        response.print("Yes");
+        response.print("\nHome Assistant auto discovery topic: ");
+        response.print(_preferences->getString(preference_mqtt_hass_discovery, "") + "/");
+        response.print("\nNuki Hub configuration URL for HA: ");
+        response.print(_preferences->getString(preference_mqtt_hass_cu_url, "").length() > 0 ? _preferences->getString(preference_mqtt_hass_cu_url, "") : "http://" + _network->localIP());
     }
-    else _response.concat("No");
-    _response.concat("\n\n------------ NUKI LOCK ------------");
-    if(_nuki == nullptr || !_preferences->getBool(preference_lock_enabled, true)) _response.concat("\nLock enabled: No");
     else
     {
-        _response.concat("\nLock enabled: Yes");
-        _response.concat("\nPaired: ");
-        _response.concat(_nuki->isPaired() ? "Yes" : "No");
-        _response.concat("\nNuki Hub device ID: ");
-        _response.concat(_preferences->getUInt(preference_device_id_lock, 0));
-        _response.concat("\nNuki device ID: ");
-        _response.concat(_preferences->getUInt(preference_nuki_id_lock, 0) > 0 ? "***" : "Not set");
-        _response.concat("\nFirmware version: ");
-        _response.concat(_nuki->firmwareVersion().c_str());
-        _response.concat("\nHardware version: ");
-        _response.concat(_nuki->hardwareVersion().c_str());
-        _response.concat("\nValid PIN set: ");
-        _response.concat(_nuki->isPaired() ? _nuki->isPinValid() ? "Yes" : "No" : "-");
-        _response.concat("\nHas door sensor: ");
-        _response.concat(_nuki->hasDoorSensor() ? "Yes" : "No");
-        _response.concat("\nHas keypad: ");
-        _response.concat(_nuki->hasKeypad() ? "Yes" : "No");
+        response.print("No");
+    }
+    response.print("\n\n------------ NUKI LOCK ------------");
+    if(_nuki == nullptr || !_preferences->getBool(preference_lock_enabled, true))
+    {
+        response.print("\nLock enabled: No");
+    }
+    else
+    {
+        response.print("\nLock enabled: Yes");
+        response.print("\nPaired: ");
+        response.print(_nuki->isPaired() ? "Yes" : "No");
+        response.print("\nNuki Hub device ID: ");
+        response.print(_preferences->getUInt(preference_device_id_lock, 0));
+        response.print("\nNuki device ID: ");
+        response.print(_preferences->getUInt(preference_nuki_id_lock, 0) > 0 ? "***" : "Not set");
+        response.print("\nFirmware version: ");
+        response.print(_nuki->firmwareVersion().c_str());
+        response.print("\nHardware version: ");
+        response.print(_nuki->hardwareVersion().c_str());
+        response.print("\nValid PIN set: ");
+        response.print(_nuki->isPaired() ? _nuki->isPinValid() ? "Yes" : "No" : "-");
+        response.print("\nHas door sensor: ");
+        response.print(_nuki->hasDoorSensor() ? "Yes" : "No");
+        response.print("\nHas keypad: ");
+        response.print(_nuki->hasKeypad() ? "Yes" : "No");
         if(_nuki->hasKeypad())
         {
-            _response.concat("\nKeypad highest entries count: ");
-            _response.concat(_preferences->getInt(preference_lock_max_keypad_code_count, 0));
+            response.print("\nKeypad highest entries count: ");
+            response.print(_preferences->getInt(preference_lock_max_keypad_code_count, 0));
+        }
+        response.print("\nTimecontrol highest entries count: ");
+        response.print(_preferences->getInt(preference_lock_max_timecontrol_entry_count, 0));
+        response.print("\nRegister as: ");
+        response.print(_preferences->getBool(preference_register_as_app, false) ? "App" : "Bridge");
+        response.print("\n\n------------ HYBRID MODE ------------");
+        if(!_preferences->getBool(preference_official_hybrid_enabled, false))
+        {
+            response.print("\nHybrid mode enabled: No");
         }
-        _response.concat("\nTimecontrol highest entries count: ");
-        _response.concat(_preferences->getInt(preference_lock_max_timecontrol_entry_count, 0));
-        _response.concat("\nRegister as: ");
-        _response.concat(_preferences->getBool(preference_register_as_app, false) ? "App" : "Bridge");
-        _response.concat("\n\n------------ HYBRID MODE ------------");
-        if(!_preferences->getBool(preference_official_hybrid_enabled, false)) _response.concat("\nHybrid mode enabled: No");
         else
         {
-            _response.concat("\nHybrid mode enabled: Yes");
-            _response.concat("\nHybrid mode connected: ");
-            _response.concat(_nuki->offConnected() ? "Yes": "No");
-            _response.concat("\nSending actions through official MQTT enabled: ");
-            _response.concat(_preferences->getBool(preference_official_hybrid_actions, false) ? "Yes" : "No");
+            response.print("\nHybrid mode enabled: Yes");
+            response.print("\nHybrid mode connected: ");
+            response.print(_nuki->offConnected() ? "Yes": "No");
+            response.print("\nSending actions through official MQTT enabled: ");
+            response.print(_preferences->getBool(preference_official_hybrid_actions, false) ? "Yes" : "No");
             /* NOT IMPLEMENTED (YET?)
             if(_preferences->getBool(preference_official_hybrid_actions, false))
             {
-                _response.concat("\nRetry actions through BLE enabled: ");
-                _response.concat(_preferences->getBool(preference_official_hybrid_retry, false) ? "Yes" : "No");
+                response.print("\nRetry actions through BLE enabled: ");
+                response.print(_preferences->getBool(preference_official_hybrid_retry, false) ? "Yes" : "No");
             }
             */
-            _response.concat("\nTime between status updates when official MQTT is offline (s): ");
-            _response.concat(_preferences->getInt(preference_query_interval_hybrid_lockstate, 600));
+            response.print("\nTime between status updates when official MQTT is offline (s): ");
+            response.print(_preferences->getInt(preference_query_interval_hybrid_lockstate, 600));
         }
         uint32_t basicLockConfigAclPrefs[16];
         _preferences->getBytes(preference_conf_lock_basic_acl, &basicLockConfigAclPrefs, sizeof(basicLockConfigAclPrefs));
         uint32_t advancedLockConfigAclPrefs[22];
         _preferences->getBytes(preference_conf_lock_advanced_acl, &advancedLockConfigAclPrefs, sizeof(advancedLockConfigAclPrefs));
-        _response.concat("\n\n------------ NUKI LOCK ACL ------------");
-        _response.concat("\nLock: ");
-        _response.concat((int)aclPrefs[0] ? "Allowed" : "Disallowed");
-        _response.concat("\nUnlock: ");
-        _response.concat((int)aclPrefs[1] ? "Allowed" : "Disallowed");
-        _response.concat("\nUnlatch: ");
-        _response.concat((int)aclPrefs[2] ? "Allowed" : "Disallowed");
-        _response.concat("\nLock N Go: ");
-        _response.concat((int)aclPrefs[3] ? "Allowed" : "Disallowed");
-        _response.concat("\nLock N Go Unlatch: ");
-        _response.concat((int)aclPrefs[4] ? "Allowed" : "Disallowed");
-        _response.concat("\nFull Lock: ");
-        _response.concat((int)aclPrefs[5] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 1: ");
-        _response.concat((int)aclPrefs[6] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 2: ");
-        _response.concat((int)aclPrefs[7] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 3: ");
-        _response.concat((int)aclPrefs[8] ? "Allowed" : "Disallowed");
-        _response.concat("\n\n------------ NUKI LOCK CONFIG ACL ------------");
-        _response.concat("\nName: ");
-        _response.concat((int)basicLockConfigAclPrefs[0] ? "Allowed" : "Disallowed");
-        _response.concat("\nLatitude: ");
-        _response.concat((int)basicLockConfigAclPrefs[1] ? "Allowed" : "Disallowed");
-        _response.concat("\nLongitude: ");
-        _response.concat((int)basicLockConfigAclPrefs[2] ? "Allowed" : "Disallowed");
-        _response.concat("\nAuto Unlatch: ");
-        _response.concat((int)basicLockConfigAclPrefs[3] ? "Allowed" : "Disallowed");
-        _response.concat("\nPairing enabled: ");
-        _response.concat((int)basicLockConfigAclPrefs[4] ? "Allowed" : "Disallowed");
-        _response.concat("\nButton enabled: ");
-        _response.concat((int)basicLockConfigAclPrefs[5] ? "Allowed" : "Disallowed");
-        _response.concat("\nLED flash enabled: ");
-        _response.concat((int)basicLockConfigAclPrefs[6] ? "Allowed" : "Disallowed");
-        _response.concat("\nLED brightness: ");
-        _response.concat((int)basicLockConfigAclPrefs[7] ? "Allowed" : "Disallowed");
-        _response.concat("\nTimezone offset: ");
-        _response.concat((int)basicLockConfigAclPrefs[8] ? "Allowed" : "Disallowed");
-        _response.concat("\nDST mode: ");
-        _response.concat((int)basicLockConfigAclPrefs[9] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 1: ");
-        _response.concat((int)basicLockConfigAclPrefs[10] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 2: ");
-        _response.concat((int)basicLockConfigAclPrefs[11] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 3: ");
-        _response.concat((int)basicLockConfigAclPrefs[12] ? "Allowed" : "Disallowed");
-        _response.concat("\nSingle Lock: ");
-        _response.concat((int)basicLockConfigAclPrefs[13] ? "Allowed" : "Disallowed");
-        _response.concat("\nAdvertising Mode: ");
-        _response.concat((int)basicLockConfigAclPrefs[14] ? "Allowed" : "Disallowed");
-        _response.concat("\nTimezone ID: ");
-        _response.concat((int)basicLockConfigAclPrefs[15] ? "Allowed" : "Disallowed");
-        _response.concat("\nUnlocked Position Offset Degrees: ");
-        _response.concat((int)advancedLockConfigAclPrefs[0] ? "Allowed" : "Disallowed");
-        _response.concat("\nLocked Position Offset Degrees: ");
-        _response.concat((int)advancedLockConfigAclPrefs[1] ? "Allowed" : "Disallowed");
-        _response.concat("\nSingle Locked Position Offset Degrees: ");
-        _response.concat((int)advancedLockConfigAclPrefs[2] ? "Allowed" : "Disallowed");
-        _response.concat("\nUnlocked To Locked Transition Offset Degrees: ");
-        _response.concat((int)advancedLockConfigAclPrefs[3] ? "Allowed" : "Disallowed");
-        _response.concat("\nLock n Go timeout: ");
-        _response.concat((int)advancedLockConfigAclPrefs[4] ? "Allowed" : "Disallowed");
-        _response.concat("\nSingle button press action: ");
-        _response.concat((int)advancedLockConfigAclPrefs[5] ? "Allowed" : "Disallowed");
-        _response.concat("\nDouble button press action: ");
-        _response.concat((int)advancedLockConfigAclPrefs[6] ? "Allowed" : "Disallowed");
-        _response.concat("\nDetached cylinder: ");
-        _response.concat((int)advancedLockConfigAclPrefs[7] ? "Allowed" : "Disallowed");
-        _response.concat("\nBattery type: ");
-        _response.concat((int)advancedLockConfigAclPrefs[8] ? "Allowed" : "Disallowed");
-        _response.concat("\nAutomatic battery type detection: ");
-        _response.concat((int)advancedLockConfigAclPrefs[9] ? "Allowed" : "Disallowed");
-        _response.concat("\nUnlatch duration: ");
-        _response.concat((int)advancedLockConfigAclPrefs[10] ? "Allowed" : "Disallowed");
-        _response.concat("\nAuto lock timeout: ");
-        _response.concat((int)advancedLockConfigAclPrefs[11] ? "Allowed" : "Disallowed");
-        _response.concat("\nAuto unlock disabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[12] ? "Allowed" : "Disallowed");
-        _response.concat("\nNightmode enabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[13] ? "Allowed" : "Disallowed");
-        _response.concat("\nNightmode start time: ");
-        _response.concat((int)advancedLockConfigAclPrefs[14] ? "Allowed" : "Disallowed");
-        _response.concat("\nNightmode end time: ");
-        _response.concat((int)advancedLockConfigAclPrefs[15] ? "Allowed" : "Disallowed");
-        _response.concat("\nNightmode auto lock enabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[16] ? "Allowed" : "Disallowed");
-        _response.concat("\nNightmode auto unlock disabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[17] ? "Allowed" : "Disallowed");
-        _response.concat("\nNightmode immediate lock on start: ");
-        _response.concat((int)advancedLockConfigAclPrefs[18] ? "Allowed" : "Disallowed");
-        _response.concat("\nAuto lock enabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[19] ? "Allowed" : "Disallowed");
-        _response.concat("\nImmediate auto lock enabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[20] ? "Allowed" : "Disallowed");
-        _response.concat("\nAuto update enabled: ");
-        _response.concat((int)advancedLockConfigAclPrefs[21] ? "Allowed" : "Disallowed");
+        response.print("\n\n------------ NUKI LOCK ACL ------------");
+        response.print("\nLock: ");
+        response.print((int)aclPrefs[0] ? "Allowed" : "Disallowed");
+        response.print("\nUnlock: ");
+        response.print((int)aclPrefs[1] ? "Allowed" : "Disallowed");
+        response.print("\nUnlatch: ");
+        response.print((int)aclPrefs[2] ? "Allowed" : "Disallowed");
+        response.print("\nLock N Go: ");
+        response.print((int)aclPrefs[3] ? "Allowed" : "Disallowed");
+        response.print("\nLock N Go Unlatch: ");
+        response.print((int)aclPrefs[4] ? "Allowed" : "Disallowed");
+        response.print("\nFull Lock: ");
+        response.print((int)aclPrefs[5] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 1: ");
+        response.print((int)aclPrefs[6] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 2: ");
+        response.print((int)aclPrefs[7] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 3: ");
+        response.print((int)aclPrefs[8] ? "Allowed" : "Disallowed");
+        response.print("\n\n------------ NUKI LOCK CONFIG ACL ------------");
+        response.print("\nName: ");
+        response.print((int)basicLockConfigAclPrefs[0] ? "Allowed" : "Disallowed");
+        response.print("\nLatitude: ");
+        response.print((int)basicLockConfigAclPrefs[1] ? "Allowed" : "Disallowed");
+        response.print("\nLongitude: ");
+        response.print((int)basicLockConfigAclPrefs[2] ? "Allowed" : "Disallowed");
+        response.print("\nAuto Unlatch: ");
+        response.print((int)basicLockConfigAclPrefs[3] ? "Allowed" : "Disallowed");
+        response.print("\nPairing enabled: ");
+        response.print((int)basicLockConfigAclPrefs[4] ? "Allowed" : "Disallowed");
+        response.print("\nButton enabled: ");
+        response.print((int)basicLockConfigAclPrefs[5] ? "Allowed" : "Disallowed");
+        response.print("\nLED flash enabled: ");
+        response.print((int)basicLockConfigAclPrefs[6] ? "Allowed" : "Disallowed");
+        response.print("\nLED brightness: ");
+        response.print((int)basicLockConfigAclPrefs[7] ? "Allowed" : "Disallowed");
+        response.print("\nTimezone offset: ");
+        response.print((int)basicLockConfigAclPrefs[8] ? "Allowed" : "Disallowed");
+        response.print("\nDST mode: ");
+        response.print((int)basicLockConfigAclPrefs[9] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 1: ");
+        response.print((int)basicLockConfigAclPrefs[10] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 2: ");
+        response.print((int)basicLockConfigAclPrefs[11] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 3: ");
+        response.print((int)basicLockConfigAclPrefs[12] ? "Allowed" : "Disallowed");
+        response.print("\nSingle Lock: ");
+        response.print((int)basicLockConfigAclPrefs[13] ? "Allowed" : "Disallowed");
+        response.print("\nAdvertising Mode: ");
+        response.print((int)basicLockConfigAclPrefs[14] ? "Allowed" : "Disallowed");
+        response.print("\nTimezone ID: ");
+        response.print((int)basicLockConfigAclPrefs[15] ? "Allowed" : "Disallowed");
+        response.print("\nUnlocked Position Offset Degrees: ");
+        response.print((int)advancedLockConfigAclPrefs[0] ? "Allowed" : "Disallowed");
+        response.print("\nLocked Position Offset Degrees: ");
+        response.print((int)advancedLockConfigAclPrefs[1] ? "Allowed" : "Disallowed");
+        response.print("\nSingle Locked Position Offset Degrees: ");
+        response.print((int)advancedLockConfigAclPrefs[2] ? "Allowed" : "Disallowed");
+        response.print("\nUnlocked To Locked Transition Offset Degrees: ");
+        response.print((int)advancedLockConfigAclPrefs[3] ? "Allowed" : "Disallowed");
+        response.print("\nLock n Go timeout: ");
+        response.print((int)advancedLockConfigAclPrefs[4] ? "Allowed" : "Disallowed");
+        response.print("\nSingle button press action: ");
+        response.print((int)advancedLockConfigAclPrefs[5] ? "Allowed" : "Disallowed");
+        response.print("\nDouble button press action: ");
+        response.print((int)advancedLockConfigAclPrefs[6] ? "Allowed" : "Disallowed");
+        response.print("\nDetached cylinder: ");
+        response.print((int)advancedLockConfigAclPrefs[7] ? "Allowed" : "Disallowed");
+        response.print("\nBattery type: ");
+        response.print((int)advancedLockConfigAclPrefs[8] ? "Allowed" : "Disallowed");
+        response.print("\nAutomatic battery type detection: ");
+        response.print((int)advancedLockConfigAclPrefs[9] ? "Allowed" : "Disallowed");
+        response.print("\nUnlatch duration: ");
+        response.print((int)advancedLockConfigAclPrefs[10] ? "Allowed" : "Disallowed");
+        response.print("\nAuto lock timeout: ");
+        response.print((int)advancedLockConfigAclPrefs[11] ? "Allowed" : "Disallowed");
+        response.print("\nAuto unlock disabled: ");
+        response.print((int)advancedLockConfigAclPrefs[12] ? "Allowed" : "Disallowed");
+        response.print("\nNightmode enabled: ");
+        response.print((int)advancedLockConfigAclPrefs[13] ? "Allowed" : "Disallowed");
+        response.print("\nNightmode start time: ");
+        response.print((int)advancedLockConfigAclPrefs[14] ? "Allowed" : "Disallowed");
+        response.print("\nNightmode end time: ");
+        response.print((int)advancedLockConfigAclPrefs[15] ? "Allowed" : "Disallowed");
+        response.print("\nNightmode auto lock enabled: ");
+        response.print((int)advancedLockConfigAclPrefs[16] ? "Allowed" : "Disallowed");
+        response.print("\nNightmode auto unlock disabled: ");
+        response.print((int)advancedLockConfigAclPrefs[17] ? "Allowed" : "Disallowed");
+        response.print("\nNightmode immediate lock on start: ");
+        response.print((int)advancedLockConfigAclPrefs[18] ? "Allowed" : "Disallowed");
+        response.print("\nAuto lock enabled: ");
+        response.print((int)advancedLockConfigAclPrefs[19] ? "Allowed" : "Disallowed");
+        response.print("\nImmediate auto lock enabled: ");
+        response.print((int)advancedLockConfigAclPrefs[20] ? "Allowed" : "Disallowed");
+        response.print("\nAuto update enabled: ");
+        response.print((int)advancedLockConfigAclPrefs[21] ? "Allowed" : "Disallowed");
 
         if(_preferences->getBool(preference_show_secrets))
         {
@@ -3584,151 +4383,154 @@ void WebCfgServer::buildInfoHtml(AsyncWebServerRequest *request)
             nukiBlePref.getBytes("secretKeyK", secretKeyK, 32);
             nukiBlePref.getBytes("authorizationId", authorizationId, 4);
             nukiBlePref.end();
-            _response.concat("\n\n------------ NUKI LOCK PAIRING ------------");
-            _response.concat("\nBLE Address: ");
+            response.print("\n\n------------ NUKI LOCK PAIRING ------------");
+            response.print("\nBLE Address: ");
             for (int i = 0; i < 6; i++)
             {
                 sprintf(tmp, "%02x", currentBleAddress[i]);
-                _response.concat(tmp);
+                response.print(tmp);
             }
-            _response.concat("\nSecretKeyK: ");
+            response.print("\nSecretKeyK: ");
             for (int i = 0; i < 32; i++)
             {
                 sprintf(tmp, "%02x", secretKeyK[i]);
-                _response.concat(tmp);
+                response.print(tmp);
             }
-            _response.concat("\nAuthorizationId: ");
+            response.print("\nAuthorizationId: ");
             for (int i = 0; i < 4; i++)
             {
                 sprintf(tmp, "%02x", authorizationId[i]);
-                _response.concat(tmp);
+                response.print(tmp);
             }
             uint32_t authorizationIdInt = authorizationId[0] + 256U*authorizationId[1] + 65536U*authorizationId[2] + 16777216U*authorizationId[3];
-            _response.concat("\nAuthorizationId (UINT32_T): ");
-            _response.concat(authorizationIdInt);
+            response.print("\nAuthorizationId (UINT32_T): ");
+            response.print(authorizationIdInt);
         }
     }
 
-    _response.concat("\n\n------------ NUKI OPENER ------------");
-    if(_nukiOpener == nullptr || !_preferences->getBool(preference_opener_enabled, false)) _response.concat("\nOpener enabled: No");
+    response.print("\n\n------------ NUKI OPENER ------------");
+    if(_nukiOpener == nullptr || !_preferences->getBool(preference_opener_enabled, false))
+    {
+        response.print("\nOpener enabled: No");
+    }
     else
     {
-        _response.concat("\nOpener enabled: Yes");
-        _response.concat("\nPaired: ");
-        _response.concat(_nukiOpener->isPaired() ? "Yes" : "No");
-        _response.concat("\nNuki Hub device ID: ");
-        _response.concat(_preferences->getUInt(preference_device_id_opener, 0));
-        _response.concat("\nNuki device ID: ");
-        _response.concat(_preferences->getUInt(preference_nuki_id_opener, 0) > 0 ? "***" : "Not set");
-        _response.concat("\nFirmware version: ");
-        _response.concat(_nukiOpener->firmwareVersion().c_str());
-        _response.concat("\nHardware version: ");
-        _response.concat(_nukiOpener->hardwareVersion().c_str());
-        _response.concat("\nOpener valid PIN set: ");
-        _response.concat(_nukiOpener->isPaired() ? _nukiOpener->isPinValid() ? "Yes" : "No" : "-");
-        _response.concat("\nOpener has keypad: ");
-        _response.concat(_nukiOpener->hasKeypad() ? "Yes" : "No");
+        response.print("\nOpener enabled: Yes");
+        response.print("\nPaired: ");
+        response.print(_nukiOpener->isPaired() ? "Yes" : "No");
+        response.print("\nNuki Hub device ID: ");
+        response.print(_preferences->getUInt(preference_device_id_opener, 0));
+        response.print("\nNuki device ID: ");
+        response.print(_preferences->getUInt(preference_nuki_id_opener, 0) > 0 ? "***" : "Not set");
+        response.print("\nFirmware version: ");
+        response.print(_nukiOpener->firmwareVersion().c_str());
+        response.print("\nHardware version: ");
+        response.print(_nukiOpener->hardwareVersion().c_str());
+        response.print("\nOpener valid PIN set: ");
+        response.print(_nukiOpener->isPaired() ? _nukiOpener->isPinValid() ? "Yes" : "No" : "-");
+        response.print("\nOpener has keypad: ");
+        response.print(_nukiOpener->hasKeypad() ? "Yes" : "No");
         if(_nuki->hasKeypad())
         {
-            _response.concat("\nKeypad highest entries count: ");
-            _response.concat(_preferences->getInt(preference_opener_max_keypad_code_count, 0));
+            response.print("\nKeypad highest entries count: ");
+            response.print(_preferences->getInt(preference_opener_max_keypad_code_count, 0));
         }
-        _response.concat("\nTimecontrol highest entries count: ");
-        _response.concat(_preferences->getInt(preference_opener_max_timecontrol_entry_count, 0));
-        _response.concat("\nRegister as: ");
-        _response.concat(_preferences->getBool(preference_register_opener_as_app, false) ? "App" : "Bridge");
-        _response.concat("\nNuki Opener Lock/Unlock action set to Continuous mode in Home Assistant: ");
-        _response.concat(_preferences->getBool(preference_opener_continuous_mode, false) ? "Yes" : "No");
+        response.print("\nTimecontrol highest entries count: ");
+        response.print(_preferences->getInt(preference_opener_max_timecontrol_entry_count, 0));
+        response.print("\nRegister as: ");
+        response.print(_preferences->getBool(preference_register_opener_as_app, false) ? "App" : "Bridge");
+        response.print("\nNuki Opener Lock/Unlock action set to Continuous mode in Home Assistant: ");
+        response.print(_preferences->getBool(preference_opener_continuous_mode, false) ? "Yes" : "No");
         uint32_t basicOpenerConfigAclPrefs[14];
         _preferences->getBytes(preference_conf_opener_basic_acl, &basicOpenerConfigAclPrefs, sizeof(basicOpenerConfigAclPrefs));
         uint32_t advancedOpenerConfigAclPrefs[20];
         _preferences->getBytes(preference_conf_opener_advanced_acl, &advancedOpenerConfigAclPrefs, sizeof(advancedOpenerConfigAclPrefs));
-        _response.concat("\n\n------------ NUKI OPENER ACL ------------");
-        _response.concat("\nActivate Ring-to-Open: ");
-        _response.concat((int)aclPrefs[9] ? "Allowed" : "Disallowed");
-        _response.concat("\nDeactivate Ring-to-Open: ");
-        _response.concat((int)aclPrefs[10] ? "Allowed" : "Disallowed");
-        _response.concat("\nElectric Strike Actuation: ");
-        _response.concat((int)aclPrefs[11] ? "Allowed" : "Disallowed");
-        _response.concat("\nActivate Continuous Mode: ");
-        _response.concat((int)aclPrefs[12] ? "Allowed" : "Disallowed");
-        _response.concat("\nDeactivate Continuous Mode: ");
-        _response.concat((int)aclPrefs[13] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 1: ");
-        _response.concat((int)aclPrefs[14] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 2: ");
-        _response.concat((int)aclPrefs[15] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 3: ");
-        _response.concat((int)aclPrefs[16] ? "Allowed" : "Disallowed");
-        _response.concat("\n\n------------ NUKI OPENER CONFIG ACL ------------");
-        _response.concat("\nName: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[0] ? "Allowed" : "Disallowed");
-        _response.concat("\nLatitude: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[1] ? "Allowed" : "Disallowed");
-        _response.concat("\nLongitude: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[2] ? "Allowed" : "Disallowed");
-        _response.concat("\nPairing enabled: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[3] ? "Allowed" : "Disallowed");
-        _response.concat("\nButton enabled: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[4] ? "Allowed" : "Disallowed");
-        _response.concat("\nLED flash enabled: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[5] ? "Allowed" : "Disallowed");
-        _response.concat("\nTimezone offset: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[6] ? "Allowed" : "Disallowed");
-        _response.concat("\nDST mode: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[7] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 1: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[8] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 2: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[9] ? "Allowed" : "Disallowed");
-        _response.concat("\nFob Action 3: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[10] ? "Allowed" : "Disallowed");
-        _response.concat("\nOperating Mode: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[11] ? "Allowed" : "Disallowed");
-        _response.concat("\nAdvertising Mode: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[12] ? "Allowed" : "Disallowed");
-        _response.concat("\nTimezone ID: ");
-        _response.concat((int)basicOpenerConfigAclPrefs[13] ? "Allowed" : "Disallowed");
-        _response.concat("\nIntercom ID: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[0] ? "Allowed" : "Disallowed");
-        _response.concat("\nBUS mode Switch: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[1] ? "Allowed" : "Disallowed");
-        _response.concat("\nShort Circuit Duration: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[2] ? "Allowed" : "Disallowed");
-        _response.concat("\nEletric Strike Delay: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[3] ? "Allowed" : "Disallowed");
-        _response.concat("\nRandom Electric Strike Delay: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[4] ? "Allowed" : "Disallowed");
-        _response.concat("\nElectric Strike Duration: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[5] ? "Allowed" : "Disallowed");
-        _response.concat("\nDisable RTO after ring: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[6] ? "Allowed" : "Disallowed");
-        _response.concat("\nRTO timeout: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[7] ? "Allowed" : "Disallowed");
-        _response.concat("\nDoorbell suppression: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[8] ? "Allowed" : "Disallowed");
-        _response.concat("\nDoorbell suppression duration: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[9] ? "Allowed" : "Disallowed");
-        _response.concat("\nSound Ring: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[10] ? "Allowed" : "Disallowed");
-        _response.concat("\nSound Open: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[11] ? "Allowed" : "Disallowed");
-        _response.concat("\nSound RTO: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[12] ? "Allowed" : "Disallowed");
-        _response.concat("\nSound CM: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[13] ? "Allowed" : "Disallowed");
-        _response.concat("\nSound confirmation: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[14] ? "Allowed" : "Disallowed");
-        _response.concat("\nSound level: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[15] ? "Allowed" : "Disallowed");
-        _response.concat("\nSingle button press action: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[16] ? "Allowed" : "Disallowed");
-        _response.concat("\nDouble button press action: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[17] ? "Allowed" : "Disallowed");
-        _response.concat("\nBattery type: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[18] ? "Allowed" : "Disallowed");
-        _response.concat("\nAutomatic battery type detection: ");
-        _response.concat((int)advancedOpenerConfigAclPrefs[19] ? "Allowed" : "Disallowed");
+        response.print("\n\n------------ NUKI OPENER ACL ------------");
+        response.print("\nActivate Ring-to-Open: ");
+        response.print((int)aclPrefs[9] ? "Allowed" : "Disallowed");
+        response.print("\nDeactivate Ring-to-Open: ");
+        response.print((int)aclPrefs[10] ? "Allowed" : "Disallowed");
+        response.print("\nElectric Strike Actuation: ");
+        response.print((int)aclPrefs[11] ? "Allowed" : "Disallowed");
+        response.print("\nActivate Continuous Mode: ");
+        response.print((int)aclPrefs[12] ? "Allowed" : "Disallowed");
+        response.print("\nDeactivate Continuous Mode: ");
+        response.print((int)aclPrefs[13] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 1: ");
+        response.print((int)aclPrefs[14] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 2: ");
+        response.print((int)aclPrefs[15] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 3: ");
+        response.print((int)aclPrefs[16] ? "Allowed" : "Disallowed");
+        response.print("\n\n------------ NUKI OPENER CONFIG ACL ------------");
+        response.print("\nName: ");
+        response.print((int)basicOpenerConfigAclPrefs[0] ? "Allowed" : "Disallowed");
+        response.print("\nLatitude: ");
+        response.print((int)basicOpenerConfigAclPrefs[1] ? "Allowed" : "Disallowed");
+        response.print("\nLongitude: ");
+        response.print((int)basicOpenerConfigAclPrefs[2] ? "Allowed" : "Disallowed");
+        response.print("\nPairing enabled: ");
+        response.print((int)basicOpenerConfigAclPrefs[3] ? "Allowed" : "Disallowed");
+        response.print("\nButton enabled: ");
+        response.print((int)basicOpenerConfigAclPrefs[4] ? "Allowed" : "Disallowed");
+        response.print("\nLED flash enabled: ");
+        response.print((int)basicOpenerConfigAclPrefs[5] ? "Allowed" : "Disallowed");
+        response.print("\nTimezone offset: ");
+        response.print((int)basicOpenerConfigAclPrefs[6] ? "Allowed" : "Disallowed");
+        response.print("\nDST mode: ");
+        response.print((int)basicOpenerConfigAclPrefs[7] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 1: ");
+        response.print((int)basicOpenerConfigAclPrefs[8] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 2: ");
+        response.print((int)basicOpenerConfigAclPrefs[9] ? "Allowed" : "Disallowed");
+        response.print("\nFob Action 3: ");
+        response.print((int)basicOpenerConfigAclPrefs[10] ? "Allowed" : "Disallowed");
+        response.print("\nOperating Mode: ");
+        response.print((int)basicOpenerConfigAclPrefs[11] ? "Allowed" : "Disallowed");
+        response.print("\nAdvertising Mode: ");
+        response.print((int)basicOpenerConfigAclPrefs[12] ? "Allowed" : "Disallowed");
+        response.print("\nTimezone ID: ");
+        response.print((int)basicOpenerConfigAclPrefs[13] ? "Allowed" : "Disallowed");
+        response.print("\nIntercom ID: ");
+        response.print((int)advancedOpenerConfigAclPrefs[0] ? "Allowed" : "Disallowed");
+        response.print("\nBUS mode Switch: ");
+        response.print((int)advancedOpenerConfigAclPrefs[1] ? "Allowed" : "Disallowed");
+        response.print("\nShort Circuit Duration: ");
+        response.print((int)advancedOpenerConfigAclPrefs[2] ? "Allowed" : "Disallowed");
+        response.print("\nEletric Strike Delay: ");
+        response.print((int)advancedOpenerConfigAclPrefs[3] ? "Allowed" : "Disallowed");
+        response.print("\nRandom Electric Strike Delay: ");
+        response.print((int)advancedOpenerConfigAclPrefs[4] ? "Allowed" : "Disallowed");
+        response.print("\nElectric Strike Duration: ");
+        response.print((int)advancedOpenerConfigAclPrefs[5] ? "Allowed" : "Disallowed");
+        response.print("\nDisable RTO after ring: ");
+        response.print((int)advancedOpenerConfigAclPrefs[6] ? "Allowed" : "Disallowed");
+        response.print("\nRTO timeout: ");
+        response.print((int)advancedOpenerConfigAclPrefs[7] ? "Allowed" : "Disallowed");
+        response.print("\nDoorbell suppression: ");
+        response.print((int)advancedOpenerConfigAclPrefs[8] ? "Allowed" : "Disallowed");
+        response.print("\nDoorbell suppression duration: ");
+        response.print((int)advancedOpenerConfigAclPrefs[9] ? "Allowed" : "Disallowed");
+        response.print("\nSound Ring: ");
+        response.print((int)advancedOpenerConfigAclPrefs[10] ? "Allowed" : "Disallowed");
+        response.print("\nSound Open: ");
+        response.print((int)advancedOpenerConfigAclPrefs[11] ? "Allowed" : "Disallowed");
+        response.print("\nSound RTO: ");
+        response.print((int)advancedOpenerConfigAclPrefs[12] ? "Allowed" : "Disallowed");
+        response.print("\nSound CM: ");
+        response.print((int)advancedOpenerConfigAclPrefs[13] ? "Allowed" : "Disallowed");
+        response.print("\nSound confirmation: ");
+        response.print((int)advancedOpenerConfigAclPrefs[14] ? "Allowed" : "Disallowed");
+        response.print("\nSound level: ");
+        response.print((int)advancedOpenerConfigAclPrefs[15] ? "Allowed" : "Disallowed");
+        response.print("\nSingle button press action: ");
+        response.print((int)advancedOpenerConfigAclPrefs[16] ? "Allowed" : "Disallowed");
+        response.print("\nDouble button press action: ");
+        response.print((int)advancedOpenerConfigAclPrefs[17] ? "Allowed" : "Disallowed");
+        response.print("\nBattery type: ");
+        response.print((int)advancedOpenerConfigAclPrefs[18] ? "Allowed" : "Disallowed");
+        response.print("\nAutomatic battery type detection: ");
+        response.print((int)advancedOpenerConfigAclPrefs[19] ? "Allowed" : "Disallowed");
         if(_preferences->getBool(preference_show_secrets))
         {
             char tmp[16];
@@ -3741,52 +4543,54 @@ void WebCfgServer::buildInfoHtml(AsyncWebServerRequest *request)
             nukiBlePref.getBytes("secretKeyK", secretKeyKOpn, 32);
             nukiBlePref.getBytes("authorizationId", authorizationIdOpn, 4);
             nukiBlePref.end();
-            _response.concat("\n\n------------ NUKI OPENER PAIRING ------------");
-            _response.concat("\nBLE Address: ");
+            response.print("\n\n------------ NUKI OPENER PAIRING ------------");
+            response.print("\nBLE Address: ");
             for (int i = 0; i < 6; i++)
             {
                 sprintf(tmp, "%02x", currentBleAddressOpn[i]);
-                _response.concat(tmp);
+                response.print(tmp);
             }
-            _response.concat("\nSecretKeyK: ");
+            response.print("\nSecretKeyK: ");
             for (int i = 0; i < 32; i++)
             {
                 sprintf(tmp, "%02x", secretKeyKOpn[i]);
-                _response.concat(tmp);
+                response.print(tmp);
             }
-            _response.concat("\nAuthorizationId: ");
+            response.print("\nAuthorizationId: ");
             for (int i = 0; i < 4; i++)
             {
                 sprintf(tmp, "%02x", authorizationIdOpn[i]);
-                _response.concat(tmp);
+                response.print(tmp);
             }
         }
     }
 
-    _response.concat("\n\n------------ GPIO ------------\n");
+    response.print("\n\n------------ GPIO ------------\n");
     String gpioStr = "";
     _gpio->getConfigurationText(gpioStr, _gpio->pinConfiguration());
-    _response.concat(gpioStr);
-    _response.concat("
"); - sendResponse(request); + response.print(gpioStr); + response.print("
"); + return response.endSend(); } -void WebCfgServer::processUnpair(AsyncWebServerRequest *request, bool opener) +esp_err_t WebCfgServer::processUnpair(PsychicRequest *request, bool opener) { String value = ""; - if(request->hasParam("CONFIRMTOKEN", true)) + if(request->hasParam("CONFIRMTOKEN")) { - const AsyncWebParameter* p = request->getParam("CONFIRMTOKEN", true); - if(p->value() != "") value = p->value(); + const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); + if(p->value() != "") + { + value = p->value(); + } } if(value != _confirmCode) { - buildConfirmHtml(request, "Confirm code is invalid.", 3, true); - return; + return buildConfirmHtml(request, "Confirm code is invalid.", 3, true); } - buildConfirmHtml(request, opener ? "Unpairing Nuki Opener and restarting." : "Unpairing Nuki Lock and restarting.", 3, true); + esp_err_t res = buildConfirmHtml(request, opener ? "Unpairing Nuki Opener and restarting." : "Unpairing Nuki Lock and restarting.", 3, true); if(!opener && _nuki != nullptr) { @@ -3800,34 +4604,38 @@ void WebCfgServer::processUnpair(AsyncWebServerRequest *request, bool opener) } waitAndProcess(false, 1000); restartEsp(RestartReason::DeviceUnpaired); + return res; } -void WebCfgServer::processUpdate(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::processUpdate(PsychicRequest *request) { + esp_err_t res; String value = ""; if(request->hasParam("token")) { - const AsyncWebParameter* p = request->getParam("token"); - if(p->value() != "") value = p->value(); + const PsychicWebParameter* p = request->getParam("token"); + if(p->value() != "") + { + value = p->value(); + } } if(value != _confirmCode) { - buildConfirmHtml(request, "Confirm code is invalid.", 3, true); - return; + return buildConfirmHtml(request, "Confirm code is invalid.", 3, true); } if(request->hasParam("beta")) { if(request->hasParam("debug")) { - buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEBUG BETA version", 2, true); + res = buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEBUG BETA version", 2, true); _preferences->putString(preference_ota_updater_url, GITHUB_BETA_UPDATER_BINARY_URL_DBG); _preferences->putString(preference_ota_main_url, GITHUB_BETA_RELEASE_BINARY_URL_DBG); } else { - buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest BETA version", 2, true); + res = buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest BETA version", 2, true); _preferences->putString(preference_ota_updater_url, GITHUB_BETA_UPDATER_BINARY_URL); _preferences->putString(preference_ota_main_url, GITHUB_BETA_RELEASE_BINARY_URL); } @@ -3836,13 +4644,13 @@ void WebCfgServer::processUpdate(AsyncWebServerRequest *request) { if(request->hasParam("debug")) { - buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEBUG DEVELOPMENT version", 2, true); + res = buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEBUG DEVELOPMENT version", 2, true); _preferences->putString(preference_ota_updater_url, GITHUB_MASTER_UPDATER_BINARY_URL_DBG); _preferences->putString(preference_ota_main_url, GITHUB_MASTER_RELEASE_BINARY_URL_DBG); } else { - buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEVELOPMENT version", 2, true); + res = buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEVELOPMENT version", 2, true); _preferences->putString(preference_ota_updater_url, GITHUB_MASTER_UPDATER_BINARY_URL); _preferences->putString(preference_ota_main_url, GITHUB_MASTER_RELEASE_BINARY_URL); } @@ -3851,53 +4659,60 @@ void WebCfgServer::processUpdate(AsyncWebServerRequest *request) { if(request->hasParam("debug")) { - buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEBUG RELEASE version", 2, true); + res = buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest DEBUG RELEASE version", 2, true); _preferences->putString(preference_ota_updater_url, GITHUB_LATEST_UPDATER_BINARY_URL_DBG); _preferences->putString(preference_ota_main_url, GITHUB_LATEST_UPDATER_BINARY_URL_DBG); } else { - buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest RELEASE version", 2, true); + res = buildConfirmHtml(request, "Rebooting to update Nuki Hub and Nuki Hub updater
Updating to latest RELEASE version", 2, true); _preferences->putString(preference_ota_updater_url, GITHUB_LATEST_UPDATER_BINARY_URL); _preferences->putString(preference_ota_main_url, GITHUB_LATEST_RELEASE_BINARY_URL); } } waitAndProcess(true, 1000); restartEsp(RestartReason::OTAReboot); + return res; } -void WebCfgServer::processFactoryReset(AsyncWebServerRequest *request) +esp_err_t WebCfgServer::processFactoryReset(PsychicRequest *request) { + esp_err_t res; String value = ""; - if(request->hasParam("CONFIRMTOKEN", true)) + if(request->hasParam("CONFIRMTOKEN")) { - const AsyncWebParameter* p = request->getParam("CONFIRMTOKEN", true); - if(p->value() != "") value = p->value(); + const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); + if(p->value() != "") + { + value = p->value(); + } } bool resetWifi = false; if(value.length() == 0 || value != _confirmCode) { - buildConfirmHtml(request, "Confirm code is invalid.", 3, true); - return; + return buildConfirmHtml(request, "Confirm code is invalid.", 3, true); } else { String value2 = ""; - if(request->hasParam("WIFI", true)) + if(request->hasParam("WIFI")) { - const AsyncWebParameter* p = request->getParam("WIFI", true); - if(p->value() != "") value = p->value(); + const PsychicWebParameter* p = request->getParam("WIFI"); + if(p->value() != "") + { + value = p->value(); + } } if(value2 == "1") { resetWifi = true; - buildConfirmHtml(request, "Factory resetting Nuki Hub, unpairing Nuki Lock and Nuki Opener and resetting WiFi.", 3, true); + res = buildConfirmHtml(request, "Factory resetting Nuki Hub, unpairing Nuki Lock and Nuki Opener and resetting WiFi.", 3, true); } else { - buildConfirmHtml(request, "Factory resetting Nuki Hub, unpairing Nuki Lock and Nuki Opener.", 3, true); + res = buildConfirmHtml(request, "Factory resetting Nuki Hub, unpairing Nuki Lock and Nuki Opener.", 3, true); } } @@ -3916,99 +4731,20 @@ void WebCfgServer::processFactoryReset(AsyncWebServerRequest *request) _preferences->clear(); - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 if(resetWifi) { - wifi_config_t current_conf; - esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_STA, ¤t_conf); - memset(current_conf.sta.ssid, 0, sizeof(current_conf.sta.ssid)); - memset(current_conf.sta.password, 0, sizeof(current_conf.sta.password)); - esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, ¤t_conf); _network->reconfigureDevice(); } - #endif +#endif waitAndProcess(false, 3000); restartEsp(RestartReason::NukiHubReset); + return res; } -void WebCfgServer::printInputField(const char *token, - const char *description, - const char *value, - const size_t& maxLength, - const char *args, - const bool& isPassword, - const bool& showLengthRestriction) -{ - char maxLengthStr[20]; - - itoa(maxLength, maxLengthStr, 10); - - _response.concat(""); - _response.concat(description); - - if(showLengthRestriction) - { - _response.concat(" (Max. "); - _response.concat(maxLength); - _response.concat(" characters)"); - } - - _response.concat(""); - _response.concat(""); - _response.concat(""); -} - -void WebCfgServer::printInputField(const char *token, - const char *description, - const int value, - size_t maxLength, - const char *args) -{ - char valueStr[20]; - itoa(value, valueStr, 10); - printInputField(token, description, valueStr, maxLength, args); -} - -void WebCfgServer::printCheckBox(const char *token, const char *description, const bool value, const char *htmlClass) -{ - _response.concat(""); - _response.concat(description); - _response.concat(""); - - _response.concat(""); - - _response.concat(""); -} - -void WebCfgServer::printTextarea(const char *token, +void WebCfgServer::printTextarea(PsychicStreamResponse *response, + const char *token, const char *description, const char *value, const size_t& maxLength, @@ -4019,112 +4755,124 @@ void WebCfgServer::printTextarea(const char *token, itoa(maxLength, maxLengthStr, 10); - _response.concat(""); - _response.concat(description); + response->print(""); + response->print(description); if(showLengthRestriction) { - _response.concat(" (Max. "); - _response.concat(maxLength); - _response.concat(" characters)"); + response->print(" (Max. "); + response->print(maxLength); + response->print(" characters)"); } - _response.concat(""); - _response.concat(" "); - _response.concat(""); + response->print(" name=\""); + response->print(token); + response->print("\" maxlength=\""); + response->print(maxLengthStr); + response->print("\">"); + response->print(value); + response->print(""); + response->print(""); } -void WebCfgServer::printDropDown(const char *token, const char *description, const String preselectedValue, const std::vector> options, const String className) +void WebCfgServer::printDropDown(PsychicStreamResponse *response, const char *token, const char *description, const String preselectedValue, const std::vector> options, const String className) { - _response.concat(""); - _response.concat(description); - _response.concat(""); - + response->print(""); + response->print(description); + response->print(""); if(className.length() > 0) { - _response.concat("print(""); - _response.concat(""); + response->print(""); + response->print(""); } -void WebCfgServer::buildNavigationButton(const char *caption, const char *targetPath, const char* labelText) +void WebCfgServer::buildNavigationButton(PsychicStreamResponse *response, const char *caption, const char *targetPath, const char* labelText) { - _response.concat("
"); - _response.concat(" "); - _response.concat(labelText); - _response.concat("
"); + response->print("
print(targetPath); + response->print("\">"); + response->print(" "); + response->print(labelText); + response->print("
"); } -void WebCfgServer::buildNavigationMenuEntry(const char *title, const char *targetPath, const char* warningMessage) +void WebCfgServer::buildNavigationMenuEntry(PsychicStreamResponse *response, const char *title, const char *targetPath, const char* warningMessage) { - _response.concat(""); - _response.concat("
  • "); - _response.concat(title); - if(strcmp(warningMessage, "") != 0){ - _response.concat(""); - _response.concat(warningMessage); - _response.concat(""); + response->print("print(targetPath); + response->print("\">"); + response->print("
  • "); + response->print(title); + if(strcmp(warningMessage, "") != 0) + { + response->print(""); + response->print(warningMessage); + response->print(""); } - _response.concat("
  • "); + response->print(""); } -void WebCfgServer::printParameter(const char *description, const char *value, const char *link, const char *id) +void WebCfgServer::printParameter(PsychicStreamResponse *response, const char *description, const char *value, const char *link, const char *id) { - _response.concat(""); - _response.concat(""); - _response.concat(description); - _response.concat(""); - if(strcmp(id, "") == 0) _response.concat(""); + response->print(""); + response->print(""); + response->print(description); + response->print(""); + if(strcmp(id, "") == 0) + { + response->print(""); + } else { - _response.concat(""); + response->print("print(id); + response->print("\">"); + } + if(strcmp(link, "") == 0) + { + response->print(value); } - if(strcmp(link, "") == 0) _response.concat(value); else { - _response.concat(" "); - _response.concat(value); - _response.concat(""); + response->print("print(link); + response->print("\"> "); + response->print(value); + response->print(""); } - _response.concat(""); - _response.concat(""); + response->print(""); + response->print(""); } @@ -4132,7 +4880,7 @@ const std::vector> WebCfgServer::getNetworkDetectionOp { std::vector> options; - options.push_back(std::make_pair("1", "Wi-Fi only")); + options.push_back(std::make_pair("1", "Wi-Fi")); options.push_back(std::make_pair("2", "Generic W5500")); options.push_back(std::make_pair("3", "M5Stack Atom POE (W5500)")); options.push_back(std::make_pair("10", "M5Stack Atom POE S3 (W5500)")); @@ -4154,14 +4902,14 @@ const std::vector> WebCfgServer::getNetworkCustomPHYOp options.push_back(std::make_pair("1", "W5500")); options.push_back(std::make_pair("2", "DN9051")); options.push_back(std::make_pair("3", "KSZ8851SNL")); - #if defined(CONFIG_IDF_TARGET_ESP32) +#if defined(CONFIG_IDF_TARGET_ESP32) options.push_back(std::make_pair("4", "LAN8720")); options.push_back(std::make_pair("5", "RTL8201")); options.push_back(std::make_pair("6", "TLK110")); options.push_back(std::make_pair("7", "DP83848")); options.push_back(std::make_pair("8", "KSZ8041")); options.push_back(std::make_pair("9", "KSZ8081")); - #endif +#endif return options; } diff --git a/src/WebCfgServer.h b/src/WebCfgServer.h index 583175d..e9be8b9 100644 --- a/src/WebCfgServer.h +++ b/src/WebCfgServer.h @@ -1,9 +1,8 @@ #pragma once #include -#include -#include -#include +#include +#include #include "esp_ota_ops.h" #include "Config.h" @@ -37,9 +36,9 @@ class WebCfgServer { public: #ifndef NUKI_HUB_UPDATER - WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, AsyncWebServer* asyncServer); + WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, PsychicHttpServer* psychicServer); #else - WebCfgServer(NukiNetwork* network, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, AsyncWebServer* asyncServer); + WebCfgServer(NukiNetwork* network, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, PsychicHttpServer* psychicServer); #endif ~WebCfgServer() = default; @@ -47,34 +46,31 @@ public: private: #ifndef NUKI_HUB_UPDATER - void sendSettings(AsyncWebServerRequest *request); - bool processArgs(AsyncWebServerRequest *request, String& message); - bool processImport(AsyncWebServerRequest *request, String& message); - void processGpioArgs(AsyncWebServerRequest *request); - void buildHtml(AsyncWebServerRequest *request); - void buildAccLvlHtml(AsyncWebServerRequest *request); - void buildCredHtml(AsyncWebServerRequest *request); - void buildImportExportHtml(AsyncWebServerRequest *request); - void buildMqttConfigHtml(AsyncWebServerRequest *request); - void buildStatusHtml(AsyncWebServerRequest *request); - void buildAdvancedConfigHtml(AsyncWebServerRequest *request); - void buildNukiConfigHtml(AsyncWebServerRequest *request); - void buildGpioConfigHtml(AsyncWebServerRequest *request); + esp_err_t sendSettings(PsychicRequest *request); + bool processArgs(PsychicRequest *request, String& message); + bool processImport(PsychicRequest *request, String& message); + void processGpioArgs(PsychicRequest *request); + esp_err_t buildHtml(PsychicRequest *request); + esp_err_t buildAccLvlHtml(PsychicRequest *request); + esp_err_t buildCredHtml(PsychicRequest *request); + esp_err_t buildImportExportHtml(PsychicRequest *request); + esp_err_t buildMqttConfigHtml(PsychicRequest *request); + esp_err_t buildStatusHtml(PsychicRequest *request); + esp_err_t buildAdvancedConfigHtml(PsychicRequest *request); + esp_err_t buildNukiConfigHtml(PsychicRequest *request); + esp_err_t buildGpioConfigHtml(PsychicRequest *request); #ifndef CONFIG_IDF_TARGET_ESP32H2 - void buildConfigureWifiHtml(AsyncWebServerRequest *request); + esp_err_t buildConfigureWifiHtml(PsychicRequest *request); #endif - void buildInfoHtml(AsyncWebServerRequest *request); - void buildCustomNetworkConfigHtml(AsyncWebServerRequest *request); - void processUnpair(AsyncWebServerRequest *request, bool opener); - void processUpdate(AsyncWebServerRequest *request); - void processFactoryReset(AsyncWebServerRequest *request); - void printInputField(const char* token, const char* description, const char* value, const size_t& maxLength, const char* args, const bool& isPassword = false, const bool& showLengthRestriction = false); - void printInputField(const char* token, const char* description, const int value, size_t maxLength, const char* args); - void printCheckBox(const char* token, const char* description, const bool value, const char* htmlClass); - void printTextarea(const char *token, const char *description, const char *value, const size_t& maxLength, const bool& enabled = true, const bool& showLengthRestriction = false); - void printDropDown(const char *token, const char *description, const String preselectedValue, std::vector> options, const String className); - void buildNavigationButton(const char* caption, const char* targetPath, const char* labelText = ""); - void buildNavigationMenuEntry(const char *title, const char *targetPath, const char* warningMessage = ""); + esp_err_t buildInfoHtml(PsychicRequest *request); + esp_err_t buildCustomNetworkConfigHtml(PsychicRequest *request); + esp_err_t processUnpair(PsychicRequest *request, bool opener); + esp_err_t processUpdate(PsychicRequest *request); + esp_err_t processFactoryReset(PsychicRequest *request); + void printTextarea(PsychicStreamResponse *response, const char *token, const char *description, const char *value, const size_t& maxLength, const bool& enabled = true, const bool& showLengthRestriction = false); + void printDropDown(PsychicStreamResponse *response, const char *token, const char *description, const String preselectedValue, std::vector> options, const String className); + void buildNavigationButton(PsychicStreamResponse *response, const char* caption, const char* targetPath, const char* labelText = ""); + void buildNavigationMenuEntry(PsychicStreamResponse *response, const char *title, const char *targetPath, const char* warningMessage = ""); const std::vector> getNetworkDetectionOptions() const; const std::vector> getGpioOptions() const; @@ -86,8 +82,8 @@ private: String getPreselectionForGpio(const uint8_t& pin); String pinStateToString(uint8_t value); - void printParameter(const char* description, const char* value, const char *link = "", const char *id = ""); - + void printParameter(PsychicStreamResponse *response, const char* description, const char* value, const char *link = "", const char *id = ""); + NukiWrapper* _nuki = nullptr; NukiOpenerWrapper* _nukiOpener = nullptr; Gpio* _gpio = nullptr; @@ -95,22 +91,32 @@ private: bool _brokerConfigured = false; bool _rebootRequired = false; #endif - - String _response; + + std::vector _ssidList; + std::vector _rssiList; String generateConfirmCode(); String _confirmCode = "----"; - void buildConfirmHtml(AsyncWebServerRequest *request, const String &message, uint32_t redirectDelay = 5, bool redirect = false); - void buildOtaHtml(AsyncWebServerRequest *request, bool debug = false); - void buildOtaCompletedHtml(AsyncWebServerRequest *request); - void sendCss(AsyncWebServerRequest *request); - void sendFavicon(AsyncWebServerRequest *request); - void buildHtmlHeader(String additionalHeader = ""); + esp_err_t buildSSIDListHtml(PsychicRequest *request); + esp_err_t buildConfirmHtml(PsychicRequest *request, const String &message, uint32_t redirectDelay = 5, bool redirect = false); + esp_err_t buildOtaHtml(PsychicRequest *request, bool debug = false); + esp_err_t buildOtaCompletedHtml(PsychicRequest *request); + esp_err_t sendCss(PsychicRequest *request); + esp_err_t sendFavicon(PsychicRequest *request); + void createSsidList(); + void buildHtmlHeader(PsychicStreamResponse *response, String additionalHeader = ""); void waitAndProcess(const bool blocking, const uint32_t duration); - void handleOtaUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final); + esp_err_t handleOtaUpload(PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final); + void printCheckBox(PsychicStreamResponse *response, const char* token, const char* description, const bool value, const char* htmlClass); void printProgress(size_t prg, size_t sz); - void sendResponse(AsyncWebServerRequest *request); + #ifndef CONFIG_IDF_TARGET_ESP32H2 + esp_err_t buildWifiConnectHtml(PsychicRequest *request); + bool processWiFi(PsychicRequest *request, String& message); - AsyncWebServer* _asyncServer = nullptr; + #endif + void printInputField(PsychicStreamResponse *response, const char* token, const char* description, const char* value, const size_t& maxLength, const char* args, const bool& isPassword = false, const bool& showLengthRestriction = false); + void printInputField(PsychicStreamResponse *response, const char* token, const char* description, const int value, size_t maxLength, const char* args); + + PsychicHttpServer* _psychicServer = nullptr; NukiNetwork* _network = nullptr; Preferences* _preferences = nullptr; diff --git a/src/main.cpp b/src/main.cpp index 60dc185..b71e6f9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,7 +5,7 @@ #include "esp_ota_ops.h" #include "esp_http_client.h" #include "esp_https_ota.h" -#include +#include "esp_task_wdt.h" #include "Config.h" #ifndef NUKI_HUB_UPDATER @@ -19,11 +19,14 @@ #include "Logger.h" #include "PreferencesKeys.h" #include "RestartReason.h" -#include -#include -#include +#include "EspMillis.h" + +/* +#ifdef DEBUG_NUKIHUB #include #include +#endif +*/ char log_print_buffer[1024]; @@ -50,12 +53,13 @@ int64_t restartTs = ((2^64) - (5 * 1000 * 60000)) / 1000; #include "../../src/PreferencesKeys.h" #include "../../src/RestartReason.h" #include "../../src/NukiNetwork.h" +#include "../../src/EspMillis.h" int64_t restartTs = 10 * 1000 * 60000; #endif -AsyncWebServer* asyncServer = nullptr; +PsychicHttpServer* psychicServer = nullptr; NukiNetwork* network = nullptr; WebCfgServer* webCfgServer = nullptr; Preferences* preferences = nullptr; @@ -76,9 +80,8 @@ TaskHandle_t networkTaskHandle = nullptr; #ifndef NUKI_HUB_UPDATER ssize_t write_fn(void* cookie, const char* buf, ssize_t size) { - Log->write((uint8_t *)buf, (size_t)size); - - return size; + Log->write((uint8_t *)buf, (size_t)size); + return size; } void ets_putc_handler(char c) @@ -87,23 +90,31 @@ void ets_putc_handler(char c) static size_t buf_pos = 0; buf[buf_pos] = c; buf_pos++; - if (c == '\n' || buf_pos == sizeof(buf)) { + if (c == '\n' || buf_pos == sizeof(buf)) + { write_fn(NULL, buf, buf_pos); buf_pos = 0; } } -int _log_vprintf(const char *fmt, va_list args) { +int _log_vprintf(const char *fmt, va_list args) +{ int ret = vsnprintf(log_print_buffer, sizeof(log_print_buffer), fmt, args); - if (ret >= 0){ + if (ret >= 0) + { Log->write((uint8_t *)log_print_buffer, (size_t)ret); } return 0; //return vprintf(fmt, args); } -void setReroute(){ +void setReroute() +{ esp_log_set_vprintf(_log_vprintf); - if(preferences->getBool(preference_mqtt_log_enabled)) esp_log_level_set("*", ESP_LOG_INFO); + if(preferences->getBool(preference_mqtt_log_enabled)) + { + esp_log_level_set("*", ESP_LOG_INFO); + esp_log_level_set("mqtt", ESP_LOG_NONE); + } else { esp_log_level_set("*", ESP_LOG_DEBUG); @@ -123,7 +134,7 @@ void networkTask(void *pvParameters) } while(true) { - int64_t ts = (esp_timer_get_time() / 1000); + int64_t ts = espMillis(); if(ts > 120000 && ts < 125000) { if(bootloopCounter > 0) @@ -148,13 +159,16 @@ void networkTask(void *pvParameters) setReroute(); } #endif - if(connected && openerEnabled) networkOpener->update(); + if(connected && openerEnabled) + { + networkOpener->update(); + } #endif - if((esp_timer_get_time() / 1000) - networkLoopTs > 120000) + if(espMillis() - networkLoopTs > 120000) { Log->println("networkTask is running"); - networkLoopTs = esp_timer_get_time() / 1000; + networkLoopTs = espMillis(); } esp_task_wdt_reset(); @@ -201,10 +215,10 @@ void nukiTask(void *pvParameters) nukiOpener->update(); } - if((esp_timer_get_time() / 1000) - nukiLoopTs > 120000) + if(espMillis() - nukiLoopTs > 120000) { Log->println("nukiTask is running"); - nukiLoopTs = esp_timer_get_time() / 1000; + nukiLoopTs = espMillis(); } esp_task_wdt_reset(); @@ -225,10 +239,10 @@ void bootloopDetection() } if(esp_reset_reason() == esp_reset_reason_t::ESP_RST_PANIC || - esp_reset_reason() == esp_reset_reason_t::ESP_RST_INT_WDT || - esp_reset_reason() == esp_reset_reason_t::ESP_RST_TASK_WDT || - true || - esp_reset_reason() == esp_reset_reason_t::ESP_RST_WDT) + esp_reset_reason() == esp_reset_reason_t::ESP_RST_INT_WDT || + esp_reset_reason() == esp_reset_reason_t::ESP_RST_TASK_WDT || + true || + esp_reset_reason() == esp_reset_reason_t::ESP_RST_WDT) { bootloopCounter++; Log->print(F("Bootloop counter incremented: ")); @@ -259,38 +273,48 @@ uint8_t checkPartition() 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 + 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; - case HTTP_EVENT_REDIRECT: - Log->println("HTTP_EVENT_REDIRECT"); - break; + 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; + case HTTP_EVENT_REDIRECT: + Log->println("HTTP_EVENT_REDIRECT"); + break; } return ESP_OK; } @@ -311,14 +335,16 @@ void otaTask(void *pvParameter) preferences->putString(preference_ota_main_url, ""); } Log->println("Starting OTA task"); - esp_http_client_config_t config = { + 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 = { + esp_https_ota_config_t ota_config = + { .http_config = &config, }; Log->print(F("Attempting to download update from ")); @@ -330,19 +356,23 @@ void otaTask(void *pvParameter) while (retryCount <= retryMax) { esp_err_t ret = esp_https_ota(&ota_config); - if (ret == ESP_OK) { + if (ret == ESP_OK) + { Log->println("OTA Succeeded, Rebooting..."); esp_ota_set_boot_partition(esp_ota_get_next_update_partition(NULL)); restartEsp(RestartReason::OTACompleted); break; - } else { + } + else + { Log->println("Firmware upgrade failed, retrying in 5 seconds"); retryCount++; esp_task_wdt_reset(); delay(5000); continue; } - while (1) { + while (1) + { vTaskDelay(1000 / portTICK_PERIOD_MS); } } @@ -355,7 +385,8 @@ void otaTask(void *pvParameter) void setupTasks(bool ota) { // configMAX_PRIORITIES is 25 - esp_task_wdt_config_t twdt_config = { + esp_task_wdt_config_t twdt_config = + { .timeout_ms = 300000, .idle_core_mask = 0, .trigger_panic = true, @@ -371,26 +402,30 @@ void setupTasks(bool ota) { xTaskCreatePinnedToCore(networkTask, "ntw", preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), NULL, 3, &networkTaskHandle, 1); esp_task_wdt_add(networkTaskHandle); - #ifndef NUKI_HUB_UPDATER - xTaskCreatePinnedToCore(nukiTask, "nuki", preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), NULL, 2, &nukiTaskHandle, 0); - esp_task_wdt_add(nukiTaskHandle); - #endif +#ifndef NUKI_HUB_UPDATER + if(!network->isApOpen()) + { + xTaskCreatePinnedToCore(nukiTask, "nuki", preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), NULL, 2, &nukiTaskHandle, 0); + esp_task_wdt_add(nukiTaskHandle); + } +#endif } } void setup() { esp_log_level_set("*", ESP_LOG_ERROR); + esp_log_level_set("mqtt", ESP_LOG_NONE); Serial.begin(115200); Log = &Serial; - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER stdout = funopen(NULL, NULL, &write_fn, NULL, NULL); static char linebuf[1024]; setvbuf(stdout, linebuf, _IOLBF, sizeof(linebuf)); esp_rom_install_channel_putc(1, &ets_putc_handler); //ets_install_putc1(&ets_putc_handler); - #endif +#endif preferences = new Preferences(); preferences->begin("nukihub", false); @@ -400,37 +435,52 @@ void setup() initializeRestartReason(); - if((partitionType==1 && preferences->getString(preference_ota_updater_url, "").length() > 0) || (partitionType==2 && preferences->getString(preference_ota_main_url, "").length() > 0)) doOta = true; + if((partitionType==1 && preferences->getString(preference_ota_updater_url, "").length() > 0) || (partitionType==2 && preferences->getString(preference_ota_main_url, "").length() > 0)) + { + doOta = true; + } - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER if(preferences->getBool(preference_enable_bootloop_reset, false)) { bootloopDetection(); } - #endif +#endif - #ifdef NUKI_HUB_UPDATER +#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(); - if(preferences->getString(preference_updater_version, "") != NUKI_HUB_VERSION) preferences->putString(preference_updater_version, NUKI_HUB_VERSION); - if(preferences->getString(preference_updater_build, "") != NUKI_HUB_BUILD) preferences->putString(preference_updater_build, NUKI_HUB_BUILD); - if(preferences->getString(preference_updater_date, "") != NUKI_HUB_DATE) preferences->putString(preference_updater_date, NUKI_HUB_DATE); + if(preferences->getString(preference_updater_version, "") != NUKI_HUB_VERSION) + { + preferences->putString(preference_updater_version, NUKI_HUB_VERSION); + } + if(preferences->getString(preference_updater_build, "") != NUKI_HUB_BUILD) + { + preferences->putString(preference_updater_build, NUKI_HUB_BUILD); + } + if(preferences->getString(preference_updater_date, "") != NUKI_HUB_DATE) + { + preferences->putString(preference_updater_date, NUKI_HUB_DATE); + } network = new NukiNetwork(preferences); network->initialize(); if(!doOta) { - asyncServer = new AsyncWebServer(80); - webCfgServer = new WebCfgServer(network, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType, asyncServer); + psychicServer = new PsychicHttpServer; + webCfgServer = new WebCfgServer(network, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType, psychicServer); webCfgServer->initialize(); - asyncServer->onNotFound([](AsyncWebServerRequest* request) { request->redirect("/"); }); - asyncServer->begin(); + psychicServer->listen(80); + psychicServer->onNotFound([](PsychicRequest* request) + { + return request->redirect("/"); + }); } - #else +#else Log->print(F("Nuki Hub version ")); Log->println(NUKI_HUB_VERSION); Log->print(F("Nuki Hub build ")); @@ -447,7 +497,6 @@ void setup() } char16_t buffer_size = preferences->getInt(preference_buffer_size, 4096); - CharBuffer::initialize(buffer_size); gpio = new Gpio(preferences); @@ -455,22 +504,30 @@ void setup() gpio->getConfigurationText(gpioDesc, gpio->pinConfiguration(), "\n\r"); Log->print(gpioDesc.c_str()); + const String mqttLockPath = preferences->getString(preference_mqtt_lock_path); + + network = new NukiNetwork(preferences, gpio, mqttLockPath, CharBuffer::get(), buffer_size); + network->initialize(); + + lockEnabled = preferences->getBool(preference_lock_enabled); + openerEnabled = preferences->getBool(preference_opener_enabled); + + if(network->isApOpen()) + { + forceEnableWebServer = true; + doOta = false; + lockEnabled = false; + openerEnabled = false; + } + bleScanner = new BleScanner::Scanner(); // Scan interval and window according to Nuki recommendations: // https://developer.nuki.io/t/bluetooth-specification-questions/1109/27 bleScanner->initialize("NukiHub", true, 40, 40); bleScanner->setScanDuration(0); - lockEnabled = preferences->getBool(preference_lock_enabled); - openerEnabled = preferences->getBool(preference_opener_enabled); - - const String mqttLockPath = preferences->getString(preference_mqtt_lock_path); - nukiOfficial = new NukiOfficial(preferences); - network = new NukiNetwork(preferences, gpio, mqttLockPath, CharBuffer::get(), buffer_size); - network->initialize(); - networkLock = new NukiNetworkLock(network, nukiOfficial, preferences, CharBuffer::get(), buffer_size); networkLock->initialize(); @@ -498,15 +555,23 @@ void setup() { if(!doOta) { - asyncServer = new AsyncWebServer(80); + psychicServer = new PsychicHttpServer; + psychicServer->config.max_uri_handlers = 40; + psychicServer->config.stack_size = 8192; + psychicServer->listen(80); if(forceEnableWebServer || preferences->getBool(preference_webserver_enabled, true)) { - webCfgServer = new WebCfgServer(nuki, nukiOpener, network, gpio, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType, asyncServer); + webCfgServer = new WebCfgServer(nuki, nukiOpener, network, gpio, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType, psychicServer); webCfgServer->initialize(); - asyncServer->onNotFound([](AsyncWebServerRequest* request) { request->redirect("/"); }); + psychicServer->onNotFound([](PsychicRequest* request) + { + return request->redirect("/"); + }); } - else asyncServer->onNotFound([](AsyncWebServerRequest* request) { request->redirect("/webserial"); }); + /* +#ifdef DEBUG_NUKIHUB + else psychicServer->onNotFound([](PsychicRequest* request) { return request->redirect("/webserial"); }); if(preferences->getBool(preference_webserial_enabled, false)) { @@ -514,21 +579,27 @@ void setup() WebSerial.begin(asyncServer); WebSerial.setBuffer(1024); } - - asyncServer->begin(); +#endif + */ } } - #endif +#endif - if(doOta) setupTasks(true); - else setupTasks(false); - - #ifdef DEBUG_NUKIHUB + if(doOta) + { + setupTasks(true); + } + else + { + setupTasks(false); + } + +#ifdef DEBUG_NUKIHUB Log->print("Task Name\tStatus\tPrio\tHWM\tTask\tAffinity\n"); char stats_buffer[1024]; vTaskList(stats_buffer); Log->println(stats_buffer); - #endif +#endif } void loop() diff --git a/src/networkDevices/EthernetDevice.cpp b/src/networkDevices/EthernetDevice.cpp index 4a9f7cc..4ec1070 100644 --- a/src/networkDevices/EthernetDevice.cpp +++ b/src/networkDevices/EthernetDevice.cpp @@ -1,103 +1,54 @@ #include "EthernetDevice.h" #include "../PreferencesKeys.h" #include "../Logger.h" -#ifndef NUKI_HUB_UPDATER -#include "../MqttTopics.h" -#include "espMqttClient.h" -#endif #include "../RestartReason.h" +RTC_NOINIT_ATTR bool criticalEthFailure; +extern char WiFi_fallbackDetect[14]; + EthernetDevice::EthernetDevice(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) -: NetworkDevice(hostname, ipConfiguration), - _deviceName(deviceName), - _phy_addr(phy_addr), - _power(power), - _mdc(mdc), - _mdio(mdio), - _type(ethtype), - _clock_mode(clock_mode), - _useSpi(false), - _preferences(preferences) + : NetworkDevice(hostname, ipConfiguration), + _deviceName(deviceName), + _phy_addr(phy_addr), + _power(power), + _mdc(mdc), + _mdio(mdio), + _type(ethtype), + _clock_mode(clock_mode), + _useSpi(false), + _preferences(preferences) { init(); } EthernetDevice::EthernetDevice(const String &hostname, - Preferences *preferences, - const IPConfiguration *ipConfiguration, - const std::string &deviceName, - uint8_t phy_addr, - int cs, - int irq, - int rst, - int spi_sck, - int spi_miso, - int spi_mosi, - eth_phy_type_t ethtype) - : NetworkDevice(hostname, ipConfiguration), - _deviceName(deviceName), - _phy_addr(phy_addr), - _cs(cs), - _irq(irq), - _rst(rst), - _spi_sck(spi_sck), - _spi_miso(spi_miso), - _spi_mosi(spi_mosi), - _type(ethtype), - _useSpi(true), - _preferences(preferences) + Preferences *preferences, + const IPConfiguration *ipConfiguration, + const std::string &deviceName, + uint8_t phy_addr, + int cs, + int irq, + int rst, + int spi_sck, + int spi_miso, + int spi_mosi, + eth_phy_type_t ethtype) + : NetworkDevice(hostname, ipConfiguration), + _deviceName(deviceName), + _phy_addr(phy_addr), + _cs(cs), + _irq(irq), + _rst(rst), + _spi_sck(spi_sck), + _spi_miso(spi_miso), + _spi_mosi(spi_mosi), + _type(ethtype), + _useSpi(true), + _preferences(preferences) { init(); } -void EthernetDevice::init() -{ -#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); - - _useEncryption = caLength > 1; // length is 1 when empty - - if(_useEncryption) - { - Log->println(F("MQTT over TLS.")); - Log->println(_ca); - _mqttClientSecure = new espMqttClientSecure(espMqttClientTypes::UseInternalTask::NO); - _mqttClientSecure->setCACert(_ca); - if(crtLength > 1 && keyLength > 1) // length is 1 when empty - { - Log->println(F("MQTT with client certificate.")); - Log->println(_cert); - Log->println(_key); - _mqttClientSecure->setCertificate(_cert); - _mqttClientSecure->setPrivateKey(_key); - } - } else - { - Log->println(F("MQTT without TLS.")); - _mqttClient = new espMqttClient(espMqttClientTypes::UseInternalTask::NO); - } - - if(_preferences->getBool(preference_mqtt_log_enabled, false) || _preferences->getBool(preference_webserial_enabled, false)) - { - MqttLoggerMode mode; - - if(_preferences->getBool(preference_mqtt_log_enabled, false) && _preferences->getBool(preference_webserial_enabled, false)) mode = MqttLoggerMode::MqttAndSerialAndWeb; - else if (_preferences->getBool(preference_webserial_enabled, false)) mode = MqttLoggerMode::SerialAndWeb; - else mode = MqttLoggerMode::MqttAndSerial; - - _path = new char[200]; - memset(_path, 0, sizeof(_path)); - - String pathStr = _preferences->getString(preference_mqtt_lock_path); - pathStr.concat(mqtt_topic_log); - strcpy(_path, pathStr.c_str()); - Log = new MqttLogger(*getMqttClient(), _path, mode); - } -#endif -} - const String EthernetDevice::deviceName() const { return _deviceName.c_str(); @@ -106,30 +57,45 @@ const String EthernetDevice::deviceName() const void EthernetDevice::initialize() { delay(250); + if(criticalEthFailure) + { + criticalEthFailure = false; + Log->println(F("Failed to initialize ethernet hardware")); + Log->println("Network device has a critical failure, enable fallback to Wi-Fi and reboot."); + strcpy(WiFi_fallbackDetect, "wifi_fallback"); + delay(200); + restartEsp(RestartReason::NetworkDeviceCriticalFailure); + return; + } Log->println(F("Init Ethernet")); if(_useSpi) { Log->println(F("Use SPI")); + criticalEthFailure = true; SPI.begin(_spi_sck, _spi_miso, _spi_mosi); _hardwareInitialized = ETH.begin(_type, _phy_addr, _cs, _irq, _rst, SPI); + criticalEthFailure = false; } - #ifdef CONFIG_IDF_TARGET_ESP32 +#ifdef CONFIG_IDF_TARGET_ESP32 else { Log->println(F("Use RMII")); + criticalEthFailure = true; _hardwareInitialized = ETH.begin(_type, _phy_addr, _mdc, _mdio, _power, _clock_mode); + criticalEthFailure = false; if(!_ipConfiguration->dhcpEnabled()) { - _checkIpTs = (esp_timer_get_time() / 1000) + 2000; + _checkIpTs = espMillis() + 2000; } } - #endif +#endif if(_hardwareInitialized) { Log->println(F("Ethernet hardware Initialized")); + memset(WiFi_fallbackDetect, 0, sizeof(WiFi_fallbackDetect)); if(_useSpi && !_ipConfiguration->dhcpEnabled()) { @@ -144,20 +110,23 @@ void EthernetDevice::initialize() else { Log->println(F("Failed to initialize ethernet hardware")); + Log->println("Network device has a critical failure, enable fallback to Wi-Fi and reboot."); + strcpy(WiFi_fallbackDetect, "wifi_fallback"); + delay(200); + restartEsp(RestartReason::NetworkDeviceCriticalFailure); + return; } } void EthernetDevice::update() { - NetworkDevice::update(); - if(_checkIpTs != -1) { if(_ipConfiguration->ipAddress() != ETH.localIP()) { Log->println(F("ETH Set static IP")); ETH.config(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); - _checkIpTs = (esp_timer_get_time() / 1000) + 2000; + _checkIpTs = espMillis() + 2000; } else { @@ -169,69 +138,67 @@ void EthernetDevice::update() void EthernetDevice::onNetworkEvent(arduino_event_id_t event, arduino_event_info_t info) { - switch (event) { - case ARDUINO_EVENT_ETH_START: - Log->println("ETH Started"); - ETH.setHostname(_hostname.c_str()); - break; - case ARDUINO_EVENT_ETH_CONNECTED: - Log->println("ETH Connected"); - if(!localIP().equals("0.0.0.0")) - { - _connected = true; - } - break; - case ARDUINO_EVENT_ETH_GOT_IP: - Log->printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); - Log->println(ETH); - - // For RMII devices, this check is handled in the update() method. - if(_useSpi && !_ipConfiguration->dhcpEnabled() && _ipConfiguration->ipAddress() != ETH.localIP()) - { - Log->printf("Static IP not used, retrying to set static IP"); - ETH.config(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); - ETH.begin(_type, _phy_addr, _cs, _irq, _rst, SPI); - } - + switch (event) + { + case ARDUINO_EVENT_ETH_START: + Log->println("ETH Started"); + ETH.setHostname(_hostname.c_str()); + break; + case ARDUINO_EVENT_ETH_CONNECTED: + Log->println("ETH Connected"); + if(!localIP().equals("0.0.0.0")) + { _connected = true; - if(_preferences->getBool(preference_ntw_reconfigure, false)) - { - _preferences->putBool(preference_ntw_reconfigure, false); - } - break; - case ARDUINO_EVENT_ETH_LOST_IP: - Log->println("ETH Lost IP"); - _connected = false; - onDisconnected(); - break; - case ARDUINO_EVENT_ETH_DISCONNECTED: - Log->println("ETH Disconnected"); - _connected = false; - onDisconnected(); - break; - case ARDUINO_EVENT_ETH_STOP: - Log->println("ETH Stopped"); - _connected = false; - onDisconnected(); - break; - default: - Log->print("ETH Event: "); - Log->println(event); - break; + } + break; + case ARDUINO_EVENT_ETH_GOT_IP: + Log->printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); + Log->println(ETH); + + // For RMII devices, this check is handled in the update() method. + if(_useSpi && !_ipConfiguration->dhcpEnabled() && _ipConfiguration->ipAddress() != ETH.localIP()) + { + Log->printf("Static IP not used, retrying to set static IP"); + ETH.config(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); + ETH.begin(_type, _phy_addr, _cs, _irq, _rst, SPI); + } + + _connected = true; + if(_preferences->getBool(preference_ntw_reconfigure, false)) + { + _preferences->putBool(preference_ntw_reconfigure, false); + } + break; + case ARDUINO_EVENT_ETH_LOST_IP: + Log->println("ETH Lost IP"); + _connected = false; + onDisconnected(); + break; + case ARDUINO_EVENT_ETH_DISCONNECTED: + Log->println("ETH Disconnected"); + _connected = false; + onDisconnected(); + break; + case ARDUINO_EVENT_ETH_STOP: + Log->println("ETH Stopped"); + _connected = false; + onDisconnected(); + break; + default: + Log->print("ETH Event: "); + Log->println(event); + break; } } - - void EthernetDevice::reconfigure() { delay(200); restartEsp(RestartReason::ReconfigureETH); } -bool EthernetDevice::supportsEncryption() +void EthernetDevice::scan(bool passive, bool async) { - return true; } bool EthernetDevice::isConnected() @@ -239,20 +206,17 @@ bool EthernetDevice::isConnected() return _connected; } -ReconnectStatus EthernetDevice::reconnect(bool force) +bool EthernetDevice::isApOpen() { - if(!_hardwareInitialized) - { - return ReconnectStatus::CriticalFailure; - } - delay(200); - return isConnected() ? ReconnectStatus::Success : ReconnectStatus::Failure; + return false; } void EthernetDevice::onDisconnected() { - if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); - reconnect(); + if(_preferences->getBool(preference_restart_on_disconnect, false) && (espMillis() > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } } int8_t EthernetDevice::signalStrength() diff --git a/src/networkDevices/EthernetDevice.h b/src/networkDevices/EthernetDevice.h index dfb45dd..c68a22e 100644 --- a/src/networkDevices/EthernetDevice.h +++ b/src/networkDevices/EthernetDevice.h @@ -11,9 +11,6 @@ #include #include #include "NetworkDevice.h" -#ifndef NUKI_HUB_UPDATER -#include "espMqttClient.h" -#endif class EthernetDevice : public NetworkDevice { @@ -48,26 +45,23 @@ public: virtual void initialize(); virtual void reconfigure(); virtual void update(); - - virtual ReconnectStatus reconnect(bool force = false); - bool supportsEncryption() override; + virtual void scan(bool passive = false, bool async = true); virtual bool isConnected(); + virtual bool isApOpen(); int8_t signalStrength() override; - + String localIP() override; String BSSIDstr() override; private: Preferences* _preferences; - - void init(); + void onDisconnected(); void onNetworkEvent(arduino_event_id_t event, arduino_event_info_t info); bool _connected = false; - char* _path; bool _hardwareInitialized = false; const std::string _deviceName; @@ -91,10 +85,4 @@ private: eth_phy_type_t _type; eth_clock_mode_t _clock_mode; bool _useSpi = false; - - #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/IPConfiguration.cpp b/src/networkDevices/IPConfiguration.cpp index 4f374ad..fadcfb6 100644 --- a/src/networkDevices/IPConfiguration.cpp +++ b/src/networkDevices/IPConfiguration.cpp @@ -3,7 +3,7 @@ #include "../Logger.h" IPConfiguration::IPConfiguration(Preferences *preferences) -: _preferences(preferences) + : _preferences(preferences) { if(!dhcpEnabled() && _preferences->getString(preference_ip_address, "").length() <= 0) { @@ -23,10 +23,14 @@ IPConfiguration::IPConfiguration(Preferences *preferences) } else { - Log->print(F("IP address: ")); Log->print(ipAddress()); - Log->print(F(", Subnet: ")); Log->print(subnet()); - Log->print(F(", Gateway: ")); Log->print(defaultGateway()); - Log->print(F(", DNS: ")); Log->println(dnsServer()); + Log->print(F("IP address: ")); + Log->print(ipAddress()); + Log->print(F(", Subnet: ")); + Log->print(subnet()); + Log->print(F(", Gateway: ")); + Log->print(defaultGateway()); + Log->print(F(", DNS: ")); + Log->println(dnsServer()); } } diff --git a/src/networkDevices/NetworkDevice.cpp b/src/networkDevices/NetworkDevice.cpp index 9e65acd..bcea055 100644 --- a/src/networkDevices/NetworkDevice.cpp +++ b/src/networkDevices/NetworkDevice.cpp @@ -1,179 +1,6 @@ #include #include "NetworkDevice.h" -#include "../Logger.h" -void NetworkDevice::printError() -{ - Log->print(F("Free Heap: ")); - Log->println(ESP.getFreeHeap()); -} - -#ifndef NUKI_HUB_UPDATER void NetworkDevice::update() { - if (_mqttEnabled) - { - getMqttClient()->loop(); - } -} - -void NetworkDevice::mqttSetClientId(const char *clientId) -{ - if (_useEncryption) - { - _mqttClientSecure->setClientId(clientId); - } - else - { - _mqttClient->setClientId(clientId); - } -} - -void NetworkDevice::mqttSetCleanSession(bool cleanSession) -{ - if (_useEncryption) - { - _mqttClientSecure->setCleanSession(cleanSession); - } - else - { - _mqttClient->setCleanSession(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); -} - -uint16_t NetworkDevice::mqttPublish(const char *topic, uint8_t qos, bool retain, const uint8_t *payload, size_t length) -{ - return getMqttClient()->publish(topic, qos, retain, payload, length); -} - -bool NetworkDevice::mqttConnected() const -{ - return getMqttClient()->connected(); -} - -void NetworkDevice::mqttSetServer(const char *host, uint16_t port) -{ - if (_useEncryption) - { - _mqttClientSecure->setServer(host, port); - } - else - { - _mqttClient->setServer(host, port); - } -} - -bool NetworkDevice::mqttConnect() -{ - return getMqttClient()->connect(); -} - -bool NetworkDevice::mqttDisconnect(bool force) -{ - return getMqttClient()->disconnect(force); -} - -void NetworkDevice::setWill(const char *topic, uint8_t qos, bool retain, const char *payload) -{ - if (_useEncryption) - { - _mqttClientSecure->setWill(topic, qos, retain, payload); - } - else - { - _mqttClient->setWill(topic, qos, retain, payload); - } -} - -void NetworkDevice::mqttSetCredentials(const char *username, const char *password) -{ - if (_useEncryption) - { - _mqttClientSecure->setCredentials(username, password); - } - else - { - _mqttClient->setCredentials(username, password); - } -} - -void NetworkDevice::mqttOnMessage(espMqttClientTypes::OnMessageCallback callback) -{ - if (_useEncryption) - { - _mqttClientSecure->onMessage(callback); - } - else - { - _mqttClient->onMessage(callback); - } -} - -void NetworkDevice::mqttOnConnect(espMqttClientTypes::OnConnectCallback callback) -{ - if(_useEncryption) - { - _mqttClientSecure->onConnect(callback); - } - else - { - _mqttClient->onConnect(callback); - } -} - -void NetworkDevice::mqttOnDisconnect(espMqttClientTypes::OnDisconnectCallback callback) -{ - if (_useEncryption) - { - _mqttClientSecure->onDisconnect(callback); - } - else - { - _mqttClient->onDisconnect(callback); - } -} - -uint16_t NetworkDevice::mqttSubscribe(const char *topic, uint8_t qos) -{ - return getMqttClient()->subscribe(topic, qos); -} - -void NetworkDevice::disableMqtt() -{ - getMqttClient()->disconnect(); - _mqttEnabled = false; -} - -MqttClient *NetworkDevice::getMqttClient() const -{ - if (_useEncryption) - { - return _mqttClientSecure; - } - else - { - return _mqttClient; - } -} -#else -void NetworkDevice::update() -{ -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/src/networkDevices/NetworkDevice.h b/src/networkDevices/NetworkDevice.h index fdf9065..abbade2 100644 --- a/src/networkDevices/NetworkDevice.h +++ b/src/networkDevices/NetworkDevice.h @@ -1,17 +1,6 @@ #pragma once - -#ifndef NUKI_HUB_UPDATER -#include "espMqttClient.h" -#include "MqttClientSetup.h" -#endif #include "IPConfiguration.h" - -enum class ReconnectStatus -{ - Failure = 0, - Success = 1, - CriticalFailure = 2 -}; +#include "../EspMillis.h" class NetworkDevice { @@ -24,50 +13,17 @@ public: virtual const String deviceName() const = 0; virtual void initialize() = 0; - virtual ReconnectStatus reconnect(bool force = false) = 0; virtual void reconfigure() = 0; - virtual void printError(); - virtual bool supportsEncryption() = 0; - virtual void update(); + virtual void scan(bool passive = false, bool async = true) = 0; virtual bool isConnected() = 0; + virtual bool isApOpen() = 0; virtual int8_t signalStrength() = 0; 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; - virtual void mqttSetServer(const char* host, uint16_t port); - virtual bool mqttConnect(); - virtual bool mqttDisconnect(bool force); - virtual void setWill(const char* topic, uint8_t qos, bool retain, const char* payload); - virtual void mqttSetCredentials(const char* username, const char* password); - virtual void mqttOnMessage(espMqttClientTypes::OnMessageCallback callback); - virtual void mqttOnConnect(espMqttClientTypes::OnConnectCallback callback); - virtual void mqttOnDisconnect(espMqttClientTypes::OnDisconnectCallback callback); - 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 - +protected: const String _hostname; const IPConfiguration* _ipConfiguration = nullptr; }; \ No newline at end of file diff --git a/src/networkDevices/WifiDevice.cpp b/src/networkDevices/WifiDevice.cpp index dc32369..8625db3 100644 --- a/src/networkDevices/WifiDevice.cpp +++ b/src/networkDevices/WifiDevice.cpp @@ -1,66 +1,14 @@ +#include "esp_wifi.h" #include #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]; - WifiDevice::WifiDevice(const String& hostname, Preferences* preferences, const IPConfiguration* ipConfiguration) -: NetworkDevice(hostname, ipConfiguration), - _preferences(preferences), - _wm(preferences->getString(preference_cred_user, "").c_str(), preferences->getString(preference_cred_password, "").c_str()) + : NetworkDevice(hostname, ipConfiguration), + _preferences(preferences) { - _startAp = strcmp(WiFiDevice_reconfdetect, "reconfigure_wifi") == 0; - - #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); - - _useEncryption = caLength > 1; // length is 1 when empty - - if(_useEncryption) - { - Log->println(F("MQTT over TLS.")); - Log->println(_ca); - _mqttClientSecure = new espMqttClientSecure(espMqttClientTypes::UseInternalTask::NO); - _mqttClientSecure->setCACert(_ca); - if(crtLength > 1 && keyLength > 1) // length is 1 when empty - { - Log->println(F("MQTT with client certificate.")); - Log->println(_cert); - Log->println(_key); - _mqttClientSecure->setCertificate(_cert); - _mqttClientSecure->setPrivateKey(_key); - } - } else - { - Log->println(F("MQTT without TLS.")); - _mqttClient = new espMqttClient(espMqttClientTypes::UseInternalTask::NO); - } - - if(preferences->getBool(preference_mqtt_log_enabled, false) || preferences->getBool(preference_webserial_enabled, false)) - { - MqttLoggerMode mode; - - if(preferences->getBool(preference_mqtt_log_enabled, false) && preferences->getBool(preference_webserial_enabled, false)) mode = MqttLoggerMode::MqttAndSerialAndWeb; - else if (preferences->getBool(preference_webserial_enabled, false)) mode = MqttLoggerMode::SerialAndWeb; - else mode = MqttLoggerMode::MqttAndSerial; - - _path = new char[200]; - memset(_path, 0, sizeof(_path)); - - String pathStr = preferences->getString(preference_mqtt_lock_path); - pathStr.concat(mqtt_topic_log); - strcpy(_path, pathStr.c_str()); - Log = new MqttLogger(*getMqttClient(), _path, mode); - } - #endif } const String WifiDevice::deviceName() const @@ -70,128 +18,390 @@ const String WifiDevice::deviceName() const void WifiDevice::initialize() { - std::vector wm_menu; - wm_menu.push_back("wifi"); - wm_menu.push_back("exit"); - _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled, false)); - // reduced timeout if ESP is set to restart on disconnect - _wm.setFindBestRSSI(_preferences->getBool(preference_find_best_rssi)); - _wm.setConnectTimeout(20); - _wm.setConfigPortalTimeout(_preferences->getBool(preference_restart_on_disconnect, false) ? 60 * 3 : 60 * 30); - _wm.setShowInfoUpdate(false); - _wm.setMenu(wm_menu); - _wm.setHostname(_hostname); - - if(!_ipConfiguration->dhcpEnabled()) - { - _wm.setSTAStaticIPConfig(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); - } - - _wm.setAPCallback(clearRtcInitVar); - - bool res = false; - bool connectedFromPortal = false; - - if(_startAp) - { - Log->println(F("Opening Wi-Fi configuration portal.")); - res = _wm.startConfigPortal(); - connectedFromPortal = true; - } - else - { - res = _wm.autoConnect(); // password protected ap - } - - if(!res) - { - esp_wifi_disconnect(); - esp_wifi_stop(); - esp_wifi_deinit(); - - Log->println(F("Failed to connect. Wait for ESP restart.")); - delay(1000); - restartEsp(RestartReason::WifiInitFailed); - } - else { - Log->print(F("Wi-Fi connected: ")); - Log->println(WiFi.localIP().toString()); - - if(connectedFromPortal) - { - Log->println(F("Connected using WifiManager portal. Wait for ESP restart.")); - delay(1000); - restartEsp(RestartReason::ConfigurationUpdated); - } - } + String ssid = _preferences->getString(preference_wifi_ssid, ""); + String pass = _preferences->getString(preference_wifi_pass, ""); + WiFi.setHostname(_hostname.c_str()); WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { - if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED || event == ARDUINO_EVENT_WIFI_STA_STOP) { - onDisconnected(); + if(!_openAP && !_connecting && _connected) + { + onDisconnected(); + _hasIP = false; + } } else if(event == ARDUINO_EVENT_WIFI_STA_GOT_IP) + { + _hasIP = true; + } + else if(event == ARDUINO_EVENT_WIFI_STA_LOST_IP) + { + _hasIP = false; + } + else if(event == ARDUINO_EVENT_WIFI_STA_CONNECTED) { onConnected(); } + else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE) + { + Log->println(F("Wi-Fi scan done")); + _foundNetworks = WiFi.scanComplete(); + + for (int i = 0; i < _foundNetworks; i++) + { + Log->println(String(F("SSID ")) + WiFi.SSID(i) + String(F(" found with RSSI: ")) + + String(WiFi.RSSI(i)) + String(F("(")) + + String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + + String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + + String(F(" and channel: ")) + String(WiFi.channel(i))); + } + + if (_connectOnScanDone && _foundNetworks > 0) + { + connect(); + } + else if (_connectOnScanDone) + { + Log->println("No networks found, restarting scan"); + scan(false, true); + } + else if (_openAP) + { + openAP(); + } + else if(_convertOldWiFi) + { + Log->println("Trying to convert old WiFi settings"); + _convertOldWiFi = false; + _preferences->putBool(preference_wifi_converted, true); + + wifi_config_t wifi_cfg; + if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { + Log->println("Failed to get Wi-Fi configuration in RAM"); + } + + if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK) + { + Log->println("Failed to set storage Wi-Fi"); + } + + String tempSSID = String(reinterpret_cast(wifi_cfg.sta.ssid)); + String tempPass = String(reinterpret_cast(wifi_cfg.sta.password)); + tempSSID.trim(); + tempPass.trim(); + bool found = false; + + for (int i = 0; i < _foundNetworks; i++) + { + if(tempSSID.length() > 0 && tempSSID == WiFi.SSID(i) && tempPass.length() > 0) + { + _preferences->putString(preference_wifi_ssid, tempSSID); + _preferences->putString(preference_wifi_pass, tempPass); + Log->println("Succesfully converted old WiFi settings"); + found = true; + break; + } + } + + memset(wifi_cfg.sta.ssid, 0, sizeof(wifi_cfg.sta.ssid)); + memset(wifi_cfg.sta.password, 0, sizeof(wifi_cfg.sta.password)); + + if (esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { + Log->println("Failed to clear NVS Wi-Fi configuration"); + } + + if(found) + { + Log->println(String("Attempting to connect to saved SSID ") + String(ssid)); + _connectOnScanDone = true; + _openAP = false; + scan(false, true); + return; + } + else + { + restartEsp(RestartReason::ReconfigureWifi); + return; + } + } + } }); + + ssid.trim(); + pass.trim(); + + if(ssid.length() > 0 && pass.length() > 0) + { + Log->println(String("Attempting to connect to saved SSID ") + String(ssid)); + _connectOnScanDone = true; + _openAP = false; + scan(false, true); + return; + } + else if(!_preferences->getBool(preference_wifi_converted, false)) + { + _connectOnScanDone = false; + _openAP = false; + _convertOldWiFi = true; + scan(false, true); + return; + } + else + { + Log->println("No SSID or Wifi password saved, opening AP"); + _connectOnScanDone = false; + _openAP = true; + scan(false, true); + return; + } +} + +void WifiDevice::scan(bool passive, bool async) +{ + if(!_connecting) + { + WiFi.scanDelete(); + WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); + WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); + + if(async) + { + Log->println(F("Wi-Fi async scan started")); + } + else + { + Log->println(F("Wi-Fi sync scan started")); + } + if(passive) + { + WiFi.scanNetworks(async,false,true,75U); + } + else + { + WiFi.scanNetworks(async); + } + } +} + +void WifiDevice::openAP() +{ + if(_startAP) + { + WiFi.mode(WIFI_AP_STA); + WiFi.softAPsetHostname(_hostname.c_str()); + WiFi.softAP("NukiHub", "NukiHubESP32"); + _startAP = false; + } +} + +bool WifiDevice::connect() +{ + bool ret = false; + String ssid = _preferences->getString(preference_wifi_ssid, ""); + String pass = _preferences->getString(preference_wifi_pass, ""); + WiFi.mode(WIFI_STA); + WiFi.setHostname(_hostname.c_str()); + delay(500); + + int bestConnection = -1; + for (int i = 0; i < _foundNetworks; i++) + { + if (ssid == WiFi.SSID(i)) + { + Log->println(String(F("Saved SSID ")) + ssid + String(F(" found with RSSI: ")) + + String(WiFi.RSSI(i)) + String(F("(")) + + String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + + String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + + String(F(" and channel: ")) + String(WiFi.channel(i))); + if (bestConnection == -1) + { + bestConnection = i; + } + else + { + if (WiFi.RSSI(i) > WiFi.RSSI(bestConnection)) + { + bestConnection = i; + } + } + } + } + + if (bestConnection == -1) + { + Log->print("No network found with SSID: "); + Log->println(ssid); + if(_preferences->getBool(preference_restart_on_disconnect, false) && (espMillis() > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } + _connectOnScanDone = true; + _openAP = false; + scan(false, true); + return false; + } + else + { + _connecting = true; + esp_wifi_scan_stop(); + Log->println(String(F("Trying to connect to SSID ")) + ssid + String(F(" found with RSSI: ")) + + String(WiFi.RSSI(bestConnection)) + String(F("(")) + + String(constrain((100.0 + WiFi.RSSI(bestConnection)) * 2, 0, 100)) + + String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(bestConnection) + + String(F(" and channel: ")) + String(WiFi.channel(bestConnection))); + + + if(!_ipConfiguration->dhcpEnabled()) + { + WiFi.config(_ipConfiguration->ipAddress(), _ipConfiguration->dnsServer(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet()); + } + + WiFi.begin(ssid, pass); + auto status = WiFi.waitForConnectResult(10000); + + switch (status) + { + case WL_CONNECTED: + Log->println("WiFi connected"); + break; + case WL_NO_SSID_AVAIL: + Log->println("WiFi SSID not available"); + break; + case WL_CONNECT_FAILED: + Log->println("WiFi connection failed"); + break; + case WL_IDLE_STATUS: + Log->println("WiFi changing status"); + break; + case WL_DISCONNECTED: + Log->println("WiFi disconnected"); + break; + default: + Log->println("WiFi timeout"); + break; + } + + if (status != WL_CONNECTED) + { + if(_preferences->getBool(preference_restart_on_disconnect, false) && (espMillis() > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + _connecting = false; + return false; + } + Log->println("Retrying"); + _connectOnScanDone = true; + _openAP = false; + scan(false, true); + _connecting = false; + return false; + } + else + { + if(!_preferences->getBool(preference_wifi_converted, false)) + { + _preferences->putBool(preference_wifi_converted, true); + } + _connecting = false; + return true; + } + } + + return false; } void WifiDevice::reconfigure() { - strcpy(WiFiDevice_reconfdetect, "reconfigure_wifi"); + _preferences->putString(preference_wifi_ssid, ""); + _preferences->putString(preference_wifi_pass, ""); delay(200); restartEsp(RestartReason::ReconfigureWifi); } -bool WifiDevice::supportsEncryption() -{ - return true; -} - bool WifiDevice::isConnected() { - return WiFi.isConnected(); -} - -ReconnectStatus WifiDevice::reconnect(bool force) -{ - _wm.setFindBestRSSI(_preferences->getBool(preference_find_best_rssi)); - - if((!isConnected() || force) && !_isReconnecting) + if (WiFi.status() != WL_CONNECTED) { - _isReconnecting = true; - WiFi.disconnect(); - int loop = 0; - - while(isConnected() && loop <20) - { - delay(100); - loop++; - } - - _wm.resetScan(); - _wm.autoConnect(); - _isReconnecting = false; + return false; + } + if (!_hasIP) + { + return false; } - if(!isConnected() && _disconnectTs > (esp_timer_get_time() / 1000) - 120000) _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled, false)); - return isConnected() ? ReconnectStatus::Success : ReconnectStatus::Failure; + return true; } void WifiDevice::onConnected() { - _isReconnecting = false; - _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled, false)); + Log->println(F("Wi-Fi connected")); + _connectedChannel = WiFi.channel(); + _connectedBSSID = WiFi.BSSID(); + _connected = true; } void WifiDevice::onDisconnected() { - _disconnectTs = (esp_timer_get_time() / 1000); - if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); - _wm.setEnableConfigPortal(false); - reconnect(); + if(_connected) + { + _connected = false; + _disconnectTs = espMillis(); + Log->println(F("Wi-Fi disconnected")); + + //QUICK RECONNECT + _connecting = true; + String ssid = _preferences->getString(preference_wifi_ssid, ""); + String pass = _preferences->getString(preference_wifi_pass, ""); + + if(!_ipConfiguration->dhcpEnabled()) + { + WiFi.config(_ipConfiguration->ipAddress(), _ipConfiguration->dnsServer(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet()); + } + + WiFi.begin(ssid, pass); + + int loop = 0; + + while(!isConnected() && loop < 200) + { + loop++; + delay(100); + } + + _connecting = false; + //END QUICK RECONECT + + if(!isConnected()) + { + if(_preferences->getBool(preference_restart_on_disconnect, false) && (espMillis() > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } + + WiFi.disconnect(true); + WiFi.mode(WIFI_STA); + WiFi.disconnect(); + delay(500); + + wifi_mode_t wifiMode; + esp_wifi_get_mode(&wifiMode); + + while (wifiMode != WIFI_MODE_STA || WiFi.status() == WL_CONNECTED) + { + delay(500); + Log->println(F("Waiting for WiFi mode change or disconnection.")); + esp_wifi_get_mode(&wifiMode); + } + + _connectOnScanDone = true; + _openAP = false; + scan(false, true); + } + } } int8_t WifiDevice::signalStrength() @@ -209,7 +419,7 @@ String WifiDevice::BSSIDstr() return WiFi.BSSIDstr(); } -void WifiDevice::clearRtcInitVar(WiFiManager *) +bool WifiDevice::isApOpen() { - memset(WiFiDevice_reconfdetect, 0, sizeof WiFiDevice_reconfdetect); -} + return _openAP; +} \ No newline at end of file diff --git a/src/networkDevices/WifiDevice.h b/src/networkDevices/WifiDevice.h index 26aec2f..50e9d25 100644 --- a/src/networkDevices/WifiDevice.h +++ b/src/networkDevices/WifiDevice.h @@ -4,10 +4,6 @@ #include #include #include "NetworkDevice.h" -#include "WiFiManager.h" -#ifndef NUKI_HUB_UPDATER -#include "espMqttClient.h" -#endif #include "IPConfiguration.h" class WifiDevice : public NetworkDevice @@ -19,33 +15,33 @@ public: virtual void initialize(); virtual void reconfigure(); - virtual ReconnectStatus reconnect(bool force = false); - bool supportsEncryption() override; + virtual void scan(bool passive = false, bool async = true); virtual bool isConnected(); + virtual bool isApOpen(); int8_t signalStrength() override; String localIP() override; String BSSIDstr() override; - private: - static void clearRtcInitVar(WiFiManager*); - + void openAP(); void onDisconnected(); void onConnected(); + bool connect(); - WiFiManager _wm; Preferences* _preferences = nullptr; - bool _startAp = false; - bool _isReconnecting = false; - char* _path; + int _foundNetworks = 0; + int _disconnectCount = 0; + bool _connectOnScanDone = false; + bool _connecting = false; + bool _openAP = false; + bool _startAP = true; + bool _convertOldWiFi = false; + bool _connected = false; + bool _hasIP = false; + uint8_t _connectedChannel = 0; + uint8_t* _connectedBSSID; int64_t _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/src/util/NetworkDeviceInstantiator.cpp b/src/util/NetworkDeviceInstantiator.cpp index 0b46666..af4fda5 100644 --- a/src/util/NetworkDeviceInstantiator.cpp +++ b/src/util/NetworkDeviceInstantiator.cpp @@ -13,153 +13,153 @@ NetworkDevice *NetworkDeviceInstantiator::Create(NetworkDeviceType networkDevice switch (networkDeviceType) { - case NetworkDeviceType::W5500: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "Generic W5500", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_GENERIC_W5500, - ETH_PHY_IRQ_GENERIC_W5500, - ETH_PHY_RST_GENERIC_W5500, - ETH_PHY_SPI_SCK_GENERIC_W5500, - ETH_PHY_SPI_MISO_GENERIC_W5500, - ETH_PHY_SPI_MOSI_GENERIC_W5500, - ETH_PHY_W5500); - break; - case NetworkDeviceType::W5500M5: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_M5_W5500, - ETH_PHY_IRQ_M5_W5500, - ETH_PHY_RST_M5_W5500, - ETH_PHY_SPI_SCK_M5_W5500, - ETH_PHY_SPI_MISO_M5_W5500, - ETH_PHY_SPI_MOSI_M5_W5500, - ETH_PHY_W5500); - break; - case NetworkDeviceType::W5500M5S3: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE S3", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_M5_W5500_S3, - ETH_PHY_IRQ_M5_W5500, - ETH_PHY_RST_M5_W5500, - ETH_PHY_SPI_SCK_M5_W5500_S3, - ETH_PHY_SPI_MISO_M5_W5500_S3, - ETH_PHY_SPI_MOSI_M5_W5500_S3, - ETH_PHY_W5500); - break; - case NetworkDeviceType::ETH01_Evo: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "ETH01-Evo", - ETH_PHY_ADDR_ETH01EVO, - ETH_PHY_CS_ETH01EVO, - ETH_PHY_IRQ_ETH01EVO, - ETH_PHY_RST_ETH01EVO, - ETH_PHY_SPI_SCK_ETH01EVO, - ETH_PHY_SPI_MISO_ETH01EVO, - ETH_PHY_SPI_MOSI_ETH01EVO, - ETH_PHY_TYPE_DM9051); - break; - case NetworkDeviceType::M5STACK_PoESP32_Unit: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5STACK PoESP32 Unit", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_M5_W5500, - ETH_PHY_IRQ_M5_W5500, - ETH_PHY_RST_M5_W5500, - ETH_PHY_SPI_SCK_M5_W5500, - ETH_PHY_SPI_MISO_M5_W5500, - ETH_PHY_SPI_MOSI_M5_W5500, - ETH_PHY_W5500); - break; - case NetworkDeviceType::CUSTOM: + case NetworkDeviceType::W5500: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "Generic W5500", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_GENERIC_W5500, + ETH_PHY_IRQ_GENERIC_W5500, + ETH_PHY_RST_GENERIC_W5500, + ETH_PHY_SPI_SCK_GENERIC_W5500, + ETH_PHY_SPI_MISO_GENERIC_W5500, + ETH_PHY_SPI_MOSI_GENERIC_W5500, + ETH_PHY_W5500); + break; + case NetworkDeviceType::W5500M5: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_M5_W5500, + ETH_PHY_IRQ_M5_W5500, + ETH_PHY_RST_M5_W5500, + ETH_PHY_SPI_SCK_M5_W5500, + ETH_PHY_SPI_MISO_M5_W5500, + ETH_PHY_SPI_MOSI_M5_W5500, + ETH_PHY_W5500); + break; + case NetworkDeviceType::W5500M5S3: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE S3", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_M5_W5500_S3, + ETH_PHY_IRQ_M5_W5500, + ETH_PHY_RST_M5_W5500, + ETH_PHY_SPI_SCK_M5_W5500_S3, + ETH_PHY_SPI_MISO_M5_W5500_S3, + ETH_PHY_SPI_MOSI_M5_W5500_S3, + ETH_PHY_W5500); + break; + case NetworkDeviceType::ETH01_Evo: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "ETH01-Evo", + ETH_PHY_ADDR_ETH01EVO, + ETH_PHY_CS_ETH01EVO, + ETH_PHY_IRQ_ETH01EVO, + ETH_PHY_RST_ETH01EVO, + ETH_PHY_SPI_SCK_ETH01EVO, + ETH_PHY_SPI_MISO_ETH01EVO, + ETH_PHY_SPI_MOSI_ETH01EVO, + ETH_PHY_TYPE_DM9051); + break; + case NetworkDeviceType::M5STACK_PoESP32_Unit: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5STACK PoESP32 Unit", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_M5_W5500, + ETH_PHY_IRQ_M5_W5500, + ETH_PHY_RST_M5_W5500, + ETH_PHY_SPI_SCK_M5_W5500, + ETH_PHY_SPI_MISO_M5_W5500, + ETH_PHY_SPI_MOSI_M5_W5500, + ETH_PHY_W5500); + break; + case NetworkDeviceType::CUSTOM: + { + int custPHY = preferences->getInt(preference_network_custom_phy, 0); + + if(custPHY >= 1 && custPHY <= 3) { - int custPHY = preferences->getInt(preference_network_custom_phy, 0); + std::string custName; + eth_phy_type_t custEthtype; - if(custPHY >= 1 && custPHY <= 3) + switch(custPHY) { - std::string custName; - eth_phy_type_t custEthtype; - - switch(custPHY) - { - case 1: - custName = "Custom (W5500)"; - custEthtype = ETH_PHY_W5500; - break; - case 2: - custName = "Custom (DN9051)"; - custEthtype = ETH_PHY_DM9051; - break; - case 3: - custName = "Custom (KSZ8851SNL)"; - custEthtype = ETH_PHY_KSZ8851; - break; - default: - custName = "Custom (W5500)"; - custEthtype = ETH_PHY_W5500; - break; - } - - device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, - preferences->getInt(preference_network_custom_addr, -1), - preferences->getInt(preference_network_custom_cs, -1), - preferences->getInt(preference_network_custom_irq, -1), - preferences->getInt(preference_network_custom_rst, -1), - preferences->getInt(preference_network_custom_sck, -1), - preferences->getInt(preference_network_custom_miso, -1), - preferences->getInt(preference_network_custom_mosi, -1), - custEthtype); - } -#if defined(CONFIG_IDF_TARGET_ESP32) - else if(custPHY >= 4 && custPHY <= 9) - { - int custCLKpref = preferences->getInt(preference_network_custom_clk, 0); - - std::string custName = NetworkUtil::GetCustomEthernetDeviceName(custPHY); - eth_phy_type_t custEthtype = NetworkUtil::GetCustomEthernetType(custPHY); - eth_clock_mode_t custCLK = NetworkUtil::GetCustomClock(custCLKpref); - - device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, preferences->getInt(preference_network_custom_addr, -1), preferences->getInt(preference_network_custom_pwr, -1), preferences->getInt(preference_network_custom_mdc, -1), preferences->getInt(preference_network_custom_mdio, -1), custEthtype, custCLK); - } -#endif -#ifndef CONFIG_IDF_TARGET_ESP32H2 - else - { - device = new WifiDevice(hostname, preferences, ipConfiguration); - } -#endif - } - break; -#if defined(CONFIG_IDF_TARGET_ESP32) - case NetworkDeviceType::Olimex_LAN8720: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "Olimex (LAN8720)", ETH_PHY_ADDR_LAN8720, 12, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); - break; - case NetworkDeviceType::WT32_LAN8720: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "WT32-ETH01", 1, 16); - break; - case NetworkDeviceType::GL_S10: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "GL-S10", 1, 5, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_IP101, ETH_CLOCK_GPIO0_IN); - break; - case NetworkDeviceType::LilyGO_T_ETH_POE: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "LilyGO T-ETH-POE", 0, -1, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); - break; -#endif -#ifndef CONFIG_IDF_TARGET_ESP32H2 - case NetworkDeviceType::WiFi: - device = new WifiDevice(hostname, preferences, ipConfiguration); - break; - default: - device = new WifiDevice(hostname, preferences, ipConfiguration); - break; -#else + case 1: + custName = "Custom (W5500)"; + custEthtype = ETH_PHY_W5500; + break; + case 2: + custName = "Custom (DN9051)"; + custEthtype = ETH_PHY_DM9051; + break; + case 3: + custName = "Custom (KSZ8851SNL)"; + custEthtype = ETH_PHY_KSZ8851; + break; default: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "Custom (W5500)", - preferences->getInt(preference_network_custom_addr, -1), - preferences->getInt(preference_network_custom_cs, -1), - preferences->getInt(preference_network_custom_irq, -1), - preferences->getInt(preference_network_custom_rst, -1), - preferences->getInt(preference_network_custom_sck, -1), - preferences->getInt(preference_network_custom_miso, -1), - preferences->getInt(preference_network_custom_mosi, -1), - ETH_PHY_W5500); - break; + custName = "Custom (W5500)"; + custEthtype = ETH_PHY_W5500; + break; + } + + device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, + preferences->getInt(preference_network_custom_addr, -1), + preferences->getInt(preference_network_custom_cs, -1), + preferences->getInt(preference_network_custom_irq, -1), + preferences->getInt(preference_network_custom_rst, -1), + preferences->getInt(preference_network_custom_sck, -1), + preferences->getInt(preference_network_custom_miso, -1), + preferences->getInt(preference_network_custom_mosi, -1), + custEthtype); + } +#if defined(CONFIG_IDF_TARGET_ESP32) + else if(custPHY >= 4 && custPHY <= 9) + { + int custCLKpref = preferences->getInt(preference_network_custom_clk, 0); + + std::string custName = NetworkUtil::GetCustomEthernetDeviceName(custPHY); + eth_phy_type_t custEthtype = NetworkUtil::GetCustomEthernetType(custPHY); + eth_clock_mode_t custCLK = NetworkUtil::GetCustomClock(custCLKpref); + + device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, preferences->getInt(preference_network_custom_addr, -1), preferences->getInt(preference_network_custom_pwr, -1), preferences->getInt(preference_network_custom_mdc, -1), preferences->getInt(preference_network_custom_mdio, -1), custEthtype, custCLK); + } +#endif +#ifndef CONFIG_IDF_TARGET_ESP32H2 + else + { + device = new WifiDevice(hostname, preferences, ipConfiguration); + } +#endif + } + break; +#if defined(CONFIG_IDF_TARGET_ESP32) + case NetworkDeviceType::Olimex_LAN8720: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "Olimex (LAN8720)", ETH_PHY_ADDR_LAN8720, 12, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); + break; + case NetworkDeviceType::WT32_LAN8720: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "WT32-ETH01", 1, 16); + break; + case NetworkDeviceType::GL_S10: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "GL-S10", 1, 5, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_IP101, ETH_CLOCK_GPIO0_IN); + break; + case NetworkDeviceType::LilyGO_T_ETH_POE: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "LilyGO T-ETH-POE", 0, -1, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); + break; +#endif +#ifndef CONFIG_IDF_TARGET_ESP32H2 + case NetworkDeviceType::WiFi: + device = new WifiDevice(hostname, preferences, ipConfiguration); + break; + default: + device = new WifiDevice(hostname, preferences, ipConfiguration); + break; +#else + default: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "Custom (W5500)", + preferences->getInt(preference_network_custom_addr, -1), + preferences->getInt(preference_network_custom_cs, -1), + preferences->getInt(preference_network_custom_irq, -1), + preferences->getInt(preference_network_custom_rst, -1), + preferences->getInt(preference_network_custom_sck, -1), + preferences->getInt(preference_network_custom_miso, -1), + preferences->getInt(preference_network_custom_mosi, -1), + ETH_PHY_W5500); + break; #endif } diff --git a/src/util/NetworkUtil.cpp b/src/util/NetworkUtil.cpp index 603b4e8..1dc057d 100644 --- a/src/util/NetworkUtil.cpp +++ b/src/util/NetworkUtil.cpp @@ -6,50 +6,50 @@ NetworkDeviceType NetworkUtil::GetDeviceTypeFromPreference(int hardwareDetect, i { switch (hardwareDetect) { - case 1: + case 1: + return NetworkDeviceType::WiFi; + break; + case 2: + return NetworkDeviceType::W5500; + break; + case 3: + return NetworkDeviceType::W5500M5; + break; + case 4: + return NetworkDeviceType::Olimex_LAN8720; + break; + case 5: + return NetworkDeviceType::WT32_LAN8720; + break; + case 6: + return NetworkDeviceType::M5STACK_PoESP32_Unit; + break; + case 7: + return NetworkDeviceType::LilyGO_T_ETH_POE; + break; + case 8: + return NetworkDeviceType::GL_S10; + break; + case 9: + return NetworkDeviceType::ETH01_Evo; + break; + case 10: + return NetworkDeviceType::W5500M5S3; + break; + case 11: + if(customPhy> 0) + { + return NetworkDeviceType::CUSTOM; + } + else + { return NetworkDeviceType::WiFi; - break; - case 2: - return NetworkDeviceType::W5500; - break; - case 3: - return NetworkDeviceType::W5500M5; - break; - case 4: - return NetworkDeviceType::Olimex_LAN8720; - break; - case 5: - return NetworkDeviceType::WT32_LAN8720; - break; - case 6: - return NetworkDeviceType::M5STACK_PoESP32_Unit; - break; - case 7: - return NetworkDeviceType::LilyGO_T_ETH_POE; - break; - case 8: - return NetworkDeviceType::GL_S10; - break; - case 9: - return NetworkDeviceType::ETH01_Evo; - break; - case 10: - return NetworkDeviceType::W5500M5S3; - break; - case 11: - if(customPhy> 0) - { - return NetworkDeviceType::CUSTOM; - } - else - { - return NetworkDeviceType::WiFi; - } - break; - default: - Log->println(F("Unknown hardware selected, falling back to Wi-Fi.")); - return NetworkDeviceType::WiFi; - break; + } + break; + default: + Log->println(F("Unknown hardware selected, falling back to Wi-Fi.")); + return NetworkDeviceType::WiFi; + break; } } @@ -57,20 +57,20 @@ std::string NetworkUtil::GetCustomEthernetDeviceName(int custPHY) { switch(custPHY) { - case 4: - return "Custom (LAN8720)"; - case 5: - return"Custom (RTL8201)"; - case 6: - return "Custom (TLK110)"; - case 7: - return "Custom (DP83848)"; - case 8: - return "Custom (KSZ8041)"; - case 9: - return "Custom (KSZ8081)"; - default: - return"Custom (LAN8720)"; + case 4: + return "Custom (LAN8720)"; + case 5: + return"Custom (RTL8201)"; + case 6: + return "Custom (TLK110)"; + case 7: + return "Custom (DP83848)"; + case 8: + return "Custom (KSZ8041)"; + case 9: + return "Custom (KSZ8081)"; + default: + return"Custom (LAN8720)"; } } @@ -79,27 +79,27 @@ eth_phy_type_t NetworkUtil::GetCustomEthernetType(int custPHY) { switch(custPHY) { - case 4: - return ETH_PHY_TYPE_LAN8720; - break; - case 5: - return ETH_PHY_RTL8201; - break; - case 6: - return ETH_PHY_TLK110; - break; - case 7: - return ETH_PHY_DP83848; - break; - case 8: - return ETH_PHY_KSZ8041; - break; - case 9: - return ETH_PHY_KSZ8081; - break; - default: - return ETH_PHY_TYPE_LAN8720; - break; + case 4: + return ETH_PHY_TYPE_LAN8720; + break; + case 5: + return ETH_PHY_RTL8201; + break; + case 6: + return ETH_PHY_TLK110; + break; + case 7: + return ETH_PHY_DP83848; + break; + case 8: + return ETH_PHY_KSZ8041; + break; + case 9: + return ETH_PHY_KSZ8081; + break; + default: + return ETH_PHY_TYPE_LAN8720; + break; } } @@ -107,18 +107,18 @@ eth_clock_mode_t NetworkUtil::GetCustomClock(int custCLKpref) { switch(custCLKpref) { - case 0: - return ETH_CLOCK_GPIO0_IN; - break; - case 2: - return ETH_CLOCK_GPIO16_OUT; - break; - case 3: - return ETH_CLOCK_GPIO17_OUT; - break; - default: - return ETH_CLOCK_GPIO17_OUT; - break; + case 0: + return ETH_CLOCK_GPIO0_IN; + break; + case 2: + return ETH_CLOCK_GPIO16_OUT; + break; + case 3: + return ETH_CLOCK_GPIO17_OUT; + break; + default: + return ETH_CLOCK_GPIO17_OUT; + break; } } #endif \ No newline at end of file diff --git a/updater/platformio.ini b/updater/platformio.ini index 6b85fb6..41ca4ca 100644 --- a/updater/platformio.ini +++ b/updater/platformio.ini @@ -24,7 +24,8 @@ board_build.embed_txtfiles = build_type = release custom_build = release board_build.partitions = partitions.csv -build_unflags = +build_unflags = + -DESP32 -Werror=all -Wall build_flags = @@ -53,9 +54,8 @@ lib_ignore = SimpleBLE WiFiProv lib_deps = - AsyncTCP=symlink://../lib/AsyncTCP - ESPAsyncWebServer=symlink://../lib/ESPAsyncWebServer - WiFiManager=symlink://../lib/WiFiManager + PsychicHttp=symlink://../lib/PsychicHttp + ArduinoJson=symlink://../lib/ArduinoJson monitor_speed = 115200 monitor_filters = @@ -96,8 +96,7 @@ board = esp32-h2-devkitm-1 board_build.cmake_extra_args = -DNUKI_TARGET_H2=y lib_deps = - AsyncTCP=symlink://../lib/AsyncTCP - ESPAsyncWebServer=symlink://../lib/ESPAsyncWebServer + PsychicHttp=symlink://../lib/PsychicHttp [env:updater_esp32-solo1] extends = env:updater_esp32 diff --git a/updater/sdkconfig.defaults b/updater/sdkconfig.defaults index e60db16..14d722b 100644 --- a/updater/sdkconfig.defaults +++ b/updater/sdkconfig.defaults @@ -22,4 +22,13 @@ CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_SPI_ETHERNET=y CONFIG_ETH_SPI_ETHERNET_W5500=y CONFIG_ETH_SPI_ETHERNET_DM9051=y -CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL=y \ No newline at end of file +CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH=y +CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH=y +CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024 +CONFIG_HTTPD_MAX_URI_LEN=512 +CONFIG_HTTPD_ERR_RESP_NO_DELAY=y +CONFIG_HTTPD_PURGE_BUF_LEN=32 +CONFIG_HTTPD_WS_SUPPORT=y +CONFIG_ESP_HTTPS_SERVER_ENABLE=y \ No newline at end of file