diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 53e05a3..fe77009 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,11 +29,10 @@ Please ensure to specify the following: Arduino IDE version: 1.8.19 ESP32 Core Version 2.0.5 OS: Ubuntu 20.04 LTS -Linux xy-Inspiron-3593 5.15.0-50-generic #56~20.04.1-Ubuntu SMP Tue Sep 27 15:51:29 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux +Linux xy-Inspiron-3593 5.15.0-52-generic #58~20.04.1-Ubuntu SMP Thu Oct 13 13:09:46 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux Context: -I encountered a crash when using this library - +I encountered a crash while using this library Steps to reproduce: 1. ... 2. ... @@ -41,13 +40,37 @@ Steps to reproduce: 4. ... ``` +### Additional context + +Add any other context about the problem here. + +--- + ### Sending Feature Requests Feel free to post feature requests. It's helpful if you can explain exactly why the feature would be useful. There are usually some outstanding feature requests in the [existing issues list](https://github.com/khoih-prog/AsyncHTTPSRequest_Generic/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement), feel free to add comments to them. +--- + ### Sending Pull Requests Pull Requests with changes and fixes are also welcome! +Please use the `astyle` to reformat the updated library code as follows (demo for Ubuntu Linux) + +1. Change directory to the library GitHub + +``` +xy@xy-Inspiron-3593:~$ cd Arduino/xy/AsyncHTTPSRequest_Generic_GitHub/ +xy@xy-Inspiron-3593:~/Arduino/xy/AsyncHTTPSRequest_Generic_GitHub$ +``` + +2. Issue astyle command + +``` +xy@xy-Inspiron-3593:~/Arduino/xy/AsyncHTTPSRequest_Generic_GitHub$ bash utils/restyle.sh +``` + + diff --git a/changelog.md b/changelog.md index 62cd73b..cff40d6 100644 --- a/changelog.md +++ b/changelog.md @@ -11,6 +11,7 @@ ## Table of Contents * [Changelog](#changelog) + * [Releases v2.2.1](#releases-v221) * [Releases v2.2.0](#releases-v220) * [Releases v2.1.3](#releases-v213) * [Releases v2.1.2](#releases-v212) @@ -32,6 +33,11 @@ ## Changelog +### Releases v2.2.1 + +1. Default to reconnect to the same `host:port` after connected for new HTTP sites. Check [Host/Headers not always sent with 1.10.1 #44](https://github.com/khoih-prog/AsyncHTTPRequest_Generic/issues/44) and [Getting 400 Bad Request on second call to same host #14](https://github.com/khoih-prog/AsyncHTTPSRequest_Generic/issues/14) +2. Use `allman astyle` and add `utils` + ### Releases v2.2.0 1. Fix crash when turn-on debug or start diff --git a/examples/AsyncHTTPSRequest_ESP/AsyncHTTPSRequest_ESP.ino b/examples/AsyncHTTPSRequest_ESP/AsyncHTTPSRequest_ESP.ino index 4fc8a62..9536f6d 100644 --- a/examples/AsyncHTTPSRequest_ESP/AsyncHTTPSRequest_ESP.ino +++ b/examples/AsyncHTTPSRequest_ESP/AsyncHTTPSRequest_ESP.ino @@ -41,11 +41,16 @@ //************************************************************************************************************* #if !( defined(ESP8266) || defined(ESP32) ) - #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. + #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. #endif -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.0" -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002000 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.1" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002001 + +///////////////////////////////////////////////////////// + +// Uncomment for certain HTTP site to optimize +//#define NOT_SEND_HEADER_AFTER_CONNECTED true // Level from 0-4 #define ASYNC_HTTPS_DEBUG_PORT Serial @@ -65,9 +70,9 @@ const char* ssid = "your_ssid"; const char* password = "your_pass"; #if (ESP8266) - #include + #include #elif (ESP32) - #include + #include #endif // Use larger queue size if necessary for large data transfer. Default is 512 bytes if not defined here @@ -87,124 +92,129 @@ Ticker ticker1; void heartBeatPrint() { - static int num = 1; - - if (WiFi.status() == WL_CONNECTED) - Serial.print(F("H")); // H means connected to WiFi - else - Serial.print(F("F")); // F means not connected to WiFi - - if (num == 80) - { - Serial.println(); - num = 1; - } - else if (num++ % 10 == 0) - { - Serial.print(F(" ")); - } + static int num = 1; + + if (WiFi.status() == WL_CONNECTED) + Serial.print(F("H")); // H means connected to WiFi + else + Serial.print(F("F")); // F means not connected to WiFi + + if (num == 80) + { + Serial.println(); + num = 1; + } + else if (num++ % 10 == 0) + { + Serial.print(F(" ")); + } } void sendRequest() { - static bool requestOpenResult; - - if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) - { - //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/Europe/London.txt"); - //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); - requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); - - if (requestOpenResult) - { - // Only send() if open() returns true, or crash - request.send(); - } - else - { - Serial.println(F("Can't send bad request")); - } - } - else - { - Serial.println(F("Can't send request")); - } + static bool requestOpenResult; + + if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) + { + //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/Europe/London.txt"); + //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); + requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); + + if (requestOpenResult) + { + // Only send() if open() returns true, or crash + request.send(); + } + else + { + Serial.println(F("Can't send bad request")); + } + } + else + { + Serial.println(F("Can't send request")); + } } void requestCB(void *optParm, AsyncHTTPSRequest *request, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), request->responseHTTPString()); - - if (request->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(request->responseText()); - Serial.println(F("**************************************")); - } - - request->setDebug(false); - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), request->responseHTTPString()); + + if (request->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(request->responseText()); + Serial.println(F("**************************************")); + } + + request->setDebug(false); + } } void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - while (!Serial && millis() < 5000); + // put your setup code here, to run once: + Serial.begin(115200); + + while (!Serial && millis() < 5000); - delay(200); + delay(200); - Serial.print(F("\nStarting AsyncHTTPSRequest_ESP using ")); Serial.println(ARDUINO_BOARD); + Serial.print(F("\nStarting AsyncHTTPSRequest_ESP using ")); + Serial.println(ARDUINO_BOARD); #if defined(ESP32) - Serial.println(ASYNC_TCP_SSL_VERSION); + Serial.println(ASYNC_TCP_SSL_VERSION); #else - //Serial.println(ESPASYNC_TCP_SSL_VERSION); + //Serial.println(ESPASYNC_TCP_SSL_VERSION); #endif - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); #if defined(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif - WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_STA); - WiFi.begin(ssid, password); + WiFi.begin(ssid, password); - Serial.print(F("Connecting to WiFi SSID: ")); Serial.println(ssid); + Serial.print(F("Connecting to WiFi SSID: ")); + Serial.println(ssid); - while (WiFi.status() != WL_CONNECTED) - { - delay(500); - Serial.print("."); - } + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print("."); + } - Serial.print(F("\nAsyncHTTPSRequest @ IP : ")); - Serial.println(WiFi.localIP()); + Serial.print(F("\nAsyncHTTPSRequest @ IP : ")); + Serial.println(WiFi.localIP()); - request.setDebug(false); + request.setDebug(false); - request.onReadyStateChange(requestCB); + request.onReadyStateChange(requestCB); - ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequest); + ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequest); - ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); + ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); - // Send first request now - sendRequest(); + // Send first request now + sendRequest(); } void loop() { - //delay(1); + //delay(1); } diff --git a/examples/AsyncHTTPSRequest_ESP_Multi/AsyncHTTPSRequest_ESP_Multi.ino b/examples/AsyncHTTPSRequest_ESP_Multi/AsyncHTTPSRequest_ESP_Multi.ino index 767e568..756c7e2 100644 --- a/examples/AsyncHTTPSRequest_ESP_Multi/AsyncHTTPSRequest_ESP_Multi.ino +++ b/examples/AsyncHTTPSRequest_ESP_Multi/AsyncHTTPSRequest_ESP_Multi.ino @@ -41,11 +41,16 @@ //************************************************************************************************************* #if !( defined(ESP8266) || defined(ESP32) ) - #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. + #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. #endif -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.0" -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002000 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.1" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002001 + +///////////////////////////////////////////////////////// + +// Uncomment for certain HTTP site to optimize +//#define NOT_SEND_HEADER_AFTER_CONNECTED true // Level from 0-4 #define ASYNC_HTTPS_DEBUG_PORT Serial @@ -65,9 +70,9 @@ const char* ssid = "your_ssid"; const char* password = "your_pass"; #if (ESP8266) - #include + #include #elif (ESP32) - #include + #include #endif // Use larger queue size if necessary for large data transfer. Default is 512 bytes if not defined here @@ -83,10 +88,10 @@ const char* password = "your_pass"; #define NUM_DIFFERENT_SITES 2 -const char* addreses[][NUM_DIFFERENT_SITES] = +const char* addreses[][NUM_DIFFERENT_SITES] = { - {"https://worldtimeapi.org/api/timezone/America/Toronto.txt", "https://worldtimeapi.org/api/timezone/Europe/Prague.txt"}, - {"https://www.myexternalip.com/raw"} + {"https://worldtimeapi.org/api/timezone/America/Toronto.txt", "https://worldtimeapi.org/api/timezone/Europe/Prague.txt"}, + {"https://www.myexternalip.com/raw"} }; #define NUM_ENTRIES_SITE_0 2 @@ -114,172 +119,177 @@ Ticker ticker1; void heartBeatPrint() { - static int num = 1; - - if (WiFi.status() == WL_CONNECTED) - Serial.print(F("H")); // H means connected to WiFi - else - Serial.print(F("F")); // F means not connected to WiFi - - if (num == 80) - { - Serial.println(); - num = 1; - } - else if (num++ % 10 == 0) - { - Serial.print(F(" ")); - } + static int num = 1; + + if (WiFi.status() == WL_CONNECTED) + Serial.print(F("H")); // H means connected to WiFi + else + Serial.print(F("F")); // F means not connected to WiFi + + if (num == 80) + { + Serial.println(); + num = 1; + } + else if (num++ % 10 == 0) + { + Serial.print(F(" ")); + } } void sendRequest(uint16_t index) { - static bool requestOpenResult; - - reqCount[index]--; - readySend[index] = false; - - requestOpenResult = request[index].open("GET", addreses[index][reqCount[index]]); - - if (requestOpenResult) - { - // Only send() if open() returns true, or crash - Serial.print("\nSending request: "); - request[index].send(); - } - else - { - Serial.print("\nCan't send bad request : "); - } - - Serial.println(addreses[index][reqCount[index]]); + static bool requestOpenResult; + + reqCount[index]--; + readySend[index] = false; + + requestOpenResult = request[index].open("GET", addreses[index][reqCount[index]]); + + if (requestOpenResult) + { + // Only send() if open() returns true, or crash + Serial.print("\nSending request: "); + request[index].send(); + } + else + { + Serial.print("\nCan't send bad request : "); + } + + Serial.println(addreses[index][reqCount[index]]); } void sendRequest0() { - sendRequest(0); + sendRequest(0); } void sendRequest1() { - sendRequest(1); + sendRequest(1); } void sendRequests() { - for (int index = 0; index < NUM_DIFFERENT_SITES; index++) - { - reqCount[index] = 2; - } - reqCount[0] = NUM_ENTRIES_SITE_0; - reqCount[1] = NUM_ENTRIES_SITE_1; + for (int index = 0; index < NUM_DIFFERENT_SITES; index++) + { + reqCount[index] = 2; + } + + reqCount[0] = NUM_ENTRIES_SITE_0; + reqCount[1] = NUM_ENTRIES_SITE_1; } void requestCB0(void *optParm, AsyncHTTPSRequest *thisRequest, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); - - if (thisRequest->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(thisRequest->responseText()); - Serial.println(F("**************************************")); - } - - thisRequest->setDebug(false); - readySend[0] = true; - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); + + if (thisRequest->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(thisRequest->responseText()); + Serial.println(F("**************************************")); + } + + thisRequest->setDebug(false); + readySend[0] = true; + } } void requestCB1(void *optParm, AsyncHTTPSRequest *thisRequest, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); - - if (thisRequest->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(thisRequest->responseText()); - Serial.println(F("**************************************")); - } - - thisRequest->setDebug(false); - readySend[1] = true; - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); + + if (thisRequest->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(thisRequest->responseText()); + Serial.println(F("**************************************")); + } + + thisRequest->setDebug(false); + readySend[1] = true; + } } void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - while (!Serial && millis() < 5000); + // put your setup code here, to run once: + Serial.begin(115200); + + while (!Serial && millis() < 5000); - delay(200); + delay(200); - Serial.print("\nStarting AsyncHTTPSRequest_ESP_Multi on "); Serial.println(ARDUINO_BOARD); + Serial.print("\nStarting AsyncHTTPSRequest_ESP_Multi on "); + Serial.println(ARDUINO_BOARD); #if defined(ESP32) - Serial.println(ASYNC_TCP_SSL_VERSION); + Serial.println(ASYNC_TCP_SSL_VERSION); #else - //Serial.println(ESPASYNC_TCP_SSL_VERSION); + //Serial.println(ESPASYNC_TCP_SSL_VERSION); #endif - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); #if defined(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif - WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_STA); - WiFi.begin(ssid, password); + WiFi.begin(ssid, password); - Serial.println("Connecting to WiFi SSID: " + String(ssid)); + Serial.println("Connecting to WiFi SSID: " + String(ssid)); - while (WiFi.status() != WL_CONNECTED) - { - delay(500); - Serial.print("."); - } + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print("."); + } - Serial.print(F("\nAsyncHTTPSRequest @ IP : ")); - Serial.println(WiFi.localIP()); + Serial.print(F("\nAsyncHTTPSRequest @ IP : ")); + Serial.println(WiFi.localIP()); - for (int index = 0; index < NUM_DIFFERENT_SITES; index++) - { - request[index].setDebug(false); + for (int index = 0; index < NUM_DIFFERENT_SITES; index++) + { + request[index].setDebug(false); - request[index].onReadyStateChange(requestCB[index]); - } + request[index].onReadyStateChange(requestCB[index]); + } - ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequests); + ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequests); - ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); + ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); } void loop() { - for (int index = 0; index < NUM_DIFFERENT_SITES; index++) - { - if ((reqCount[index] > 0) && readySend[index]) - { - sendRequestCB[index](); - - // Don't reduce this or possible crash. TLS needs long time to work. - delay(100); - } - } + for (int index = 0; index < NUM_DIFFERENT_SITES; index++) + { + if ((reqCount[index] > 0) && readySend[index]) + { + sendRequestCB[index](); + + // Don't reduce this or possible crash. TLS needs long time to work. + delay(100); + } + } } diff --git a/examples/AsyncHTTPSRequest_ESP_WiFiManager/AsyncHTTPSRequest_ESP_WiFiManager.ino b/examples/AsyncHTTPSRequest_ESP_WiFiManager/AsyncHTTPSRequest_ESP_WiFiManager.ino index 50e82f9..4d4006b 100644 --- a/examples/AsyncHTTPSRequest_ESP_WiFiManager/AsyncHTTPSRequest_ESP_WiFiManager.ino +++ b/examples/AsyncHTTPSRequest_ESP_WiFiManager/AsyncHTTPSRequest_ESP_WiFiManager.ino @@ -1,6 +1,6 @@ /**************************************************************************************************************************** AsyncHTTPSRequest_ESP_WiFiManager.ino - Dead simple AsyncHTTPRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet - + For ESP8266, ESP32 and STM32 with built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc) AsyncHTTPSRequest_Generic is a library for the ESP8266, ESP32 and currently STM32 run built-in Ethernet WebServer @@ -43,17 +43,20 @@ // Important note: This code is intended to run with the ESPAsync_WiFiManager library version 1.4.1+. #if !( defined(ESP8266) || defined(ESP32) ) - #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. + #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. #endif -#define ESP_ASYNC_WIFIMANAGER_VERSION_MIN_TARGET "ESPAsync_WiFiManager v1.15.0" -#define ESP_ASYNC_WIFIMANAGER_VERSION_MIN 1015000 +#define ESP_ASYNC_WIFIMANAGER_VERSION_MIN_TARGET "ESPAsync_WiFiManager v1.15.1" +#define ESP_ASYNC_WIFIMANAGER_VERSION_MIN 1015001 -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.0" -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002000 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.1" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002001 ///////////////////////////////////////////////////////// +// Uncomment for certain HTTP site to optimize +//#define NOT_SEND_HEADER_AFTER_CONNECTED true + // Use larger queue size if necessary for large data transfer. Default is 512 bytes if not defined here //#define ASYNC_QUEUE_LENGTH 512 @@ -74,93 +77,93 @@ //Ported to ESP32 #ifdef ESP32 - #include - #include - #include - - // From v1.1.1 - #include - WiFiMulti wifiMulti; - - // LittleFS has higher priority than SPIFFS - #define USE_LITTLEFS true - #define USE_SPIFFS false - - #if USE_LITTLEFS - // Use LittleFS - #include "FS.h" - - // The library will be depreciated after being merged to future major Arduino esp32 core release 2.x - // At that time, just remove this library inclusion - #if ( defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 2) ) - #warning Using ESP32 Core 1.0.6 or 2.0.0+ and core LittleFS library - // The library has been merged into esp32 core from release 1.0.6 - #include // https://github.com/espressif/arduino-esp32/tree/master/libraries/LittleFS - - //#define FileFS LittleFS - //#define FS_Name "LittleFS" - FS* filesystem = &LittleFS; - #define FileFS LittleFS - #else - #warning Using ESP32 Core 1.0.5-. You must install LITTLEFS library - // The library has been merged into esp32 core from release 1.0.6 - #include // https://github.com/lorol/LITTLEFS - - //#define FileFS LITTLEFS - FS* filesystem = &LITTLEFS; - #define FileFS LITTLEFS - #endif - - #define FS_Name "LittleFS" - #elif USE_SPIFFS - #include - FS* filesystem = &SPIFFS; - #define FileFS SPIFFS - #define FS_Name "SPIFFS" - #else - // +Use FFat - #include - FS* filesystem = &FFat; - #define FileFS FFat - #define FS_Name "FFat" - #endif - ////// - - #if !defined(LED_BUILTIN) - #define LED_BUILTIN 2 - #endif - - #define LED_ON HIGH - #define LED_OFF LOW + #include + #include + #include + + // From v1.1.1 + #include + WiFiMulti wifiMulti; + + // LittleFS has higher priority than SPIFFS + #define USE_LITTLEFS true + #define USE_SPIFFS false + + #if USE_LITTLEFS + // Use LittleFS + #include "FS.h" + + // The library will be depreciated after being merged to future major Arduino esp32 core release 2.x + // At that time, just remove this library inclusion + #if ( defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 2) ) + #warning Using ESP32 Core 1.0.6 or 2.0.0+ and core LittleFS library + // The library has been merged into esp32 core from release 1.0.6 + #include // https://github.com/espressif/arduino-esp32/tree/master/libraries/LittleFS + + //#define FileFS LittleFS + //#define FS_Name "LittleFS" + FS* filesystem = &LittleFS; + #define FileFS LittleFS + #else + #warning Using ESP32 Core 1.0.5-. You must install LITTLEFS library + // The library has been merged into esp32 core from release 1.0.6 + #include // https://github.com/lorol/LITTLEFS + + //#define FileFS LITTLEFS + FS* filesystem = &LITTLEFS; + #define FileFS LITTLEFS + #endif + + #define FS_Name "LittleFS" + #elif USE_SPIFFS + #include + FS* filesystem = &SPIFFS; + #define FileFS SPIFFS + #define FS_Name "SPIFFS" + #else + // +Use FFat + #include + FS* filesystem = &FFat; + #define FileFS FFat + #define FS_Name "FFat" + #endif + ////// + + #if !defined(LED_BUILTIN) + #define LED_BUILTIN 2 + #endif + + #define LED_ON HIGH + #define LED_OFF LOW #else - #include //https://github.com/esp8266/Arduino - //needed for library - #include - - // From v1.1.1 - #include - ESP8266WiFiMulti wifiMulti; - - #define USE_LITTLEFS true - - #if USE_LITTLEFS - #include - FS* filesystem = &LittleFS; - #define FileFS LittleFS - #define FS_Name "LittleFS" - #else - FS* filesystem = &SPIFFS; - #define FileFS SPIFFS - #define FS_Name "SPIFFS" - #endif - ////// - - #define ESP_getChipId() (ESP.getChipId()) - - #define LED_ON LOW - #define LED_OFF HIGH + #include //https://github.com/esp8266/Arduino + //needed for library + #include + + // From v1.1.1 + #include + ESP8266WiFiMulti wifiMulti; + + #define USE_LITTLEFS true + + #if USE_LITTLEFS + #include + FS* filesystem = &LittleFS; + #define FileFS LittleFS + #define FS_Name "LittleFS" + #else + FS* filesystem = &SPIFFS; + #define FileFS SPIFFS + #define FS_Name "SPIFFS" + #endif + ////// + + #define ESP_getChipId() (ESP.getChipId()) + + #define LED_ON LOW + #define LED_OFF HIGH #endif // SSID and PW for your Router @@ -180,21 +183,21 @@ String Router_Pass; typedef struct { - char wifi_ssid[SSID_MAX_LEN]; - char wifi_pw [PASS_MAX_LEN]; + char wifi_ssid[SSID_MAX_LEN]; + char wifi_pw [PASS_MAX_LEN]; } WiFi_Credentials; typedef struct { - String wifi_ssid; - String wifi_pw; + String wifi_ssid; + String wifi_pw; } WiFi_Credentials_String; #define NUM_WIFI_CREDENTIALS 2 typedef struct { - WiFi_Credentials WiFi_Creds [NUM_WIFI_CREDENTIALS]; + WiFi_Credentials WiFi_Creds [NUM_WIFI_CREDENTIALS]; } WM_Config; WM_Config WM_config; @@ -229,35 +232,35 @@ bool initialConfig = false; // Use USE_DHCP_IP == true for dynamic DHCP IP, false to use static IP which you have to change accordingly to your network #if (defined(USE_STATIC_IP_CONFIG_IN_CP) && !USE_STATIC_IP_CONFIG_IN_CP) -// Force DHCP to be true - #if defined(USE_DHCP_IP) - #undef USE_DHCP_IP - #endif - #define USE_DHCP_IP true + // Force DHCP to be true + #if defined(USE_DHCP_IP) + #undef USE_DHCP_IP + #endif + #define USE_DHCP_IP true #else - // You can select DHCP or Static IP here - #define USE_DHCP_IP true - //#define USE_DHCP_IP false + // You can select DHCP or Static IP here + #define USE_DHCP_IP true + //#define USE_DHCP_IP false #endif #if ( USE_DHCP_IP || ( defined(USE_STATIC_IP_CONFIG_IN_CP) && !USE_STATIC_IP_CONFIG_IN_CP ) ) - // Use DHCP - #warning Using DHCP IP - IPAddress stationIP = IPAddress(0, 0, 0, 0); - IPAddress gatewayIP = IPAddress(192, 168, 2, 1); - IPAddress netMask = IPAddress(255, 255, 255, 0); + // Use DHCP + #warning Using DHCP IP + IPAddress stationIP = IPAddress(0, 0, 0, 0); + IPAddress gatewayIP = IPAddress(192, 168, 2, 1); + IPAddress netMask = IPAddress(255, 255, 255, 0); #else - // Use static IP - #warning Using static IP - - #ifdef ESP32 - IPAddress stationIP = IPAddress(192, 168, 2, 232); - #else - IPAddress stationIP = IPAddress(192, 168, 2, 186); - #endif - - IPAddress gatewayIP = IPAddress(192, 168, 2, 1); - IPAddress netMask = IPAddress(255, 255, 255, 0); + // Use static IP + #warning Using static IP + + #ifdef ESP32 + IPAddress stationIP = IPAddress(192, 168, 2, 232); + #else + IPAddress stationIP = IPAddress(192, 168, 2, 186); + #endif + + IPAddress gatewayIP = IPAddress(192, 168, 2, 1); + IPAddress netMask = IPAddress(255, 255, 255, 0); #endif #define USE_CONFIGURABLE_DNS true @@ -294,25 +297,25 @@ Ticker ticker; /////////////////////////////////////////// // New in v1.4.0 /****************************************** - * // Defined in ESPAsync_WiFiManager.h -typedef struct -{ + // Defined in ESPAsync_WiFiManager.h + typedef struct + { IPAddress _ap_static_ip; IPAddress _ap_static_gw; IPAddress _ap_static_sn; -} WiFi_AP_IPConfig; + } WiFi_AP_IPConfig; -typedef struct -{ + typedef struct + { IPAddress _sta_static_ip; IPAddress _sta_static_gw; IPAddress _sta_static_sn; -#if USE_CONFIGURABLE_DNS + #if USE_CONFIGURABLE_DNS IPAddress _sta_static_dns1; IPAddress _sta_static_dns2; -#endif -} WiFi_STA_IPConfig; + #endif + } WiFi_STA_IPConfig; ******************************************/ WiFi_AP_IPConfig WM_AP_IPconfig; @@ -320,40 +323,40 @@ WiFi_STA_IPConfig WM_STA_IPconfig; void initAPIPConfigStruct(WiFi_AP_IPConfig &in_WM_AP_IPconfig) { - in_WM_AP_IPconfig._ap_static_ip = APStaticIP; - in_WM_AP_IPconfig._ap_static_gw = APStaticGW; - in_WM_AP_IPconfig._ap_static_sn = APStaticSN; + in_WM_AP_IPconfig._ap_static_ip = APStaticIP; + in_WM_AP_IPconfig._ap_static_gw = APStaticGW; + in_WM_AP_IPconfig._ap_static_sn = APStaticSN; } void initSTAIPConfigStruct(WiFi_STA_IPConfig &in_WM_STA_IPconfig) { - in_WM_STA_IPconfig._sta_static_ip = stationIP; - in_WM_STA_IPconfig._sta_static_gw = gatewayIP; - in_WM_STA_IPconfig._sta_static_sn = netMask; -#if USE_CONFIGURABLE_DNS - in_WM_STA_IPconfig._sta_static_dns1 = dns1IP; - in_WM_STA_IPconfig._sta_static_dns2 = dns2IP; + in_WM_STA_IPconfig._sta_static_ip = stationIP; + in_WM_STA_IPconfig._sta_static_gw = gatewayIP; + in_WM_STA_IPconfig._sta_static_sn = netMask; +#if USE_CONFIGURABLE_DNS + in_WM_STA_IPconfig._sta_static_dns1 = dns1IP; + in_WM_STA_IPconfig._sta_static_dns2 = dns2IP; #endif } void displayIPConfigStruct(WiFi_STA_IPConfig in_WM_STA_IPconfig) { - LOGERROR3(F("stationIP ="), in_WM_STA_IPconfig._sta_static_ip, F(", gatewayIP ="), in_WM_STA_IPconfig._sta_static_gw); - LOGERROR1(F("netMask ="), in_WM_STA_IPconfig._sta_static_sn); + LOGERROR3(F("stationIP ="), in_WM_STA_IPconfig._sta_static_ip, F(", gatewayIP ="), in_WM_STA_IPconfig._sta_static_gw); + LOGERROR1(F("netMask ="), in_WM_STA_IPconfig._sta_static_sn); #if USE_CONFIGURABLE_DNS - LOGERROR3(F("dns1IP ="), in_WM_STA_IPconfig._sta_static_dns1, F(", dns2IP ="), in_WM_STA_IPconfig._sta_static_dns2); + LOGERROR3(F("dns1IP ="), in_WM_STA_IPconfig._sta_static_dns1, F(", dns2IP ="), in_WM_STA_IPconfig._sta_static_dns2); #endif } void configWiFi(WiFi_STA_IPConfig in_WM_STA_IPconfig) { - #if USE_CONFIGURABLE_DNS - // Set static IP, Gateway, Subnetmask, DNS1 and DNS2. New in v1.0.5 - WiFi.config(in_WM_STA_IPconfig._sta_static_ip, in_WM_STA_IPconfig._sta_static_gw, in_WM_STA_IPconfig._sta_static_sn, in_WM_STA_IPconfig._sta_static_dns1, in_WM_STA_IPconfig._sta_static_dns2); - #else - // Set static IP, Gateway, Subnetmask, Use auto DNS1 and DNS2. - WiFi.config(in_WM_STA_IPconfig._sta_static_ip, in_WM_STA_IPconfig._sta_static_gw, in_WM_STA_IPconfig._sta_static_sn); - #endif +#if USE_CONFIGURABLE_DNS + // Set static IP, Gateway, Subnetmask, DNS1 and DNS2. New in v1.0.5 + WiFi.config(in_WM_STA_IPconfig._sta_static_ip, in_WM_STA_IPconfig._sta_static_gw, in_WM_STA_IPconfig._sta_static_sn, in_WM_STA_IPconfig._sta_static_dns1, in_WM_STA_IPconfig._sta_static_dns2); +#else + // Set static IP, Gateway, Subnetmask, Use auto DNS1 and DNS2. + WiFi.config(in_WM_STA_IPconfig._sta_static_ip, in_WM_STA_IPconfig._sta_static_gw, in_WM_STA_IPconfig._sta_static_sn); +#endif } /////////////////////////////////////////// @@ -361,473 +364,483 @@ void configWiFi(WiFi_STA_IPConfig in_WM_STA_IPconfig) uint8_t connectMultiWiFi() { #if ESP32 - // For ESP32, this better be 0 to shorten the connect time. - // For ESP32-S2, must be > 500 - #if ( ARDUINO_ESP32S2_DEV || ARDUINO_FEATHERS2 || ARDUINO_PROS2 || ARDUINO_MICROS2 ) - #define WIFI_MULTI_1ST_CONNECT_WAITING_MS 500L - #else - // For ESP32 core v1.0.6, must be >= 500 - #define WIFI_MULTI_1ST_CONNECT_WAITING_MS 800L - #endif + // For ESP32, this better be 0 to shorten the connect time. + // For ESP32-S2, must be > 500 +#if ( ARDUINO_ESP32S2_DEV || ARDUINO_FEATHERS2 || ARDUINO_PROS2 || ARDUINO_MICROS2 ) +#define WIFI_MULTI_1ST_CONNECT_WAITING_MS 500L #else - // For ESP8266, this better be 2200 to enable connect the 1st time - #define WIFI_MULTI_1ST_CONNECT_WAITING_MS 2200L + // For ESP32 core v1.0.6, must be >= 500 +#define WIFI_MULTI_1ST_CONNECT_WAITING_MS 800L +#endif +#else + // For ESP8266, this better be 2200 to enable connect the 1st time +#define WIFI_MULTI_1ST_CONNECT_WAITING_MS 2200L #endif #define WIFI_MULTI_CONNECT_WAITING_MS 100L - - uint8_t status; - LOGERROR(F("ConnectMultiWiFi with :")); - - if ( (Router_SSID != "") && (Router_Pass != "") ) - { - LOGERROR3(F("* Flash-stored Router_SSID = "), Router_SSID, F(", Router_Pass = "), Router_Pass ); - } + uint8_t status; - for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) - { - // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) - if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != "") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) - { - LOGERROR3(F("* Additional SSID = "), WM_config.WiFi_Creds[i].wifi_ssid, F(", PW = "), WM_config.WiFi_Creds[i].wifi_pw ); - } - } - - LOGERROR(F("Connecting MultiWifi...")); + LOGERROR(F("ConnectMultiWiFi with :")); + + if ( (Router_SSID != "") && (Router_Pass != "") ) + { + LOGERROR3(F("* Flash-stored Router_SSID = "), Router_SSID, F(", Router_Pass = "), Router_Pass ); + } + + for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) + { + // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) + if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != "") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) + { + LOGERROR3(F("* Additional SSID = "), WM_config.WiFi_Creds[i].wifi_ssid, F(", PW = "), WM_config.WiFi_Creds[i].wifi_pw ); + } + } - WiFi.mode(WIFI_STA); + LOGERROR(F("Connecting MultiWifi...")); + + WiFi.mode(WIFI_STA); #if !USE_DHCP_IP - // New in v1.4.0 - configWiFi(WM_STA_IPconfig); - ////// + // New in v1.4.0 + configWiFi(WM_STA_IPconfig); + ////// #endif - int i = 0; - status = wifiMulti.run(); + int i = 0; + status = wifiMulti.run(); - delay(WIFI_MULTI_1ST_CONNECT_WAITING_MS); + delay(WIFI_MULTI_1ST_CONNECT_WAITING_MS); - while ( ( i++ < 20 ) && ( status != WL_CONNECTED ) ) - { - status = wifiMulti.run(); + while ( ( i++ < 20 ) && ( status != WL_CONNECTED ) ) + { + status = wifiMulti.run(); - if ( status == WL_CONNECTED ) - break; - else - delay(WIFI_MULTI_CONNECT_WAITING_MS); - } + if ( status == WL_CONNECTED ) + break; + else + delay(WIFI_MULTI_CONNECT_WAITING_MS); + } - if ( status == WL_CONNECTED ) - { - LOGERROR1(F("WiFi connected after time: "), i); - LOGERROR3(F("SSID:"), WiFi.SSID(), F(",RSSI="), WiFi.RSSI()); - LOGERROR3(F("Channel:"), WiFi.channel(), F(",IP address:"), WiFi.localIP() ); - } - else - LOGERROR(F("WiFi not connected")); - - return status; + if ( status == WL_CONNECTED ) + { + LOGERROR1(F("WiFi connected after time: "), i); + LOGERROR3(F("SSID:"), WiFi.SSID(), F(",RSSI="), WiFi.RSSI()); + LOGERROR3(F("Channel:"), WiFi.channel(), F(",IP address:"), WiFi.localIP() ); + } + else + LOGERROR(F("WiFi not connected")); + + return status; } void heartBeatPrint() { - static int num = 1; - - if (WiFi.status() == WL_CONNECTED) - Serial.print(F("H")); // H means connected to WiFi - else - Serial.print(F("F")); // F means not connected to WiFi - - if (num == 80) - { - Serial.println(); - num = 1; - } - else if (num++ % 10 == 0) - { - Serial.print(F(" ")); - } + static int num = 1; + + if (WiFi.status() == WL_CONNECTED) + Serial.print(F("H")); // H means connected to WiFi + else + Serial.print(F("F")); // F means not connected to WiFi + + if (num == 80) + { + Serial.println(); + num = 1; + } + else if (num++ % 10 == 0) + { + Serial.print(F(" ")); + } } void check_WiFi() { - if ( (WiFi.status() != WL_CONNECTED) ) - { - Serial.println(F("\nWiFi lost. Call connectMultiWiFi in loop")); - connectMultiWiFi(); - } -} + if ( (WiFi.status() != WL_CONNECTED) ) + { + Serial.println(F("\nWiFi lost. Call connectMultiWiFi in loop")); + connectMultiWiFi(); + } +} void check_status() { - static ulong checkstatus_timeout = 0; - static ulong checkwifi_timeout = 0; + static ulong checkstatus_timeout = 0; + static ulong checkwifi_timeout = 0; - static ulong current_millis; + static ulong current_millis; #define WIFICHECK_INTERVAL 1000L #define HEARTBEAT_INTERVAL 10000L - current_millis = millis(); - - // Check WiFi every WIFICHECK_INTERVAL (1) seconds. - if ((current_millis > checkwifi_timeout) || (checkwifi_timeout == 0)) - { - check_WiFi(); - checkwifi_timeout = current_millis + WIFICHECK_INTERVAL; - } - - // Print hearbeat every HEARTBEAT_INTERVAL (10) seconds. - if ((current_millis > checkstatus_timeout) || (checkstatus_timeout == 0)) - { - heartBeatPrint(); - checkstatus_timeout = current_millis + HEARTBEAT_INTERVAL; - } + current_millis = millis(); + + // Check WiFi every WIFICHECK_INTERVAL (1) seconds. + if ((current_millis > checkwifi_timeout) || (checkwifi_timeout == 0)) + { + check_WiFi(); + checkwifi_timeout = current_millis + WIFICHECK_INTERVAL; + } + + // Print hearbeat every HEARTBEAT_INTERVAL (10) seconds. + if ((current_millis > checkstatus_timeout) || (checkstatus_timeout == 0)) + { + heartBeatPrint(); + checkstatus_timeout = current_millis + HEARTBEAT_INTERVAL; + } } void loadConfigData() { - File file = FileFS.open(CONFIG_FILENAME, "r"); - LOGERROR(F("LoadWiFiCfgFile ")); - - memset(&WM_config, 0, sizeof(WM_config)); - - // New in v1.4.0 - //memset(&WM_STA_IPconfig, 0, sizeof(WM_STA_IPconfig)); - WM_STA_IPconfig = {}; - ////// - - if (file) - { - file.readBytes((char *) &WM_config, sizeof(WM_config)); - - // New in v1.4.0 - file.readBytes((char *) &WM_STA_IPconfig, sizeof(WM_STA_IPconfig)); - ////// - - file.close(); - LOGERROR(F("OK")); - - // New in v1.4.0 - displayIPConfigStruct(WM_STA_IPconfig); - ////// - } - else - { - LOGERROR(F("failed")); - } + File file = FileFS.open(CONFIG_FILENAME, "r"); + LOGERROR(F("LoadWiFiCfgFile ")); + + memset(&WM_config, 0, sizeof(WM_config)); + + // New in v1.4.0 + //memset(&WM_STA_IPconfig, 0, sizeof(WM_STA_IPconfig)); + WM_STA_IPconfig = {}; + ////// + + if (file) + { + file.readBytes((char *) &WM_config, sizeof(WM_config)); + + // New in v1.4.0 + file.readBytes((char *) &WM_STA_IPconfig, sizeof(WM_STA_IPconfig)); + ////// + + file.close(); + LOGERROR(F("OK")); + + // New in v1.4.0 + displayIPConfigStruct(WM_STA_IPconfig); + ////// + } + else + { + LOGERROR(F("failed")); + } } - + void saveConfigData() { - File file = FileFS.open(CONFIG_FILENAME, "w"); - LOGERROR(F("SaveWiFiCfgFile ")); - - if (file) - { - file.write((uint8_t*) &WM_config, sizeof(WM_config)); - - // New in v1.4.0 - file.write((uint8_t*) &WM_STA_IPconfig, sizeof(WM_STA_IPconfig)); - ////// - - file.close(); - LOGERROR(F("OK")); - } - else - { - LOGERROR(F("failed")); - } + File file = FileFS.open(CONFIG_FILENAME, "w"); + LOGERROR(F("SaveWiFiCfgFile ")); + + if (file) + { + file.write((uint8_t*) &WM_config, sizeof(WM_config)); + + // New in v1.4.0 + file.write((uint8_t*) &WM_STA_IPconfig, sizeof(WM_STA_IPconfig)); + ////// + + file.close(); + LOGERROR(F("OK")); + } + else + { + LOGERROR(F("failed")); + } } -void sendRequest() +void sendRequest() { - static bool requestOpenResult; - - if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) - { - //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/Europe/London.txt"); - //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); - requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); - - if (requestOpenResult) - { - // Only send() if open() returns true, or crash - request.send(); - } - else - { - Serial.println(F("Can't send bad request")); - } - } - else - { - Serial.println(F("Can't send request")); - } + static bool requestOpenResult; + + if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) + { + //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/Europe/London.txt"); + //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); + requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); + + if (requestOpenResult) + { + // Only send() if open() returns true, or crash + request.send(); + } + else + { + Serial.println(F("Can't send bad request")); + } + } + else + { + Serial.println(F("Can't send request")); + } } void requestCB(void *optParm, AsyncHTTPSRequest *request, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGWARN0(F("\n**************************************\n")); - AHTTPS_LOGWARN1(F("Response Code = "), request->responseHTTPString()); - - if (request->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(request->responseText()); - Serial.println(F("**************************************")); - } - - request->setDebug(false); - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGWARN0(F("\n**************************************\n")); + AHTTPS_LOGWARN1(F("Response Code = "), request->responseHTTPString()); + + if (request->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(request->responseText()); + Serial.println(F("**************************************")); + } + + request->setDebug(false); + } } void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - while (!Serial && millis() < 5000); + // put your setup code here, to run once: + Serial.begin(115200); + + while (!Serial && millis() < 5000); - delay(200); - - Serial.print(F("\nStarting AsyncHTTPSRequest_ESP_WiFiManager using ")); Serial.print(FS_Name); - Serial.print(F(" on ")); Serial.println(ARDUINO_BOARD); - Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + delay(200); + + Serial.print(F("\nStarting AsyncHTTPSRequest_ESP_WiFiManager using ")); + Serial.print(FS_Name); + Serial.print(F(" on ")); + Serial.println(ARDUINO_BOARD); + Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); #if defined(ESP_ASYNC_WIFIMANAGER_VERSION_INT) - if (ESP_ASYNC_WIFIMANAGER_VERSION_INT < ESP_ASYNC_WIFIMANAGER_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version later than : ")); - Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION_MIN_TARGET); - } + + if (ESP_ASYNC_WIFIMANAGER_VERSION_INT < ESP_ASYNC_WIFIMANAGER_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version later than : ")); + Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION_MIN_TARGET); + } + #endif #if defined(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif - if (FORMAT_FILESYSTEM) - FileFS.format(); + if (FORMAT_FILESYSTEM) + FileFS.format(); - // Format FileFS if not yet + // Format FileFS if not yet #ifdef ESP32 - if (!FileFS.begin(true)) + + if (!FileFS.begin(true)) #else - if (!FileFS.begin()) -#endif - { - Serial.print(FS_Name); - Serial.println(F(" failed! AutoFormatting.")); - + if (!FileFS.begin()) +#endif + { + Serial.print(FS_Name); + Serial.println(F(" failed! AutoFormatting.")); + #ifdef ESP8266 - FileFS.format(); + FileFS.format(); #endif - } - - unsigned long startedAt = millis(); - - // New in v1.4.0 - initAPIPConfigStruct(WM_AP_IPconfig); - initSTAIPConfigStruct(WM_STA_IPconfig); - ////// - - //Local intialization. Once its business is done, there is no need to keep it around - // Use this to default DHCP hostname to ESP8266-XXXXXX or ESP32-XXXXXX - //ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer); - // Use this to personalize DHCP hostname (RFC952 conformed) - AsyncWebServer webServer(HTTP_PORT); - - //ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP"); + } + + unsigned long startedAt = millis(); + + // New in v1.4.0 + initAPIPConfigStruct(WM_AP_IPconfig); + initSTAIPConfigStruct(WM_STA_IPconfig); + ////// + + //Local intialization. Once its business is done, there is no need to keep it around + // Use this to default DHCP hostname to ESP8266-XXXXXX or ESP32-XXXXXX + //ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer); + // Use this to personalize DHCP hostname (RFC952 conformed) + AsyncWebServer webServer(HTTP_PORT); + + //ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP"); #if ( USING_ESP32_S2 || USING_ESP32_C3 ) - ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, NULL, "AutoConnectAP"); + ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, NULL, "AutoConnectAP"); #else - AsyncDNSServer dnsServer; + AsyncDNSServer dnsServer; - ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP"); -#endif + ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP"); +#endif - //ESPAsync_wifiManager.setDebugOutput(true); + //ESPAsync_wifiManager.setDebugOutput(true); - //reset settings - for testing - //ESPAsync_wifiManager.resetSettings(); + //reset settings - for testing + //ESPAsync_wifiManager.resetSettings(); #if USE_CUSTOM_AP_IP - //set custom ip for portal - // New in v1.4.0 - ESPAsync_wifiManager.setAPStaticIPConfig(WM_AP_IPconfig); - ////// + //set custom ip for portal + // New in v1.4.0 + ESPAsync_wifiManager.setAPStaticIPConfig(WM_AP_IPconfig); + ////// #endif - ESPAsync_wifiManager.setMinimumSignalQuality(-1); - - // From v1.0.10 only - // Set config portal channel, default = 1. Use 0 => random channel from 1-13 - ESPAsync_wifiManager.setConfigPortalChannel(0); - ////// - -#if !USE_DHCP_IP - // Set (static IP, Gateway, Subnetmask, DNS1 and DNS2) or (IP, Gateway, Subnetmask). New in v1.0.5 - // New in v1.4.0 - ESPAsync_wifiManager.setSTAStaticIPConfig(WM_STA_IPconfig); - ////// + ESPAsync_wifiManager.setMinimumSignalQuality(-1); + + // From v1.0.10 only + // Set config portal channel, default = 1. Use 0 => random channel from 1-13 + ESPAsync_wifiManager.setConfigPortalChannel(0); + ////// + +#if !USE_DHCP_IP + // Set (static IP, Gateway, Subnetmask, DNS1 and DNS2) or (IP, Gateway, Subnetmask). New in v1.0.5 + // New in v1.4.0 + ESPAsync_wifiManager.setSTAStaticIPConfig(WM_STA_IPconfig); + ////// #endif - // New from v1.1.1 + // New from v1.1.1 #if USING_CORS_FEATURE - ESPAsync_wifiManager.setCORSHeader("Your Access-Control-Allow-Origin"); + ESPAsync_wifiManager.setCORSHeader("Your Access-Control-Allow-Origin"); #endif - // We can't use WiFi.SSID() in ESP32 as it's only valid after connected. - // SSID and Password stored in ESP32 wifi_ap_record_t and wifi_config_t are also cleared in reboot - // Have to create a new function to store in EEPROM/SPIFFS for this purpose - Router_SSID = ESPAsync_wifiManager.WiFi_SSID(); - Router_Pass = ESPAsync_wifiManager.WiFi_Pass(); + // We can't use WiFi.SSID() in ESP32 as it's only valid after connected. + // SSID and Password stored in ESP32 wifi_ap_record_t and wifi_config_t are also cleared in reboot + // Have to create a new function to store in EEPROM/SPIFFS for this purpose + Router_SSID = ESPAsync_wifiManager.WiFi_SSID(); + Router_Pass = ESPAsync_wifiManager.WiFi_Pass(); - //Remove this line if you do not want to see WiFi password printed - Serial.print(F("Stored: SSID = ")); Serial.print(Router_SSID); - Serial.print(F(", Pass = ")); Serial.println(Router_Pass); + //Remove this line if you do not want to see WiFi password printed + Serial.print(F("Stored: SSID = ")); + Serial.print(Router_SSID); + Serial.print(F(", Pass = ")); + Serial.println(Router_Pass); - if (Router_SSID != "") - { - ESPAsync_wifiManager.setConfigPortalTimeout(120); //If no access point name has been previously entered disable timeout. - Serial.println(F("Got stored Credentials. Timeout 120s")); - } - else - { - Serial.println(F("No stored Credentials. No timeout")); - } + if (Router_SSID != "") + { + ESPAsync_wifiManager.setConfigPortalTimeout(120); //If no access point name has been previously entered disable timeout. + Serial.println(F("Got stored Credentials. Timeout 120s")); + } + else + { + Serial.println(F("No stored Credentials. No timeout")); + } - String chipID = String(ESP_getChipId(), HEX); - chipID.toUpperCase(); + String chipID = String(ESP_getChipId(), HEX); + chipID.toUpperCase(); - // SSID and PW for Config Portal - String AP_SSID = "ESP_" + chipID; - String AP_PASS = "MyESP_" + chipID; + // SSID and PW for Config Portal + String AP_SSID = "ESP_" + chipID; + String AP_PASS = "MyESP_" + chipID; - // From v1.1.0, Don't permit NULL password - if ( (Router_SSID == "") || (Router_Pass == "") ) - { - Serial.println(F("We haven't got any access point credentials, so get them now")); + // From v1.1.0, Don't permit NULL password + if ( (Router_SSID == "") || (Router_Pass == "") ) + { + Serial.println(F("We haven't got any access point credentials, so get them now")); - initialConfig = true; + initialConfig = true; - Serial.print(F("Starting configuration portal @ ")); - -#if USE_CUSTOM_AP_IP - Serial.print(APStaticIP); + Serial.print(F("Starting configuration portal @ ")); + +#if USE_CUSTOM_AP_IP + Serial.print(APStaticIP); #else - Serial.print(F("192.168.4.1")); + Serial.print(F("192.168.4.1")); #endif - Serial.print(F(", SSID = ")); - Serial.print(AP_SSID); - Serial.print(F(", PASS = ")); - Serial.println(AP_PASS); - - // Starts an access point - //if (!ESPAsync_wifiManager.startConfigPortal((const char *) ssid.c_str(), password)) - if ( !ESPAsync_wifiManager.startConfigPortal((const char *) AP_SSID.c_str(), AP_PASS.c_str()) ) - Serial.println(F("Not connected to WiFi but continuing anyway.")); - else - Serial.println(F("WiFi connected...yeey :)")); - - // Stored for later usage, from v1.1.0, but clear first - memset(&WM_config, 0, sizeof(WM_config)); - - for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) - { - String tempSSID = ESPAsync_wifiManager.getSSID(i); - String tempPW = ESPAsync_wifiManager.getPW(i); - - if (strlen(tempSSID.c_str()) < sizeof(WM_config.WiFi_Creds[i].wifi_ssid) - 1) - strcpy(WM_config.WiFi_Creds[i].wifi_ssid, tempSSID.c_str()); - else - strncpy(WM_config.WiFi_Creds[i].wifi_ssid, tempSSID.c_str(), sizeof(WM_config.WiFi_Creds[i].wifi_ssid) - 1); - - if (strlen(tempPW.c_str()) < sizeof(WM_config.WiFi_Creds[i].wifi_pw) - 1) - strcpy(WM_config.WiFi_Creds[i].wifi_pw, tempPW.c_str()); - else - strncpy(WM_config.WiFi_Creds[i].wifi_pw, tempPW.c_str(), sizeof(WM_config.WiFi_Creds[i].wifi_pw) - 1); - - // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) - if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != "") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) - { - LOGERROR3(F("* Add SSID = "), WM_config.WiFi_Creds[i].wifi_ssid, F(", PW = "), WM_config.WiFi_Creds[i].wifi_pw ); - wifiMulti.addAP(WM_config.WiFi_Creds[i].wifi_ssid, WM_config.WiFi_Creds[i].wifi_pw); - } - } - - // New in v1.4.0 - ESPAsync_wifiManager.getSTAStaticIPConfig(WM_STA_IPconfig); - displayIPConfigStruct(WM_STA_IPconfig); - ////// - - saveConfigData(); - } - else - { - wifiMulti.addAP(Router_SSID.c_str(), Router_Pass.c_str()); - } - - startedAt = millis(); - - if (!initialConfig) - { - // Load stored data, the addAP ready for MultiWiFi reconnection - loadConfigData(); - - for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) - { - // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) - if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != "") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) - { - LOGERROR3(F("* Add SSID = "), WM_config.WiFi_Creds[i].wifi_ssid, F(", PW = "), WM_config.WiFi_Creds[i].wifi_pw ); - wifiMulti.addAP(WM_config.WiFi_Creds[i].wifi_ssid, WM_config.WiFi_Creds[i].wifi_pw); - } - } - - if ( WiFi.status() != WL_CONNECTED ) - { - Serial.println(F("ConnectMultiWiFi in setup")); - - connectMultiWiFi(); - } - } - - Serial.print(F("After waiting ")); - Serial.print((float) (millis() - startedAt) / 1000L); - Serial.print(F(" secs more in setup(), connection result is ")); - - if (WiFi.status() == WL_CONNECTED) - { - Serial.print(F("connected. Local IP: ")); - Serial.println(WiFi.localIP()); - } - else - Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status())); - - request.setDebug(false); - - request.onReadyStateChange(requestCB); - ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequest); - - // Send first request now - sendRequest(); + Serial.print(F(", SSID = ")); + Serial.print(AP_SSID); + Serial.print(F(", PASS = ")); + Serial.println(AP_PASS); + + // Starts an access point + //if (!ESPAsync_wifiManager.startConfigPortal((const char *) ssid.c_str(), password)) + if ( !ESPAsync_wifiManager.startConfigPortal((const char *) AP_SSID.c_str(), AP_PASS.c_str()) ) + Serial.println(F("Not connected to WiFi but continuing anyway.")); + else + Serial.println(F("WiFi connected...yeey :)")); + + // Stored for later usage, from v1.1.0, but clear first + memset(&WM_config, 0, sizeof(WM_config)); + + for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) + { + String tempSSID = ESPAsync_wifiManager.getSSID(i); + String tempPW = ESPAsync_wifiManager.getPW(i); + + if (strlen(tempSSID.c_str()) < sizeof(WM_config.WiFi_Creds[i].wifi_ssid) - 1) + strcpy(WM_config.WiFi_Creds[i].wifi_ssid, tempSSID.c_str()); + else + strncpy(WM_config.WiFi_Creds[i].wifi_ssid, tempSSID.c_str(), sizeof(WM_config.WiFi_Creds[i].wifi_ssid) - 1); + + if (strlen(tempPW.c_str()) < sizeof(WM_config.WiFi_Creds[i].wifi_pw) - 1) + strcpy(WM_config.WiFi_Creds[i].wifi_pw, tempPW.c_str()); + else + strncpy(WM_config.WiFi_Creds[i].wifi_pw, tempPW.c_str(), sizeof(WM_config.WiFi_Creds[i].wifi_pw) - 1); + + // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) + if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != "") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) + { + LOGERROR3(F("* Add SSID = "), WM_config.WiFi_Creds[i].wifi_ssid, F(", PW = "), WM_config.WiFi_Creds[i].wifi_pw ); + wifiMulti.addAP(WM_config.WiFi_Creds[i].wifi_ssid, WM_config.WiFi_Creds[i].wifi_pw); + } + } + + // New in v1.4.0 + ESPAsync_wifiManager.getSTAStaticIPConfig(WM_STA_IPconfig); + displayIPConfigStruct(WM_STA_IPconfig); + ////// + + saveConfigData(); + } + else + { + wifiMulti.addAP(Router_SSID.c_str(), Router_Pass.c_str()); + } + + startedAt = millis(); + + if (!initialConfig) + { + // Load stored data, the addAP ready for MultiWiFi reconnection + loadConfigData(); + + for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) + { + // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) + if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != "") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) + { + LOGERROR3(F("* Add SSID = "), WM_config.WiFi_Creds[i].wifi_ssid, F(", PW = "), WM_config.WiFi_Creds[i].wifi_pw ); + wifiMulti.addAP(WM_config.WiFi_Creds[i].wifi_ssid, WM_config.WiFi_Creds[i].wifi_pw); + } + } + + if ( WiFi.status() != WL_CONNECTED ) + { + Serial.println(F("ConnectMultiWiFi in setup")); + + connectMultiWiFi(); + } + } + + Serial.print(F("After waiting ")); + Serial.print((float) (millis() - startedAt) / 1000L); + Serial.print(F(" secs more in setup(), connection result is ")); + + if (WiFi.status() == WL_CONNECTED) + { + Serial.print(F("connected. Local IP: ")); + Serial.println(WiFi.localIP()); + } + else + Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status())); + + request.setDebug(false); + + request.onReadyStateChange(requestCB); + ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequest); + + // Send first request now + sendRequest(); } void loop() -{ - // put your main code here, to run repeatedly - check_status(); +{ + // put your main code here, to run repeatedly + check_status(); } diff --git a/examples/AsyncHTTP_HTTPSRequest_ESP/AsyncHTTP_HTTPSRequest_ESP.ino b/examples/AsyncHTTP_HTTPSRequest_ESP/AsyncHTTP_HTTPSRequest_ESP.ino index 2898ebb..4ce8fb4 100644 --- a/examples/AsyncHTTP_HTTPSRequest_ESP/AsyncHTTP_HTTPSRequest_ESP.ino +++ b/examples/AsyncHTTP_HTTPSRequest_ESP/AsyncHTTP_HTTPSRequest_ESP.ino @@ -41,14 +41,19 @@ //************************************************************************************************************* #if !( defined(ESP8266) || defined(ESP32) ) -#error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. + #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. #endif -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.0" -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002000 +#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPRequest_Generic v1.10.2" +#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN 1010002 -#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPRequest_Generic v1.9.2" -#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN 1009002 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.1" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002001 + +///////////////////////////////////////////////////////// + +// Uncomment for certain HTTP site to optimize +//#define NOT_SEND_HEADER_AFTER_CONNECTED true // Level from 0-4 #define ASYNC_HTTPS_DEBUG_PORT Serial @@ -68,9 +73,9 @@ const char* ssid = "your_ssid"; const char* password = "your_pass"; #if (ESP8266) - #include + #include #elif (ESP32) - #include + #include #endif // Use larger queue size if necessary for large data transfer. Default is 512 bytes if not defined here @@ -91,9 +96,9 @@ const char* password = "your_pass"; const char* addreses[][NUM_DIFFERENT_SITES] = { - {"https://worldtimeapi.org/api/timezone/America/Toronto.txt", "https://worldtimeapi.org/api/timezone/Europe/Prague.txt"}, - {"http://worldtimeapi.org/api/timezone/Europe/London.txt", "http://worldtimeapi.org/api/timezone/America/Vancouver.txt"}, - {"http://www.myexternalip.com/raw"} + {"https://worldtimeapi.org/api/timezone/America/Toronto.txt", "https://worldtimeapi.org/api/timezone/Europe/Prague.txt"}, + {"http://worldtimeapi.org/api/timezone/Europe/London.txt", "http://worldtimeapi.org/api/timezone/America/Vancouver.txt"}, + {"http://www.myexternalip.com/raw"} }; #define NUM_ENTRIES_SITE_0 2 @@ -105,8 +110,8 @@ bool readySend[] = { true, true, true }; typedef enum { - HTTP_REQUEST = 0, - HTTPS_REQUEST = 1, + HTTP_REQUEST = 0, + HTTPS_REQUEST = 1, } HTTP_Type; AsyncHTTPSRequest request0; @@ -115,15 +120,15 @@ AsyncHTTPRequest request2; typedef struct _AsyncHTTPRequestData { - void* request; // (void*) for AsyncHTTPRequest* or AsyncHTTPSRequest* - HTTP_Type httpType; + void* request; // (void*) for AsyncHTTPRequest* or AsyncHTTPSRequest* + HTTP_Type httpType; } AsyncHTTPRequestData; AsyncHTTPRequestData myAsyncHTTPRequestData[] = { - { (void*) &request0, HTTPS_REQUEST }, - { (void*) &request1, HTTP_REQUEST }, - { (void*) &request2, HTTP_REQUEST } + { (void*) &request0, HTTPS_REQUEST }, + { (void*) &request1, HTTP_REQUEST }, + { (void*) &request2, HTTP_REQUEST } }; // This is for HTTPS and must use AsyncHTTPSRequest @@ -152,238 +157,244 @@ Ticker ticker1; void heartBeatPrint() { - static int num = 1; - - if (WiFi.status() == WL_CONNECTED) - Serial.print(F("H")); // H means connected to WiFi - else - Serial.print(F("F")); // F means not connected to WiFi - - if (num == 80) - { - Serial.println(); - num = 1; - } - else if (num++ % 10 == 0) - { - Serial.print(F(" ")); - } + static int num = 1; + + if (WiFi.status() == WL_CONNECTED) + Serial.print(F("H")); // H means connected to WiFi + else + Serial.print(F("F")); // F means not connected to WiFi + + if (num == 80) + { + Serial.println(); + num = 1; + } + else if (num++ % 10 == 0) + { + Serial.print(F(" ")); + } } void sendRequest(uint16_t index) { - static bool requestOpenResult; - - reqCount[index]--; - readySend[index] = false; - - if ( myAsyncHTTPRequestData[index].httpType == HTTPS_REQUEST ) - { - requestOpenResult = ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->open("GET", addreses[index][reqCount[index]]); - - if (requestOpenResult) - { - // Only send() if open() returns true, or crash - Serial.print("\nSending HTTPS request: "); - ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->send(); - } - else - { - Serial.print("\nCan't send bad HTTPS request : "); - } - } - else if ( myAsyncHTTPRequestData[index].httpType == HTTP_REQUEST ) - { - requestOpenResult = ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->open("GET", addreses[index][reqCount[index]]); - - if (requestOpenResult) - { - // Only send() if open() returns true, or crash - Serial.print("\nSending HTTP request: "); - ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->send(); - } - else - { - Serial.print("\nCan't send bad HTTP request : "); - } - } - - Serial.println(addreses[index][reqCount[index]]); + static bool requestOpenResult; + + reqCount[index]--; + readySend[index] = false; + + if ( myAsyncHTTPRequestData[index].httpType == HTTPS_REQUEST ) + { + requestOpenResult = ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->open("GET", addreses[index][reqCount[index]]); + + if (requestOpenResult) + { + // Only send() if open() returns true, or crash + Serial.print("\nSending HTTPS request: "); + ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->send(); + } + else + { + Serial.print("\nCan't send bad HTTPS request : "); + } + } + else if ( myAsyncHTTPRequestData[index].httpType == HTTP_REQUEST ) + { + requestOpenResult = ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->open("GET", addreses[index][reqCount[index]]); + + if (requestOpenResult) + { + // Only send() if open() returns true, or crash + Serial.print("\nSending HTTP request: "); + ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->send(); + } + else + { + Serial.print("\nCan't send bad HTTP request : "); + } + } + + Serial.println(addreses[index][reqCount[index]]); } void sendRequest0() { - sendRequest(0); + sendRequest(0); } void sendRequest1() { - sendRequest(1); + sendRequest(1); } void sendRequest2() { - sendRequest(2); + sendRequest(2); } void sendRequests() { - for (int index = 0; index < NUM_DIFFERENT_SITES; index++) - { - reqCount[index] = 2; - } - - reqCount[0] = NUM_ENTRIES_SITE_0; - reqCount[1] = NUM_ENTRIES_SITE_1; - reqCount[2] = NUM_ENTRIES_SITE_2; + for (int index = 0; index < NUM_DIFFERENT_SITES; index++) + { + reqCount[index] = 2; + } + + reqCount[0] = NUM_ENTRIES_SITE_0; + reqCount[1] = NUM_ENTRIES_SITE_1; + reqCount[2] = NUM_ENTRIES_SITE_2; } // This is for HTTPS and must use AsyncHTTPSRequest void requestCB0(void *optParm, AsyncHTTPSRequest *thisRequest, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); - - if (thisRequest->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(thisRequest->responseText()); - Serial.println(F("**************************************")); - } - - thisRequest->setDebug(false); - readySend[0] = true; - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); + + if (thisRequest->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(thisRequest->responseText()); + Serial.println(F("**************************************")); + } + + thisRequest->setDebug(false); + readySend[0] = true; + } } // This is for HTTP and must use AsyncHTTPRequest void requestCB1(void *optParm, AsyncHTTPRequest *thisRequest, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); - - if (thisRequest->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(thisRequest->responseText()); - Serial.println(F("**************************************")); - } - - thisRequest->setDebug(false); - readySend[1] = true; - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); + + if (thisRequest->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(thisRequest->responseText()); + Serial.println(F("**************************************")); + } + + thisRequest->setDebug(false); + readySend[1] = true; + } } // This is for HTTP and must use AsyncHTTPRequest void requestCB2(void *optParm, AsyncHTTPRequest *thisRequest, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); - - if (thisRequest->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(thisRequest->responseText()); - Serial.println(F("**************************************")); - } - - thisRequest->setDebug(false); - readySend[2] = true; - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), thisRequest->responseHTTPString()); + + if (thisRequest->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(thisRequest->responseText()); + Serial.println(F("**************************************")); + } + + thisRequest->setDebug(false); + readySend[2] = true; + } } void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - while (!Serial && millis() < 5000); + // put your setup code here, to run once: + Serial.begin(115200); - delay(200); + while (!Serial && millis() < 5000); - Serial.print("\nStarting AsyncHTTP_HTTPSRequest_ESP on "); Serial.println(ARDUINO_BOARD); + delay(200); + + Serial.print("\nStarting AsyncHTTP_HTTPSRequest_ESP on "); + Serial.println(ARDUINO_BOARD); #if defined(ESP32) - Serial.println(ASYNC_TCP_SSL_VERSION); + Serial.println(ASYNC_TCP_SSL_VERSION); #else - //Serial.println(ESPASYNC_TCP_SSL_VERSION); + //Serial.println(ESPASYNC_TCP_SSL_VERSION); #endif - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); - Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION); #if defined(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif #if defined(ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTP_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTP_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif - WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_STA); - WiFi.begin(ssid, password); + WiFi.begin(ssid, password); - Serial.println("Connecting to WiFi SSID: " + String(ssid)); + Serial.println("Connecting to WiFi SSID: " + String(ssid)); - while (WiFi.status() != WL_CONNECTED) - { - delay(500); - Serial.print("."); - } + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print("."); + } - Serial.print(F("\nAsyncHTTPSRequest @ IP : ")); - Serial.println(WiFi.localIP()); + Serial.print(F("\nAsyncHTTPSRequest @ IP : ")); + Serial.println(WiFi.localIP()); - for (int index = 0; index < NUM_DIFFERENT_SITES; index++) - { - if ( myAsyncHTTPRequestData[index].httpType == HTTPS_REQUEST ) - { - ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->setDebug(false); - ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->onReadyStateChange( (requestCallback0) requestCB[index]); - } - else if ( myAsyncHTTPRequestData[index].httpType == HTTP_REQUEST ) - { - ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->setDebug(false); - ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->onReadyStateChange((requestCallback1) requestCB[index]); - } - } + for (int index = 0; index < NUM_DIFFERENT_SITES; index++) + { + if ( myAsyncHTTPRequestData[index].httpType == HTTPS_REQUEST ) + { + ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->setDebug(false); + ((AsyncHTTPSRequest *) myAsyncHTTPRequestData[index].request)->onReadyStateChange( (requestCallback0) requestCB[index]); + } + else if ( myAsyncHTTPRequestData[index].httpType == HTTP_REQUEST ) + { + ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->setDebug(false); + ((AsyncHTTPRequest *) myAsyncHTTPRequestData[index].request)->onReadyStateChange((requestCallback1) requestCB[index]); + } + } - ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequests); + ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequests); - ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); + ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); } void loop() { - for (int index = 0; index < NUM_DIFFERENT_SITES; index++) - { - if ((reqCount[index] > 0) && readySend[index]) - { - sendRequestCB[index](); - - // Don't reduce this or possible crash. TLS needs long time to work. - delay(100); - } - } + for (int index = 0; index < NUM_DIFFERENT_SITES; index++) + { + if ((reqCount[index] > 0) && readySend[index]) + { + sendRequestCB[index](); + + // Don't reduce this or possible crash. TLS needs long time to work. + delay(100); + } + } } diff --git a/examples/WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01.ino b/examples/WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01.ino index 15ddd60..d21952c 100644 --- a/examples/WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01.ino +++ b/examples/WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01/AsyncHTTPSRequest_WT32_ETH01.ino @@ -1,21 +1,21 @@ /**************************************************************************************************************************** AsyncHTTPSRequest_WT32_ETH01.ino - Dead simple AsyncHTTPSRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet - + For ESP8266, ESP32 and STM32 with built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc) - + AsyncHTTPSRequest_Generic is a library for the ESP8266, ESP32 and currently STM32 run built-in Ethernet WebServer - + Based on and modified from AsyncHTTPRequest Library (https://github.com/boblemaire/AsyncHTTPRequest) - + Built by Khoi Hoang https://github.com/khoih-prog/AsyncHTTPSRequest_Generic Licensed under MIT license - + Copyright (C) <2018> - This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published bythe 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 . + You should have received a copy of the GNU General Public License along with this program. If not, see . *****************************************************************************************************************************/ //************************************************************************************************************ // @@ -41,14 +41,17 @@ //************************************************************************************************************* #if !( defined(ESP32) ) - #error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting. + #error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting. #endif -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.0" -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002000 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.1" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002001 ///////////////////////////////////////////////////////// +// Uncomment for certain HTTP site to optimize +//#define NOT_SEND_HEADER_AFTER_CONNECTED true + // Use larger queue size if necessary for large data transfer. Default is 512 bytes if not defined here //#define ASYNC_QUEUE_LENGTH 512 @@ -98,121 +101,126 @@ IPAddress myDNS(8, 8, 8, 8); void heartBeatPrint() { - static int num = 1; - - if (WT32_ETH01_isConnected()) - Serial.print(F("H")); // H means connected - else - Serial.print(F("F")); // F means not connected - - if (num == 80) - { - Serial.println(); - num = 1; - } - else if (num++ % 10 == 0) - { - Serial.print(F(" ")); - } + static int num = 1; + + if (WT32_ETH01_isConnected()) + Serial.print(F("H")); // H means connected + else + Serial.print(F("F")); // F means not connected + + if (num == 80) + { + Serial.println(); + num = 1; + } + else if (num++ % 10 == 0) + { + Serial.print(F(" ")); + } } -void sendRequest() +void sendRequest() { - static bool requestOpenResult; - - if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) - { - //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/Europe/London.txt"); - requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); - - if (requestOpenResult) - { - // Only send() if open() returns true, or crash - request.send(); - } - else - { - Serial.println(F("Can't send bad request")); - } - } - else - { - Serial.println(F("Can't send request")); - } + static bool requestOpenResult; + + if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) + { + //requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/Europe/London.txt"); + requestOpenResult = request.open("GET", "https://worldtimeapi.org/api/timezone/America/Toronto.txt"); + + if (requestOpenResult) + { + // Only send() if open() returns true, or crash + request.send(); + } + else + { + Serial.println(F("Can't send bad request")); + } + } + else + { + Serial.println(F("Can't send request")); + } } void requestCB(void *optParm, AsyncHTTPSRequest *request, int readyState) { - (void) optParm; - - if (readyState == readyStateDone) - { - AHTTPS_LOGDEBUG0(F("\n**************************************\n")); - AHTTPS_LOGDEBUG1(F("Response Code = "), request->responseHTTPString()); - - if (request->responseHTTPcode() == 200) - { - Serial.println(F("\n**************************************")); - Serial.println(request->responseText()); - Serial.println(F("**************************************")); - } - - request->setDebug(false); - } + (void) optParm; + + if (readyState == readyStateDone) + { + AHTTPS_LOGDEBUG0(F("\n**************************************\n")); + AHTTPS_LOGDEBUG1(F("Response Code = "), request->responseHTTPString()); + + if (request->responseHTTPcode() == 200) + { + Serial.println(F("\n**************************************")); + Serial.println(request->responseText()); + Serial.println(F("**************************************")); + } + + request->setDebug(false); + } } void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - while (!Serial && millis() < 5000); + // put your setup code here, to run once: + Serial.begin(115200); + + while (!Serial && millis() < 5000); - delay(200); + delay(200); - Serial.print(F("\nStarting AsyncHTTPSRequest_WT32_ETH01 using ")); Serial.print(ARDUINO_BOARD); - Serial.print(F(" with ")); Serial.println(SHIELD_TYPE); - Serial.println(WEBSERVER_WT32_ETH01_VERSION); - Serial.println(ASYNC_TCP_SSL_VERSION); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + Serial.print(F("\nStarting AsyncHTTPSRequest_WT32_ETH01 using ")); + Serial.print(ARDUINO_BOARD); + Serial.print(F(" with ")); + Serial.println(SHIELD_TYPE); + Serial.println(WEBSERVER_WT32_ETH01_VERSION); + Serial.println(ASYNC_TCP_SSL_VERSION); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + + Serial.setDebugOutput(true); - Serial.setDebugOutput(true); - #if defined(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif - // To be called before ETH.begin() - WT32_ETH01_onEvent(); + // To be called before ETH.begin() + WT32_ETH01_onEvent(); + + //bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO, + // eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE); + //ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE); + ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER); - //bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO, - // eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE); - //ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE); - ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER); + // Static IP, leave without this line to get IP via DHCP + //bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0); + ETH.config(myIP, myGW, mySN, myDNS); - // Static IP, leave without this line to get IP via DHCP - //bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0); - ETH.config(myIP, myGW, mySN, myDNS); + WT32_ETH01_waitForConnect(); - WT32_ETH01_waitForConnect(); + Serial.print(F("\nHTTP WebClient is @ IP : ")); + Serial.println(ETH.localIP()); - Serial.print(F("\nHTTP WebClient is @ IP : ")); - Serial.println(ETH.localIP()); - - request.setDebug(false); - - request.onReadyStateChange(requestCB); - ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequest); + request.setDebug(false); - ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); - - // Send first request now - sendRequest(); + request.onReadyStateChange(requestCB); + ticker.attach(HTTPS_REQUEST_INTERVAL, sendRequest); + + ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint); + + // Send first request now + sendRequest(); } void loop() -{ +{ } diff --git a/examples/multiFileProject/multiFileProject.ino b/examples/multiFileProject/multiFileProject.ino index 4179473..d2f8542 100644 --- a/examples/multiFileProject/multiFileProject.ino +++ b/examples/multiFileProject/multiFileProject.ino @@ -13,11 +13,16 @@ // To demo how to include files in multi-file Projects #if !( defined(ESP32) ) - #error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting. + #error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting. #endif -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.1.3" -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2001003 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET "AsyncHTTPSRequest_Generic v2.2.1" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN 2002001 + +///////////////////////////////////////////////////////// + +// Uncomment for certain HTTP site to optimize +//#define NOT_SEND_HEADER_AFTER_CONNECTED true #include "multiFileProject.h" @@ -26,26 +31,29 @@ // To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error #include "AsyncHTTPSRequest_Generic.h" -void setup() +void setup() { - Serial.begin(115200); - while (!Serial && millis() < 5000); + Serial.begin(115200); + + while (!Serial && millis() < 5000); - delay(200); - - Serial.println(F("\nStart multiFileProject")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); + delay(200); + + Serial.println(F("\nStart multiFileProject")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION); #if defined(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) - { - Serial.print(F("Warning. Must use this example on Version equal or later than : ")); - Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); - } + + if (ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN) + { + Serial.print(F("Warning. Must use this example on Version equal or later than : ")); + Serial.println(ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MIN_TARGET); + } + #endif } -void loop() +void loop() { - // put your main code here, to run repeatedly: + // put your main code here, to run repeatedly: } diff --git a/library.json b/library.json index a17a54b..6d03495 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name":"AsyncHTTPSRequest_Generic", - "version": "2.2.0", + "version": "2.2.1", "description":"Simple Async HTTPS Request library, supporting GET, POST, PUT, PATCH, DELETE and HEAD, on top of AsyncTCP_SSL library for ESP32 (including ESP32_S2, ESP32_S3 and ESP32_C3), WT32_ETH01 (ESP32 + LAN8720). Supporting in the future for RP2040W, ESP8266, Portenta_H7, STM32 with built-in LAN8742A Ethernet, etc. Now you can send HTTP / HTTPS requests to multiple addresses and receive responses from them.", "keywords":"communication, async, tcp, https, ssl, tls, ESP8266, ESP32, ESP32-S2, wt32-eth01, ESPAsyncTCP, AsyncTCP, stm32, ethernet, wifi, lan8742a, lan8720, f407ve, nucleo-144, stm32f7", "authors": [ @@ -45,13 +45,13 @@ { "owner": "khoih-prog", "name": "AsyncHTTPRequest_Generic", - "version": ">=1.9.2", + "version": ">=1.10.2", "platforms": ["espressif8266", "espressif32"] }, { "owner": "khoih-prog", "name": "ESPAsync_WiFiManager", - "version": ">=1.15.0", + "version": ">=1.15.1", "platforms": ["espressif8266", "espressif32"] } ], diff --git a/library.properties b/library.properties index 06a0ad3..984b334 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=AsyncHTTPSRequest_Generic -version=2.2.0 +version=2.2.1 author=Bob Lemaire,Khoi Hoang maintainer=Khoi Hoang license=GPLv3 diff --git a/platformio/platformio.ini b/platformio/platformio.ini index f0a110c..2e414d5 100644 --- a/platformio/platformio.ini +++ b/platformio/platformio.ini @@ -48,14 +48,14 @@ lib_ldf_mode = chain+ lib_deps = ; PlatformIO 4.x ; AsyncTCP_SSL@>=1.3.1 -; AsyncHTTPRequest_Generic@>=1.9.2 +; AsyncHTTPRequest_Generic@>=1.10.2 ; WebServer_WT32_ETH01@>=1.5.1 -; ESPAsync_WiFiManager@>=1.15.0 +; ESPAsync_WiFiManager@>=1.15.1 ; PlatformIO 5.x khoih-prog/AsyncTCP_SSL@>=1.3.1 - khoih-prog/AsyncHTTPRequest_Generic@>=1.9.2 + khoih-prog/AsyncHTTPRequest_Generic@>=1.10.2 khoih-prog/WebServer_WT32_ETH01@>=1.5.1 - khoih-prog/ESPAsync_WiFiManager@>=1.15.0 + khoih-prog/ESPAsync_WiFiManager@>=1.15.1 build_flags = diff --git a/src/AsyncHTTPSRequest_Debug_Generic.h b/src/AsyncHTTPSRequest_Debug_Generic.h index 5a0c9e6..a044066 100644 --- a/src/AsyncHTTPSRequest_Debug_Generic.h +++ b/src/AsyncHTTPSRequest_Debug_Generic.h @@ -1,24 +1,24 @@ /**************************************************************************************************************************** AsyncHTTPSRequest_Debug_Generic.h - + For ESP32, future ESP8266 - + AsyncHTTPSRequest is a library for the ESP32, ESP8266 (not-yet ready) - + Based on and modified from AsyncHTTPRequest Library (https://github.com/boblemaire/asyncHTTPrequest) - + Built by Khoi Hoang https://github.com/khoih-prog/AsyncHTTPSRequest_Generic - + Copyright (C) <2018> - This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published bythe 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 . - - Version: 2.1.3 - + You should have received a copy of the GNU General Public License along with this program. + If not, see . + + Version: 2.2.1 + Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 21/10/2021 Initial coding to support only ESP32 @@ -34,6 +34,8 @@ 2.1.1 K Hoang 09/09/2022 Fix ESP32 chipID for example `AsyncHTTPSRequest_ESP_WiFiManager` 2.1.2 K Hoang 18/09/2022 Fix bug and compiler error in some cases 2.1.3 K Hoang 18/10/2022 Not try to reconnect to the same host:port after connected + 2.2.0 K Hoang 20/10/2022 Fix crash and memory leak + 2.2.1 K Hoang 09/11/2022 Default to reconnect to the same host:port after connected for new HTTP sites *****************************************************************************************************************************/ #pragma once diff --git a/src/AsyncHTTPSRequest_Generic.h b/src/AsyncHTTPSRequest_Generic.h index 5c87405..ce214ac 100644 --- a/src/AsyncHTTPSRequest_Generic.h +++ b/src/AsyncHTTPSRequest_Generic.h @@ -1,24 +1,24 @@ /**************************************************************************************************************************** AsyncHTTPSRequest_Generic.h - + For ESP32, future ESP8266 - + AsyncHTTPSRequest is a library for the ESP32, ESP8266 (not-yet ready) - + Based on and modified from AsyncHTTPRequest Library (https://github.com/boblemaire/asyncHTTPrequest) - + Built by Khoi Hoang https://github.com/khoih-prog/AsyncHTTPSRequest_Generic - + Copyright (C) <2018> - This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published bythe 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 . - - Version: 2.2.0 - + You should have received a copy of the GNU General Public License along with this program. + If not, see . + + Version: 2.2.1 + Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 21/10/2021 Initial coding to support only ESP32 @@ -35,6 +35,7 @@ 2.1.2 K Hoang 18/09/2022 Fix bug and compiler error in some cases 2.1.3 K Hoang 18/10/2022 Not try to reconnect to the same host:port after connected 2.2.0 K Hoang 20/10/2022 Fix crash and memory leak + 2.2.1 K Hoang 09/11/2022 Default to reconnect to the same host:port after connected for new HTTP sites *****************************************************************************************************************************/ #pragma once diff --git a/src/AsyncHTTPSRequest_Generic.hpp b/src/AsyncHTTPSRequest_Generic.hpp index 2c54f05..56527b0 100644 --- a/src/AsyncHTTPSRequest_Generic.hpp +++ b/src/AsyncHTTPSRequest_Generic.hpp @@ -17,8 +17,8 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . - Version: 2.2.0 - + Version: 2.2.1 + Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 21/10/2021 Initial coding to support only ESP32 @@ -35,6 +35,7 @@ 2.1.2 K Hoang 18/09/2022 Fix bug and compiler error in some cases 2.1.3 K Hoang 18/10/2022 Not try to reconnect to the same host:port after connected 2.2.0 K Hoang 20/10/2022 Fix crash and memory leak + 2.2.1 K Hoang 09/11/2022 Default to reconnect to the same host:port after connected for new HTTP sites *****************************************************************************************************************************/ #pragma once @@ -50,13 +51,13 @@ //////////////////////////////////////// -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION "AsyncHTTPSRequest_Generic v2.2.0" +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION "AsyncHTTPSRequest_Generic v2.2.1" #define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MAJOR 2 #define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_MINOR 2 -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_PATCH 0 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_PATCH 1 -#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT 2002000 +#define ASYNC_HTTPS_REQUEST_GENERIC_VERSION_INT 2002001 //////////////////////////////////////// @@ -64,6 +65,15 @@ #include "AsyncHTTPSRequest_Debug_Generic.h" +//////////////////////////////////////// + +#if !defined(NOT_SEND_HEADER_AFTER_CONNECTED) + // Default is false + #define NOT_SEND_HEADER_AFTER_CONNECTED false +#endif + +//////////////////////////////////////// + #ifndef DEBUG_IOTA_PORT #define DEBUG_IOTA_PORT Serial #endif @@ -107,6 +117,8 @@ #define _AHTTPS_lock xSemaphoreTakeRecursive(threadLock,portMAX_DELAY) #define _AHTTPS_unlock xSemaphoreGiveRecursive(threadLock) + +//////////////////////////////////////// #elif defined(ESP8266) @@ -119,6 +131,8 @@ #define _AHTTPS_lock #define _AHTTPS_unlock + +//////////////////////////////////////// #elif ( defined(STM32F0) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) ||defined(STM32F4) || defined(STM32F7) || \ defined(STM32L0) || defined(STM32L1) || defined(STM32L4) || defined(STM32H7) ||defined(STM32G0) || defined(STM32G4) || \ @@ -131,6 +145,8 @@ #define MUTEX_LOCK(returnVal) #define _AHTTPS_lock #define _AHTTPS_unlock + +//////////////////////////////////////// #else #error Not supported board @@ -152,6 +168,9 @@ struct xseg uint8_t data[]; }; +//////////////////////////////////////// +//////////////////////////////////////// + class xbuf: public Print { public: @@ -269,6 +288,8 @@ class xbuf: public Print #define HTTPCODE_STREAM_WRITE (-10) #define HTTPCODE_TIMEOUT (-11) +//////////////////////////////////////// + typedef enum { readyStateUnsent = 0, // Client created, open not yet called diff --git a/src/AsyncHTTPSRequest_Impl_Generic.h b/src/AsyncHTTPSRequest_Impl_Generic.h index e580621..b520e7a 100644 --- a/src/AsyncHTTPSRequest_Impl_Generic.h +++ b/src/AsyncHTTPSRequest_Impl_Generic.h @@ -1,24 +1,24 @@ /**************************************************************************************************************************** AsyncHTTPSRequest_Impl_Generic.h - + For ESP32, future ESP8266 - + AsyncHTTPSRequest is a library for the ESP32, ESP8266 (not-yet ready) - + Based on and modified from AsyncHTTPRequest Library (https://github.com/boblemaire/asyncHTTPrequest) - + Built by Khoi Hoang https://github.com/khoih-prog/AsyncHTTPSRequest_Generic - + Copyright (C) <2018> - This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published bythe 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 . - - Version: 2.2.0 - + You should have received a copy of the GNU General Public License along with this program. + If not, see . + + Version: 2.2.1 + Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 21/10/2021 Initial coding to support only ESP32 @@ -35,8 +35,9 @@ 2.1.2 K Hoang 18/09/2022 Fix bug and compiler error in some cases 2.1.3 K Hoang 18/10/2022 Not try to reconnect to the same host:port after connected 2.2.0 K Hoang 20/10/2022 Fix crash and memory leak + 2.2.1 K Hoang 09/11/2022 Default to reconnect to the same host:port after connected for new HTTP sites *****************************************************************************************************************************/ - + #pragma once #ifndef ASYNC_HTTPS_REQUEST_GENERIC_IMPL_H @@ -52,119 +53,119 @@ // Merge xbuf //////////////////////////////////////// -xbuf::xbuf(const uint16_t segSize) : _head(nullptr), _tail(nullptr), _used(0), _free(0), _offset(0) +xbuf::xbuf(const uint16_t segSize) : _head(nullptr), _tail(nullptr), _used(0), _free(0), _offset(0) { _segSize = (segSize + 3) & -4;//((segSize + 3) >> 2) << 2; } //////////////////////////////////////// -xbuf::~xbuf() +xbuf::~xbuf() { flush(); } //////////////////////////////////////// -size_t xbuf::write(const uint8_t byte) +size_t xbuf::write(const uint8_t byte) { return write((uint8_t*) &byte, 1); } //////////////////////////////////////// -size_t xbuf::write(const char* buf) +size_t xbuf::write(const char* buf) { return write((uint8_t*)buf, strlen(buf)); } //////////////////////////////////////// -size_t xbuf::write(const String& string) +size_t xbuf::write(const String& string) { return write((uint8_t*)string.c_str(), string.length()); } //////////////////////////////////////// -size_t xbuf::write(const uint8_t* buf, const size_t len) +size_t xbuf::write(const uint8_t* buf, const size_t len) { size_t supply = len; - - while (supply) + + while (supply) { - if (!_free) + if (!_free) { addSeg(); } - + size_t demand = _free < supply ? _free : supply; memcpy(_tail->data + ((_offset + _used) % _segSize), buf + (len - supply), demand); _free -= demand; _used += demand; supply -= demand; } - + return len; } //////////////////////////////////////// -size_t xbuf::write(xbuf* buf, const size_t len) +size_t xbuf::write(xbuf* buf, const size_t len) { size_t supply = len; - - if (supply > buf->available()) + + if (supply > buf->available()) { supply = buf->available(); } - + size_t read = 0; - - while (supply) + + while (supply) { - if (!_free) + if (!_free) { addSeg(); } - + size_t demand = _free < supply ? _free : supply; read += buf->read(_tail->data + ((_offset + _used) % _segSize), demand); _free -= demand; _used += demand; supply -= demand; } - + return read; } //////////////////////////////////////// -uint8_t xbuf::read() +uint8_t xbuf::read() { uint8_t byte = 0; read((uint8_t*) &byte, 1); - + return byte; } //////////////////////////////////////// -uint8_t xbuf::peek() +uint8_t xbuf::peek() { uint8_t byte = 0; peek((uint8_t*) &byte, 1); - + return byte; } //////////////////////////////////////// -size_t xbuf::read(uint8_t* buf, const size_t len) +size_t xbuf::read(uint8_t* buf, const size_t len) { size_t read = 0; - - while (read < len && _used) + + while (read < len && _used) { size_t supply = (_offset + _used) > _segSize ? _segSize - _offset : _used; size_t demand = len - read; @@ -173,225 +174,225 @@ size_t xbuf::read(uint8_t* buf, const size_t len) _offset += chunk; _used -= chunk; read += chunk; - - if (_offset == _segSize) + + if (_offset == _segSize) { remSeg(); _offset = 0; } } - - if ( ! _used) + + if ( ! _used) { flush(); } - + return read; } //////////////////////////////////////// -size_t xbuf::peek(uint8_t* buf, const size_t len) +size_t xbuf::peek(uint8_t* buf, const size_t len) { size_t read = 0; xseg* seg = _head; size_t offset = _offset; size_t used = _used; - - while (read < len && used) + + while (read < len && used) { size_t supply = (offset + used) > _segSize ? _segSize - offset : used; size_t demand = len - read; size_t chunk = supply < demand ? supply : demand; - + memcpy(buf + read, seg->data + offset, chunk); - + offset += chunk; used -= chunk; read += chunk; - - if (offset == _segSize) + + if (offset == _segSize) { seg = seg->next; offset = 0; } } - + return read; } //////////////////////////////////////// -size_t xbuf::available() +size_t xbuf::available() { return _used; } //////////////////////////////////////// -int xbuf::indexOf(const char target, const size_t begin) +int xbuf::indexOf(const char target, const size_t begin) { char targetstr[2] = " "; targetstr[0] = target; - + return indexOf(targetstr, begin); } //////////////////////////////////////// -int xbuf::indexOf(const char* target, const size_t begin) +int xbuf::indexOf(const char* target, const size_t begin) { size_t targetLen = strlen(target); - - if (targetLen > _segSize || targetLen > _used) + + if (targetLen > _segSize || targetLen > _used) return -1; - + size_t searchPos = _offset + begin; size_t searchEnd = _offset + _used - targetLen; - - if (searchPos > searchEnd) + + if (searchPos > searchEnd) return -1; - + size_t searchSeg = searchPos / _segSize; xseg* seg = _head; - - while (searchSeg) + + while (searchSeg) { seg = seg->next; searchSeg --; } - + size_t segPos = searchPos % _segSize; - - while (searchPos <= searchEnd) + + while (searchPos <= searchEnd) { size_t compLen = targetLen; - - if (compLen <= (_segSize - segPos)) + + if (compLen <= (_segSize - segPos)) { - if (memcmp(target, seg->data + segPos, compLen) == 0) + if (memcmp(target, seg->data + segPos, compLen) == 0) { return searchPos - _offset; } } - else + else { size_t compLen = _segSize - segPos; - - if (memcmp(target, seg->data + segPos, compLen) == 0) + + if (memcmp(target, seg->data + segPos, compLen) == 0) { compLen = targetLen - compLen; - - if (memcmp(target + targetLen - compLen, seg->next->data, compLen) == 0) + + if (memcmp(target + targetLen - compLen, seg->next->data, compLen) == 0) { return searchPos - _offset; } } } - + searchPos++; segPos++; - - if (segPos == _segSize) + + if (segPos == _segSize) { seg = seg->next; segPos = 0; } } - + return -1; } //////////////////////////////////////// -String xbuf::readStringUntil(const char target) +String xbuf::readStringUntil(const char target) { return readString(indexOf(target) + 1); } //////////////////////////////////////// -String xbuf::readStringUntil(const char* target) +String xbuf::readStringUntil(const char* target) { int index = indexOf(target); - - if (index < 0) + + if (index < 0) return String(); - + return readString(index + strlen(target)); } //////////////////////////////////////// -String xbuf::readString(int endPos) +String xbuf::readString(int endPos) { String result; - - if ( ! result.reserve(endPos + 1)) - { + + if ( ! result.reserve(endPos + 1)) + { return result; } - - if (endPos > _used) + + if (endPos > _used) { endPos = _used; } - - if (endPos > 0 && result.reserve(endPos + 1)) + + if (endPos > 0 && result.reserve(endPos + 1)) { - while (endPos--) + while (endPos--) { result += (char)_head->data[_offset++]; _used--; - - if (_offset >= _segSize) + + if (_offset >= _segSize) { remSeg(); } } } - + return result; } //////////////////////////////////////// -String xbuf::peekString(int endPos) +String xbuf::peekString(int endPos) { String result; - + xseg* seg = _head; size_t offset = _offset; - - if (endPos > _used) + + if (endPos > _used) { endPos = _used; } - - if (endPos > 0 && result.reserve(endPos + 1)) + + if (endPos > 0 && result.reserve(endPos + 1)) { - while (endPos--) + while (endPos--) { result += (char)seg->data[offset++]; - - if ( offset >= _segSize) + + if ( offset >= _segSize) { seg = seg->next; offset = 0; } } } - + return result; } //////////////////////////////////////// -void xbuf::flush() +void xbuf::flush() { - while (_head) + while (_head) remSeg(); - + _tail = nullptr; _offset = 0; _used = 0; @@ -399,54 +400,54 @@ void xbuf::flush() } //////////////////////////////////////// -void xbuf::addSeg() +void xbuf::addSeg() { - if (_tail) + if (_tail) { _tail->next = (xseg*) new uint32_t[_segSize / 4 + 1]; - + if (_tail->next == NULL) { AHTTPS_LOGERROR(F("xbuf::addSeg: error new 1")); - } - else + } + else { // KH, Must check NULL here _tail = _tail->next; } } - else + else { // KH, Must check NULL here _tail = _head = (xseg*) new uint32_t[_segSize / 4 + 1]; - + if (_tail == NULL) AHTTPS_LOGERROR(F("xbuf::addSeg: error new 2")); } - + // KH, Must check NULL here if (_tail) _tail->next = nullptr; - + _free += _segSize; } //////////////////////////////////////// -void xbuf::remSeg() +void xbuf::remSeg() { - if (_head) + if (_head) { xseg *next = _head->next; delete[] (uint32_t*) _head; _head = next; - - if ( ! _head) + + if ( ! _head) { _tail = nullptr; } } - + _offset = 0; } @@ -455,7 +456,8 @@ void xbuf::remSeg() //////////////////////////////////////// //////////////////////////////////////// -AsyncHTTPSRequest::AsyncHTTPSRequest(): _readyState(readyStateUnsent), _HTTPcode(0), _chunked(false), _debug(DEBUG_IOTA_HTTP_SET) +AsyncHTTPSRequest::AsyncHTTPSRequest(): _readyState(readyStateUnsent), _HTTPcode(0), _chunked(false), + _debug(DEBUG_IOTA_HTTP_SET) , _timeout(DEFAULT_RX_TIMEOUT), _lastActivity(0), _requestStartTime(0), _requestEndTime(0), _URL(nullptr) , _connectedHost(nullptr), _connectedPort(-1), _client(nullptr), _contentLength(0), _contentRead(0) , _readyStateChangeCB(nullptr), _readyStateChangeCBarg(nullptr), _onDataCB(nullptr), _onDataCBarg(nullptr) @@ -483,11 +485,13 @@ AsyncHTTPSRequest::~AsyncHTTPSRequest() SAFE_DELETE_ARRAY(_connectedHost) #ifdef ESP32 + // KH add if (threadLock) { - vSemaphoreDelete(threadLock); + vSemaphoreDelete(threadLock); } + #endif } @@ -499,7 +503,7 @@ void AsyncHTTPSRequest::setDebug(bool debug) { _debug = true; } - + _debug = debug; } @@ -514,21 +518,21 @@ bool AsyncHTTPSRequest::debug() // KH Add for HTTPS -AsyncHTTPSRequest& AsyncHTTPSRequest::setSecure(bool secure) +AsyncHTTPSRequest& AsyncHTTPSRequest::setSecure(bool secure) { _secure = secure; - + return *this; } //////////////////////////////////////// -AsyncHTTPSRequest& AsyncHTTPSRequest::addServerFingerprint(const uint8_t* fingerprint) +AsyncHTTPSRequest& AsyncHTTPSRequest::addServerFingerprint(const uint8_t* fingerprint) { std::array newFingerprint; memcpy(newFingerprint.data(), fingerprint, SHA1_SIZE); _secureServerFingerprints.push_back(newFingerprint); - + return *this; } @@ -541,18 +545,18 @@ bool AsyncHTTPSRequest::open(const char* method, const char* URL) if (_readyState != readyStateUnsent && _readyState != readyStateDone) { AHTTPS_LOGERROR(F("open: not ready")); - + return false; } _requestStartTime = millis(); - + SAFE_DELETE(_URL) SAFE_DELETE(_headers) SAFE_DELETE(_request) SAFE_DELETE(_response) SAFE_DELETE(_chunks) - + _URL = nullptr; _headers = nullptr; _response = nullptr; @@ -561,10 +565,8 @@ bool AsyncHTTPSRequest::open(const char* method, const char* URL) _chunked = false; _contentRead = 0; _readyState = readyStateUnsent; - - // New in v1.1.1 + _requestReadyToSend = false; - ////// if (strcmp(method, "GET") == 0) { @@ -574,7 +576,6 @@ bool AsyncHTTPSRequest::open(const char* method, const char* URL) { _HTTPmethod = HTTPmethodPOST; } - // New in v1.1.0 else if (strcmp(method, "PUT") == 0) { _HTTPmethod = HTTPmethodPUT; @@ -591,69 +592,81 @@ bool AsyncHTTPSRequest::open(const char* method, const char* URL) { _HTTPmethod = HTTPmethodHEAD; } - ////// else { AHTTPS_LOGERROR(F("open: Bad method")); - + return false; } if (!_parseURL(URL)) { AHTTPS_LOGERROR(F("open: error parsing URL")); - + return false; } +#if NOT_SEND_HEADER_AFTER_CONNECTED + if ( _client && _client->connected() ) { if ( (strcmp(_URL->host, _connectedHost) == 0) && (_URL->port == _connectedPort) ) { AHTTPS_LOGINFO(F("open: already connected")); - + _lastActivity = millis(); - + _requestReadyToSend = true; - + return _connect(); } else - { + { AHTTPS_LOGINFO(F("open: not connected: different host or port")); - + return false; } } +#else + + if ( _client && _client->connected() && (strcmp(_URL->host, _connectedHost) != 0 || _URL->port != _connectedPort)) + { + AHTTPS_LOGERROR(F("open: not connected")); + + return false; + } + +#endif + char* hostName = new char[strlen(_URL->host) + 10]; - + if (hostName) { sprintf(hostName, "%s:%d", _URL->host, _URL->port); _addHeader("host", hostName); - + AHTTPS_LOGINFO1(F("open: connecting to hostname ="), hostName); - + SAFE_DELETE_ARRAY(hostName) - + _lastActivity = millis(); - + _requestReadyToSend = true; - + return _connect(); } else { AHTTPS_LOGERROR(F("open: error alloc")); - + return false; } } //////////////////////////////////////// -void AsyncHTTPSRequest::onReadyStateChange(readyStateChangeCB cb, void* arg) +void AsyncHTTPSRequest::onReadyStateChange(readyStateChangeCB cb, void* arg) { _readyStateChangeCB = cb; _readyStateChangeCBarg = arg; @@ -662,7 +675,7 @@ void AsyncHTTPSRequest::onReadyStateChange(readyStateChangeCB cb, void* arg) //////////////////////////////////////// -void AsyncHTTPSRequest::setTimeout(int seconds) +void AsyncHTTPSRequest::setTimeout(int seconds) { _timeout = seconds; } @@ -670,24 +683,24 @@ void AsyncHTTPSRequest::setTimeout(int seconds) //////////////////////////////////////// -bool AsyncHTTPSRequest::send() -{ +bool AsyncHTTPSRequest::send() +{ if (!_requestReadyToSend) { AHTTPS_LOGERROR(CANT_SEND_BAD_REQUEST); - + return false; } MUTEX_LOCK(false) - - if ( ! _buildRequest()) + + if ( ! _buildRequest()) return false; - + _send(); - + _AHTTPS_unlock; - + return true; } @@ -699,56 +712,56 @@ bool AsyncHTTPSRequest::send(const String& body) if (!_requestReadyToSend) { AHTTPS_LOGERROR(CANT_SEND_BAD_REQUEST); - + return false; } MUTEX_LOCK(false) - + _addHeader("Content-Length", String(body.length()).c_str()); - - if ( ! _buildRequest()) + + if ( ! _buildRequest()) { _AHTTPS_unlock; - + return false; } - + _request->write(body); _send(); - + _AHTTPS_unlock; - + return true; } //////////////////////////////////////// -bool AsyncHTTPSRequest::send(const char* body) +bool AsyncHTTPSRequest::send(const char* body) { if (!_requestReadyToSend) { AHTTPS_LOGERROR(CANT_SEND_BAD_REQUEST); - + return false; } MUTEX_LOCK(false) - + _addHeader("Content-Length", String(strlen(body)).c_str()); - - if ( ! _buildRequest()) + + if ( ! _buildRequest()) { _AHTTPS_unlock; - + return false; } - + _request->write(body); _send(); - + _AHTTPS_unlock; - + return true; } @@ -764,21 +777,21 @@ bool AsyncHTTPSRequest::send(const uint8_t* body, size_t len) } MUTEX_LOCK(false) - + _addHeader("Content-Length", String(len).c_str()); - - if ( ! _buildRequest()) + + if ( ! _buildRequest()) { _AHTTPS_unlock; - + return false; } - + _request->write(body, len); _send(); - + _AHTTPS_unlock; - + return true; } @@ -794,21 +807,21 @@ bool AsyncHTTPSRequest::send(xbuf* body, size_t len) } MUTEX_LOCK(false) - + _addHeader("Content-Length", String(len).c_str()); - - if ( ! _buildRequest()) + + if ( ! _buildRequest()) { _AHTTPS_unlock; - + return false; } - + _request->write(body, len); _send(); - + _AHTTPS_unlock; - + return true; } @@ -823,11 +836,11 @@ void AsyncHTTPSRequest::abort() { return; } - + MUTEX_LOCK_NR - + _client->abort(); - + _AHTTPS_unlock; } @@ -852,75 +865,167 @@ int AsyncHTTPSRequest::responseHTTPcode() String AsyncHTTPSRequest::responseHTTPString() { - switch(_HTTPcode) + switch (_HTTPcode) { - case 0: + case 0: return F("OK"); - case HTTPCODE_CONNECTION_REFUSED: + + case HTTPCODE_CONNECTION_REFUSED: return F("CONNECTION_REFUSED"); - case HTTPCODE_SEND_HEADER_FAILED: + + case HTTPCODE_SEND_HEADER_FAILED: return F("SEND_HEADER_FAILED"); - case HTTPCODE_SEND_PAYLOAD_FAILED: + + case HTTPCODE_SEND_PAYLOAD_FAILED: return F("SEND_PAYLOAD_FAILED"); - case HTTPCODE_NOT_CONNECTED: + + case HTTPCODE_NOT_CONNECTED: return F("NOT_CONNECTED"); - case HTTPCODE_CONNECTION_LOST: + + case HTTPCODE_CONNECTION_LOST: return F("CONNECTION_LOST"); - case HTTPCODE_NO_STREAM: + + case HTTPCODE_NO_STREAM: return F("NO_STREAM"); - case HTTPCODE_NO_HTTP_SERVER: + + case HTTPCODE_NO_HTTP_SERVER: return F("NO_HTTP_SERVER"); - case HTTPCODE_TOO_LESS_RAM: + + case HTTPCODE_TOO_LESS_RAM: return F("TOO_LESS_RAM"); - case HTTPCODE_ENCODING: + + case HTTPCODE_ENCODING: return F("ENCODING"); - case HTTPCODE_STREAM_WRITE: + + case HTTPCODE_STREAM_WRITE: return F("STREAM_WRITE"); - case HTTPCODE_TIMEOUT: + + case HTTPCODE_TIMEOUT: return F("TIMEOUT"); - - // HTTP positive code - case 100: return F("Continue"); - case 101: return F("Switching Protocols"); - case 200: return F("HTTP OK"); - case 201: return F("Created"); - case 202: return F("Accepted"); - case 203: return F("Non-Authoritative Information"); - case 204: return F("No Content"); - case 205: return F("Reset Content"); - case 206: return F("Partial Content"); - case 300: return F("Multiple Choices"); - case 301: return F("Moved Permanently"); - case 302: return F("Found"); - case 303: return F("See Other"); - case 304: return F("Not Modified"); - case 305: return F("Use Proxy"); - case 307: return F("Temporary Redirect"); - case 400: return F("Bad Request"); - case 401: return F("Unauthorized"); - case 402: return F("Payment Required"); - case 403: return F("Forbidden"); - case 404: return F("Not Found"); - case 405: return F("Method Not Allowed"); - case 406: return F("Not Acceptable"); - case 407: return F("Proxy Authentication Required"); - case 408: return F("Request Time-out"); - case 409: return F("Conflict"); - case 410: return F("Gone"); - case 411: return F("Length Required"); - case 412: return F("Precondition Failed"); - case 413: return F("Request Entity Too Large"); - case 414: return F("Request-URI Too Large"); - case 415: return F("Unsupported Media Type"); - case 416: return F("Requested range not satisfiable"); - case 417: return F("Expectation Failed"); - case 500: return F("Internal Server Error"); - case 501: return F("Not Implemented"); - case 502: return F("Bad Gateway"); - case 503: return F("Service Unavailable"); - case 504: return F("Gateway Time-out"); - case 505: return F("HTTP Version not supported"); - default: return "UNKNOWN"; + + // HTTP positive code + case 100: + return F("Continue"); + + case 101: + return F("Switching Protocols"); + + case 200: + return F("HTTP OK"); + + case 201: + return F("Created"); + + case 202: + return F("Accepted"); + + case 203: + return F("Non-Authoritative Information"); + + case 204: + return F("No Content"); + + case 205: + return F("Reset Content"); + + case 206: + return F("Partial Content"); + + case 300: + return F("Multiple Choices"); + + case 301: + return F("Moved Permanently"); + + case 302: + return F("Found"); + + case 303: + return F("See Other"); + + case 304: + return F("Not Modified"); + + case 305: + return F("Use Proxy"); + + case 307: + return F("Temporary Redirect"); + + case 400: + return F("Bad Request"); + + case 401: + return F("Unauthorized"); + + case 402: + return F("Payment Required"); + + case 403: + return F("Forbidden"); + + case 404: + return F("Not Found"); + + case 405: + return F("Method Not Allowed"); + + case 406: + return F("Not Acceptable"); + + case 407: + return F("Proxy Authentication Required"); + + case 408: + return F("Request Time-out"); + + case 409: + return F("Conflict"); + + case 410: + return F("Gone"); + + case 411: + return F("Length Required"); + + case 412: + return F("Precondition Failed"); + + case 413: + return F("Request Entity Too Large"); + + case 414: + return F("Request-URI Too Large"); + + case 415: + return F("Unsupported Media Type"); + + case 416: + return F("Requested range not satisfiable"); + + case 417: + return F("Expectation Failed"); + + case 500: + return F("Internal Server Error"); + + case 501: + return F("Not Implemented"); + + case 502: + return F("Bad Gateway"); + + case 503: + return F("Service Unavailable"); + + case 504: + return F("Gateway Time-out"); + + case 505: + return F("HTTP Version not supported"); + + default: + return "UNKNOWN"; } } @@ -930,34 +1035,34 @@ String AsyncHTTPSRequest::responseHTTPString() String AsyncHTTPSRequest::responseText() { MUTEX_LOCK(String()) - + if ( ! _response || _readyState < readyStateLoading || ! available()) { AHTTPS_LOGERROR(F("responseText() no data")); _AHTTPS_unlock; - + return String(); } size_t avail = available(); - + String localString = _response->readString(avail); - - if (localString.length() < avail) + + if (localString.length() < avail) { AHTTPS_LOGERROR(F("!responseText() no buffer")) _HTTPcode = HTTPCODE_TOO_LESS_RAM; _client->abort(); _AHTTPS_unlock; - + return String(); } - + _contentRead += localString.length(); - + _AHTTPS_unlock; - + return localString; } @@ -967,7 +1072,7 @@ String AsyncHTTPSRequest::responseText() #if defined(ESP32) #define HTTPS_GLOBAL_STR_LEN (32 * 1024) #elif defined(ESP8266) - #define HTTPS_GLOBAL_STR_LEN (16 * 1024) + #define HTTPS_GLOBAL_STR_LEN (16 * 1024) #else #define HTTPS_GLOBAL_STR_LEN (4 * 1024) #endif @@ -981,13 +1086,13 @@ char globalLongStringHTTPS[HTTPS_GLOBAL_STR_LEN + 1]; char* AsyncHTTPSRequest::responseLongText() { MUTEX_LOCK(NULL) - + if ( ! _response || _readyState < readyStateLoading || ! available()) { AHTTPS_LOGERROR(F("responseText() no data")); _AHTTPS_unlock; - + return NULL; } @@ -996,11 +1101,11 @@ char* AsyncHTTPSRequest::responseLongText() strncpy(globalLongStringHTTPS, _response->readString(avail).c_str(), lenToCopy ); globalLongStringHTTPS[ lenToCopy + 1 ] = 0; - + _contentRead += _response->readString(avail).length(); - + _AHTTPS_unlock; - + return globalLongStringHTTPS; } @@ -1016,12 +1121,12 @@ size_t AsyncHTTPSRequest::responseRead(uint8_t* buf, size_t len) } MUTEX_LOCK(0) - + size_t avail = available() > len ? len : available(); _response->read(buf, avail); _contentRead += avail; - + _AHTTPS_unlock; return avail; @@ -1103,21 +1208,21 @@ bool AsyncHTTPSRequest::_parseURL(const char* url) bool AsyncHTTPSRequest::_parseURL(const String& url) { SAFE_DELETE(_URL) - + int hostBeg = 0; - + _URL = new URL; - + if (_URL) { _URL->scheme = new char[strlen(ASYNC_HTTPS_PREFIX) + 1]; - + if (! (_URL->scheme) ) return false; } else return false; - + // KH mod for HTTPS if ( url.substring(0, strlen(ASYNC_HTTP_PREFIX)).equalsIgnoreCase(ASYNC_HTTP_PREFIX) ) { @@ -1131,6 +1236,7 @@ bool AsyncHTTPSRequest::_parseURL(const String& url) strcpy(_URL->scheme, ASYNC_HTTPS_PREFIX); hostBeg += strlen(ASYNC_HTTPS_PREFIX); } + ////// int pathBeg = url.indexOf('/', hostBeg); @@ -1148,29 +1254,29 @@ bool AsyncHTTPSRequest::_parseURL(const String& url) } _URL->host = new char[hostEnd - hostBeg + 1]; - + if (_URL->host == nullptr) return false; - + strcpy(_URL->host, url.substring(hostBeg, hostEnd).c_str()); int queryBeg = url.indexOf('?'); - - if (queryBeg < 0) + + if (queryBeg < 0) queryBeg = url.length(); - + _URL->path = new char[queryBeg - pathBeg + 1]; - + if (_URL->path == nullptr) return false; - + strcpy(_URL->path, url.substring(pathBeg, queryBeg).c_str()); - + _URL->query = new char[url.length() - queryBeg + 1]; - + if (_URL->query == nullptr) return false; - + strcpy(_URL->query, url.substring(queryBeg).c_str()); return true; @@ -1183,7 +1289,7 @@ bool AsyncHTTPSRequest::_connect() if ( ! _client) { _client = new AsyncSSLClient(); - + if (! _client) return false; } @@ -1191,29 +1297,29 @@ bool AsyncHTTPSRequest::_connect() SAFE_DELETE_ARRAY(_connectedHost) _connectedHost = new char[strlen(_URL->host) + 1]; - + if (_connectedHost == nullptr) return false; - + strcpy(_connectedHost, _URL->host); _connectedPort = _URL->port; - - _client->onConnect([](void *obj, AsyncSSLClient * client) + + _client->onConnect([](void *obj, AsyncSSLClient * client) { ((AsyncHTTPSRequest*)(obj))->_onConnect(client); }, this); - - _client->onDisconnect([](void *obj, AsyncSSLClient * client) + + _client->onDisconnect([](void *obj, AsyncSSLClient * client) { ((AsyncHTTPSRequest*)(obj))->_onDisconnect(client); }, this); - - _client->onPoll([](void *obj, AsyncSSLClient * client) + + _client->onPoll([](void *obj, AsyncSSLClient * client) { ((AsyncHTTPSRequest*)(obj))->_onPoll(client); }, this); - - _client->onError([](void *obj, AsyncSSLClient * client, uint32_t error) + + _client->onError([](void *obj, AsyncSSLClient * client, uint32_t error) { ((AsyncHTTPSRequest*)(obj))->_onError(client, error); }, this); @@ -1221,10 +1327,10 @@ bool AsyncHTTPSRequest::_connect() if ( ! _client->connected()) { AHTTPS_LOGINFO3(F("_client->connecting to"), _URL->host, F(","), _URL->port); - + // KH, for HTTPS if ( ! _client->connect(_URL->host, _URL->port, true)) - ////// + ////// { AHTTPS_LOGERROR3(F("client.connect failed:"), _URL->host, F(","), _URL->port); @@ -1244,7 +1350,7 @@ bool AsyncHTTPSRequest::_connect() } _lastActivity = millis(); - + return true; } @@ -1256,7 +1362,7 @@ bool AsyncHTTPSRequest::_buildRequest() if ( ! _request) { _request = new xbuf; - + if ( ! _request) return false; } @@ -1264,29 +1370,29 @@ bool AsyncHTTPSRequest::_buildRequest() _request->write(_HTTPmethodStringwithSpace[_HTTPmethod]); _request->write(_URL->path); _request->write(_URL->query); - + _request->write(" HTTP/1.1\r\n"); - + SAFE_DELETE(_URL) _URL = nullptr; header* hdr = _headers; - + while (hdr) { _request->write(hdr->name); _request->write(':'); _request->write(hdr->value); _request->write("\r\n"); - + hdr = hdr->next; } - + SAFE_DELETE(_headers) - + _headers = nullptr; _request->write("\r\n"); - + return true; } @@ -1296,9 +1402,9 @@ size_t AsyncHTTPSRequest::_send() { if ( ! _request) return 0; - + if ( ! _client->connected()) - { + { // KH fix bug https://github.com/khoih-prog/AsyncHTTPRequest_Generic/issues/38 _HTTPcode = HTTPCODE_NOT_CONNECTED; _setReadyState(readyStateUnsent); @@ -1318,36 +1424,36 @@ size_t AsyncHTTPSRequest::_send() supply = demand; size_t sent = 0; - - #define TEMP_SIZE 255 + +#define TEMP_SIZE 255 uint8_t* temp = new uint8_t[TEMP_SIZE + 1]; - + if (!temp) return 0; while (supply) { size_t chunk = supply < TEMP_SIZE ? supply : TEMP_SIZE; - - memset(temp, 0, TEMP_SIZE + 1); - supply -= _request->read(temp, chunk); + + memset(temp, 0, TEMP_SIZE + 1); + supply -= _request->read(temp, chunk); sent += _client->add((char*)temp, chunk); } - + // KH, Must be delete [] temp; SAFE_DELETE_ARRAY(temp) if (_request->available() == 0) { SAFE_DELETE(_request) - + _request = nullptr; - + // KH fix crash bug return 0; } - + _client->send(); _lastActivity = millis(); @@ -1357,7 +1463,7 @@ size_t AsyncHTTPSRequest::_send() //////////////////////////////////////// -void AsyncHTTPSRequest::_setReadyState(reqStates newState) +void AsyncHTTPSRequest::_setReadyState(reqStates newState) { if (_readyState != newState) { @@ -1422,73 +1528,75 @@ void AsyncHTTPSRequest::_processChunks() void AsyncHTTPSRequest::_onConnect(AsyncSSLClient* client) { MUTEX_LOCK_NR - + _client = client; _setReadyState(readyStateOpened); - + // KH Add HTTPS, not tested yet !!! #if 0 //(ESP8266) - if (_secure && _secureServerFingerprints.size() > 0) + + if (_secure && _secureServerFingerprints.size() > 0) { //SSL* clientSsl = _client.getSSL(); bool sslFoundFingerprint = false; - - for (std::array fingerprint : _secureServerFingerprints) + + for (std::array fingerprint : _secureServerFingerprints) { - //if (ssl_match_fingerprint(clientSsl, fingerprint.data()) == SSL_OK) + //if (ssl_match_fingerprint(clientSsl, fingerprint.data()) == SSL_OK) { AHTTPS_LOGDEBUG(F("_onConnect handler: sslFoundFingerprint")); - + sslFoundFingerprint = true; break; } } - if (!sslFoundFingerprint) + if (!sslFoundFingerprint) { AHTTPS_LOGDEBUG(F("_onConnect handler: _tlsBadFingerprint")); - + _tlsBadFingerprint = true; _client->close(true); return; } } -#endif - + +#endif + // KH test _response = new xbuf; //_response = new xbuf(256); ////// - + if (!_response) { _AHTTPS_unlock; - + // KH, to remove AHTTPS_LOGERROR(F("_onConnect: Can't new _response")); /////// - + return; } - + _contentLength = 0; _contentRead = 0; _chunked = false; - - _client->onAck([](void* obj, AsyncSSLClient * client, size_t len, uint32_t time) + + _client->onAck([](void* obj, AsyncSSLClient * client, size_t len, uint32_t time) { (void) client; (void) len; (void) time; - + ((AsyncHTTPSRequest*)(obj))->_send(); }, this); - - _client->onData([](void* obj, AsyncSSLClient * client, void* data, size_t len) + + _client->onData([](void* obj, AsyncSSLClient * client, void* data, size_t len) { (void) client; - + ((AsyncHTTPSRequest*)(obj))->_onData(data, len); }, this); @@ -1498,7 +1606,7 @@ void AsyncHTTPSRequest::_onConnect(AsyncSSLClient* client) } _lastActivity = millis(); - + _AHTTPS_unlock; } @@ -1507,7 +1615,7 @@ void AsyncHTTPSRequest::_onConnect(AsyncSSLClient* client) void AsyncHTTPSRequest::_onPoll(AsyncSSLClient* client) { (void) client; - + MUTEX_LOCK_NR if (_timeout && (millis() - _lastActivity) > (_timeout * 1000)) @@ -1529,7 +1637,7 @@ void AsyncHTTPSRequest::_onPoll(AsyncSSLClient* client) void AsyncHTTPSRequest::_onError(AsyncSSLClient* client, int8_t error) { (void) client; - + // SSL_error = (Non_SSL_error + 64) // Check void AsyncSSLClient::_ssl_error(int8_t err) => _error_cb(_error_cb_arg, this, err + 64); if (error >= 64) @@ -1545,16 +1653,16 @@ void AsyncHTTPSRequest::_onError(AsyncSSLClient* client, int8_t error) void AsyncHTTPSRequest::_onDisconnect(AsyncSSLClient* client) { (void) client; - + MUTEX_LOCK_NR - + if (_readyState < readyStateOpened) { AHTTPS_LOGDEBUG(F("HTTPCODE_NOT_CONNECTED")); _HTTPcode = HTTPCODE_NOT_CONNECTED; } else if (_HTTPcode > 0 && - (_readyState < readyStateHdrsRecvd || (_contentRead + _response->available()) < _contentLength)) + (_readyState < readyStateHdrsRecvd || (_contentRead + _response->available()) < _contentLength)) { AHTTPS_LOGDEBUG(F("_onDisconnect: HTTPCODE_CONNECTION_LOST")); _HTTPcode = HTTPCODE_CONNECTION_LOST; @@ -1562,35 +1670,35 @@ void AsyncHTTPSRequest::_onDisconnect(AsyncSSLClient* client) // KH, Not in AsyncHTTPRequest SAFE_DELETE(_client) - + _client = nullptr; ////// - + SAFE_DELETE_ARRAY(_connectedHost) - + _connectedHost = nullptr; - + _connectedPort = -1; _requestEndTime = millis(); _lastActivity = 0; _setReadyState(readyStateDone); - + _AHTTPS_unlock; } //////////////////////////////////////// void AsyncHTTPSRequest::_onData(void* Vbuf, size_t len) -{ +{ MUTEX_LOCK_NR - + _lastActivity = millis(); // Transfer data to xbuf if (_chunks) { _chunks->write((uint8_t*)Vbuf, len); - + _processChunks(); } else @@ -1604,7 +1712,7 @@ void AsyncHTTPSRequest::_onData(void* Vbuf, size_t len) if ( ! _collectHeaders()) { _AHTTPS_unlock; - + return; } } @@ -1745,7 +1853,7 @@ void AsyncHTTPSRequest::setReqHeader(const char* name, const __FlashStringHelper { char* _value = _charstar(value); _addHeader(name, _value); - + SAFE_DELETE_ARRAY(_value) } } @@ -1758,7 +1866,7 @@ void AsyncHTTPSRequest::setReqHeader(const __FlashStringHelper *name, const char { char* _name = _charstar(name); _addHeader(_name, value); - + SAFE_DELETE_ARRAY(_name) } } @@ -1772,7 +1880,7 @@ void AsyncHTTPSRequest::setReqHeader(const __FlashStringHelper *name, const __Fl char* _name = _charstar(name); char* _value = _charstar(value); _addHeader(_name, _value); - + SAFE_DELETE_ARRAY(_name) SAFE_DELETE_ARRAY(_value) } @@ -1786,7 +1894,7 @@ void AsyncHTTPSRequest::setReqHeader(const __FlashStringHelper *name, int32_t va { char* _name = _charstar(name); setReqHeader(_name, String(value).c_str()); - + SAFE_DELETE_ARRAY(_name) } } @@ -1815,16 +1923,16 @@ int AsyncHTTPSRequest::respHeaderCount() //////////////////////////////////////// -char* AsyncHTTPSRequest::respHeaderName(int ndx) +char* AsyncHTTPSRequest::respHeaderName(int ndx) { - if (_readyState < readyStateHdrsRecvd) + if (_readyState < readyStateHdrsRecvd) return nullptr; - + header* hdr = _getHeader(ndx); - - if ( ! hdr) + + if ( ! hdr) return nullptr; - + return hdr->name; } @@ -1886,7 +1994,7 @@ char* AsyncHTTPSRequest::respHeaderValue(const __FlashStringHelper *name) char* _name = _charstar(name); header* hdr = _getHeader(_name); - + SAFE_DELETE_ARRAY(_name) if ( ! hdr) @@ -1904,7 +2012,7 @@ bool AsyncHTTPSRequest::respHeaderExists(const __FlashStringHelper *name) char* _name = _charstar(name); header* hdr = _getHeader(_name); - + SAFE_DELETE_ARRAY(_name) if ( ! hdr) @@ -1921,7 +2029,7 @@ bool AsyncHTTPSRequest::respHeaderExists(const __FlashStringHelper *name) String AsyncHTTPSRequest::headers() { MUTEX_LOCK(String()) - + String response = ""; header* hdr = _headers; @@ -1935,7 +2043,7 @@ String AsyncHTTPSRequest::headers() } response += "\r\n"; - + _AHTTPS_unlock; return response; @@ -1946,7 +2054,7 @@ String AsyncHTTPSRequest::headers() AsyncHTTPSRequest::header* AsyncHTTPSRequest::_addHeader(const char* name, const char* value) { MUTEX_LOCK(nullptr) - + header* hdr = (header*) &_headers; while (hdr->next) @@ -1956,7 +2064,7 @@ AsyncHTTPSRequest::header* AsyncHTTPSRequest::_addHeader(const char* name, cons header* oldHdr = hdr->next; hdr->next = hdr->next->next; oldHdr->next = nullptr; - + SAFE_DELETE(oldHdr) } else @@ -1966,29 +2074,29 @@ AsyncHTTPSRequest::header* AsyncHTTPSRequest::_addHeader(const char* name, cons } hdr->next = new header; - + if (hdr->next) { hdr->next->name = new char[strlen(name) + 1]; - + if (hdr->next->name) strcpy(hdr->next->name, name); else { SAFE_DELETE(hdr->next) - + return nullptr; } - + hdr->next->value = new char[strlen(value) + 1]; - + if (hdr->next->value) - strcpy(hdr->next->value, value); + strcpy(hdr->next->value, value); else { SAFE_DELETE_ARRAY(hdr->next->name) SAFE_DELETE(hdr->next) - + return nullptr; } } @@ -1996,7 +2104,7 @@ AsyncHTTPSRequest::header* AsyncHTTPSRequest::_addHeader(const char* name, cons { return nullptr; } - + _AHTTPS_unlock; return hdr->next; @@ -2007,7 +2115,7 @@ AsyncHTTPSRequest::header* AsyncHTTPSRequest::_addHeader(const char* name, cons AsyncHTTPSRequest::header* AsyncHTTPSRequest::_getHeader(const char* name) { MUTEX_LOCK(nullptr) - + header* hdr = _headers; while (hdr) @@ -2028,7 +2136,7 @@ AsyncHTTPSRequest::header* AsyncHTTPSRequest::_getHeader(const char* name) AsyncHTTPSRequest::header* AsyncHTTPSRequest::_getHeader(int ndx) { MUTEX_LOCK(nullptr) - + header* hdr = _headers; while (hdr) @@ -2055,12 +2163,12 @@ char* AsyncHTTPSRequest::_charstar(const __FlashStringHelper * str) return nullptr; char* ptr = new char[strlen_P((PGM_P)str) + 1]; - + if (ptr) { strcpy_P(ptr, (PGM_P)str); } - + // Return good ptr or nullptr return ptr; } diff --git a/utils/astyle_library.conf b/utils/astyle_library.conf new file mode 100644 index 0000000..8a73bc2 --- /dev/null +++ b/utils/astyle_library.conf @@ -0,0 +1,70 @@ +# Code formatting rules for Arduino libraries, modified from for KH libraries: +# +# https://github.com/arduino/Arduino/blob/master/build/shared/examples_formatter.conf +# + +# astyle --style=allman -s2 -t2 -C -S -xW -Y -M120 -f -p -xg -H -xb -c --xC120 -xL *.h *.cpp *.ino + +--mode=c +--lineend=linux +--style=allman + +# -r or -R +#--recursive + +# -c => Converts tabs into spaces +convert-tabs + +# -s2 => 2 spaces indentation +--indent=spaces=2 + +# -t2 => tab =2 spaces +#--indent=tab=2 + +# -C +--indent-classes + +# -S +--indent-switches + +# -xW +--indent-preproc-block + +# -Y => indent classes, switches (and cases), comments starting at column 1 +--indent-col1-comments + +# -M120 => maximum of 120 spaces to indent a continuation line +--max-continuation-indent=120 + +# -xC120 => max‑code‑length will break a line if the code exceeds # characters +--max-code-length=120 + +# -f => +--break-blocks + +# -p => put a space around operators +--pad-oper + +# -xg => Insert space padding after commas +--pad-comma + +# -H => put a space after if/for/while +pad-header + +# -xb => Break one line headers (e.g. if/for/while) +--break-one-line-headers + +# -c => Converts tabs into spaces +#--convert-tabs + +# if you like one-liners, keep them +#keep-one-line-statements + +# -xV +--attach-closing-while + +#unpad-paren + +# -xp +remove-comment-prefix + diff --git a/utils/restyle.sh b/utils/restyle.sh new file mode 100644 index 0000000..bcd846f --- /dev/null +++ b/utils/restyle.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +for dir in . ; do + find $dir -type f \( -name "*.c" -o -name "*.h" -o -name "*.cpp" -o -name "*.ino" \) -exec astyle --suffix=none --options=./utils/astyle_library.conf \{\} \; +done +