From 355a666ade435f89d3057744703d9bf1ae5a7998 Mon Sep 17 00:00:00 2001 From: Jeroen88 Date: Sat, 13 Oct 2018 17:02:07 +0200 Subject: [PATCH 1/5] Added baudrate detection to esp32-hal-uart and HardwareSerial --- cores/esp32/HardwareSerial.cpp | 22 ++++++++++-- cores/esp32/HardwareSerial.h | 20 ++++++++++- cores/esp32/esp32-hal-uart.c | 62 ++++++++++++++++++++++++++++++++++ cores/esp32/esp32-hal-uart.h | 2 ++ 4 files changed, 103 insertions(+), 3 deletions(-) diff --git a/cores/esp32/HardwareSerial.cpp b/cores/esp32/HardwareSerial.cpp index 1871a4b51d1..8bc9c61fe65 100644 --- a/cores/esp32/HardwareSerial.cpp +++ b/cores/esp32/HardwareSerial.cpp @@ -30,7 +30,7 @@ HardwareSerial Serial2(2); HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _uart(NULL) {} -void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert) +void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout) { if(0 > _uart_nr || _uart_nr > 2) { log_e("Serial number is invalid, please use 0, 1 or 2"); @@ -51,7 +51,25 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in rxPin = RX2; txPin = TX2; } - _uart = uartBegin(_uart_nr, baud, config, rxPin, txPin, 256, invert); + + _uart = uartBegin(_uart_nr, baud ? baud : 9600, config, rxPin, txPin, 256, invert); + + if(!baud) { + time_t startMillis = millis(); + unsigned long detectedBaudRate; + while(millis() - startMillis < timeout && !(detectedBaudRate = uartDetectBaudrate(_uart))) { + yield(); + } + + end(); + + if(detectedBaudRate) { + _uart = uartBegin(_uart_nr, detectedBaudRate, config, rxPin, txPin, 256, invert); + } else { + log_e("Could not detect baudrate. Serial data at the port must be present within the timeout for detection to be possible"); + _uart = NULL; + } + } } void HardwareSerial::end() diff --git a/cores/esp32/HardwareSerial.h b/cores/esp32/HardwareSerial.h index a5a3f671cf0..540a21f5877 100644 --- a/cores/esp32/HardwareSerial.h +++ b/cores/esp32/HardwareSerial.h @@ -22,6 +22,24 @@ Modified 18 December 2014 by Ivan Grokhotkov (esp8266 platform support) Modified 31 March 2015 by Markus Sattler (rewrite the code for UART0 + UART1 support in ESP8266) Modified 25 April 2015 by Thomas Flayols (add configuration different from 8N1 in ESP8266) + Modified 13 October 2018 by Jeroen Döll (add baudrate detection) + Baudrate detection example usage (detection on Serial1): + void setup() { + Serial.begin(115200); + delay(100); + Serial.println(); + + Serial1.begin(0, SERIAL_8N1, -1, -1, true, 11000UL); // Passing 0 for baudrate to detect it, the last parameter is a timeout in ms + + unsigned long detectedBaudRate = Serial1.baudRate(); + if(detectedBaudRate) { + Serial.printf("Detected baudrate is %lu\n", detectedBaudRate); + } else { + Serial.println("No baudrate detected, Serial1 will not work!"); + } + } + + Pay attention: the baudrate returned by baudRate() may be rounded, eg 115200 returns 115201 */ #ifndef HardwareSerial_h @@ -37,7 +55,7 @@ class HardwareSerial: public Stream public: HardwareSerial(int uart_nr); - void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false); + void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false, unsigned long timeout = 20000UL); void end(); int available(void); int availableForWrite(void); diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c index 08956e18797..0d1e8d1c22b 100644 --- a/cores/esp32/esp32-hal-uart.c +++ b/cores/esp32/esp32-hal-uart.c @@ -455,3 +455,65 @@ int log_printf(const char *format, ...) } return len; } + +/* + * if enough pulses are detected return the minimum high pulse duration + minimum low pulse duration divided by two. + * This equals one bit period. If flag is true the function return inmediately, otherwise it waits for enough pulses. + */ +unsigned long uartBaudrateDetect(uart_t *uart, bool flg) +{ + while(uart->dev->rxd_cnt.edge_cnt < 30) { // UART_PULSE_NUM(uart_num) + if(flg) return 0; + ets_delay_us(1000); + } + + UART_MUTEX_LOCK(); + unsigned long ret = ((uart->dev->lowpulse.min_cnt + uart->dev->highpulse.min_cnt) >> 1) + 12; + UART_MUTEX_UNLOCK(); + + return ret; +} + +/* + * To start detection of baud rate with the uart the auto_baud.en bit needs to be cleared and set. The bit period is + * detected calling uartBadrateDetect(). The raw baudrate is computed using the UART_CLK_FREQ. The raw baudrate is + * rounded to the closed real baudrate. +*/ +unsigned long +uartDetectBaudrate(uart_t *uart) +{ + static bool uartStateDetectingBaudrate = false; + + if(!uartStateDetectingBaudrate) { + uart->dev->auto_baud.glitch_filt = 0x08; + uart->dev->auto_baud.en = 0; + uart->dev->auto_baud.en = 1; + uartStateDetectingBaudrate = true; + } + + unsigned long divisor = uartBaudrateDetect(uart, true); + if (!divisor) { + return 0; + } + + uart->dev->auto_baud.en = 0; + uartStateDetectingBaudrate = false; // Initialize for the next round + + unsigned long baudrate = UART_CLK_FREQ / divisor; + + static const unsigned long default_rates[] = {300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 74880, 115200, 230400, 256000, 460800, 921600, 1843200, 3686400}; + + size_t i; + for (i = 1; i < sizeof(default_rates) / sizeof(default_rates[0]) - 1; i++) // find the nearest real baudrate + { + if (baudrate <= default_rates[i]) + { + if (baudrate - default_rates[i - 1] < default_rates[i] - baudrate) { + i--; + } + break; + } + } + + return default_rates[i]; +} diff --git a/cores/esp32/esp32-hal-uart.h b/cores/esp32/esp32-hal-uart.h index e3023a1c575..3a317324f68 100644 --- a/cores/esp32/esp32-hal-uart.h +++ b/cores/esp32/esp32-hal-uart.h @@ -72,6 +72,8 @@ size_t uartResizeRxBuffer(uart_t* uart, size_t new_size); void uartSetDebug(uart_t* uart); int uartGetDebug(); +unsigned long uartDetectBaudrate(uart_t *uart); + #ifdef __cplusplus } #endif From 9bf0054586685383750fde13bd69c710cd52af4e Mon Sep 17 00:00:00 2001 From: Jeroen88 Date: Sat, 13 Oct 2018 17:26:27 +0200 Subject: [PATCH 2/5] Solved compiler warning for uartResizeRxBuffer() --- cores/esp32/esp32-hal-uart.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c index 0d1e8d1c22b..1685430869b 100644 --- a/cores/esp32/esp32-hal-uart.c +++ b/cores/esp32/esp32-hal-uart.c @@ -242,7 +242,7 @@ void uartEnd(uart_t* uart) size_t uartResizeRxBuffer(uart_t * uart, size_t new_size) { if(uart == NULL) { - return; + return 0; } UART_MUTEX_LOCK(); From b14230bdc8d646d4392c31e3c8a2a0f3ef86f0bc Mon Sep 17 00:00:00 2001 From: Jeroen88 Date: Sat, 13 Oct 2018 23:03:16 +0200 Subject: [PATCH 3/5] Add unit to header variable name (timeout_ms) --- cores/esp32/HardwareSerial.cpp | 4 +- cores/esp32/HardwareSerial.h | 2 +- .../BasicHttpClient/BasicHttpClient.ino | 139 ++++++------- .../BasicHttpsClient/BasicHttpsClient.ino | 81 ++++++++ libraries/HTTPClient/src/HTTPClient.cpp | 187 +++++++++++++----- libraries/HTTPClient/src/HTTPClient.h | 20 +- 6 files changed, 303 insertions(+), 130 deletions(-) create mode 100644 libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino diff --git a/cores/esp32/HardwareSerial.cpp b/cores/esp32/HardwareSerial.cpp index 8bc9c61fe65..65cfac254dc 100644 --- a/cores/esp32/HardwareSerial.cpp +++ b/cores/esp32/HardwareSerial.cpp @@ -30,7 +30,7 @@ HardwareSerial Serial2(2); HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _uart(NULL) {} -void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout) +void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout_ms) { if(0 > _uart_nr || _uart_nr > 2) { log_e("Serial number is invalid, please use 0, 1 or 2"); @@ -57,7 +57,7 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in if(!baud) { time_t startMillis = millis(); unsigned long detectedBaudRate; - while(millis() - startMillis < timeout && !(detectedBaudRate = uartDetectBaudrate(_uart))) { + while(millis() - startMillis < timeout_ms && !(detectedBaudRate = uartDetectBaudrate(_uart))) { yield(); } diff --git a/cores/esp32/HardwareSerial.h b/cores/esp32/HardwareSerial.h index 540a21f5877..8e312c8da4d 100644 --- a/cores/esp32/HardwareSerial.h +++ b/cores/esp32/HardwareSerial.h @@ -55,7 +55,7 @@ class HardwareSerial: public Stream public: HardwareSerial(int uart_nr); - void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false, unsigned long timeout = 20000UL); + void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false, unsigned long timeout_ms = 20000UL); void end(); int available(void); int availableForWrite(void); diff --git a/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino index 9ee620ab5a5..21a97172efe 100644 --- a/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino +++ b/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino @@ -1,101 +1,76 @@ /** - * BasicHTTPClient.ino - * - * Created on: 24.05.2015 - * - */ + BasicHTTPClient.ino -#include + Created on: 24.05.2015 -#include -#include - -#include - -#define USE_SERIAL Serial - -WiFiMulti wifiMulti; - -/* -const char* ca = \ -"-----BEGIN CERTIFICATE-----\n" \ -"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ -"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ -"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ -"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ -"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ -"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ -"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ -"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ -"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ -"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ -"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ -"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ -"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ -"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ -"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ -"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ -"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ -"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ -"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ -"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ -"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ -"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ -"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ -"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ -"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ -"-----END CERTIFICATE-----\n"; */ +#include + +#include +#include + +#include + +#include + +ESP8266WiFiMulti WiFiMulti; + void setup() { - USE_SERIAL.begin(115200); + Serial.begin(115200); + // Serial.setDebugOutput(true); - USE_SERIAL.println(); - USE_SERIAL.println(); - USE_SERIAL.println(); + Serial.println(); + Serial.println(); + Serial.println(); - for(uint8_t t = 4; t > 0; t--) { - USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); - USE_SERIAL.flush(); - delay(1000); - } + for (uint8_t t = 4; t > 0; t--) { + Serial.printf("[SETUP] WAIT %d...\n", t); + Serial.flush(); + delay(1000); + } - wifiMulti.addAP("SSID", "PASSWORD"); + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); } void loop() { - // wait for WiFi connection - if((wifiMulti.run() == WL_CONNECTED)) { - - HTTPClient http; - - USE_SERIAL.print("[HTTP] begin...\n"); - // configure traged server and url - //http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS - http.begin("http://example.com/index.html"); //HTTP - - USE_SERIAL.print("[HTTP] GET...\n"); - // start connection and send HTTP header - int httpCode = http.GET(); - - // httpCode will be negative on error - if(httpCode > 0) { - // HTTP header has been send and Server response header has been handled - USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); - - // file found at server - if(httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - USE_SERIAL.println(payload); - } - } else { - USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + // wait for WiFi connection + if ((WiFiMulti.run() == WL_CONNECTED)) { + + WiFiClient client; + + HTTPClient http; + + Serial.print("[HTTP] begin...\n"); + if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP + + + Serial.print("[HTTP] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + Serial.printf("[HTTP] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + String payload = http.getString(); + Serial.println(payload); } + } else { + Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } - http.end(); + http.end(); + } else { + Serial.printf("[HTTP} Unable to connect\n"); } + } - delay(5000); + delay(10000); } diff --git a/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino new file mode 100644 index 00000000000..e0eb2879b26 --- /dev/null +++ b/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -0,0 +1,81 @@ +/** + BasicHTTPSClient.ino + + Created on: 20.08.2018 + +*/ + +#include + +#include +#include + +#include + +#include +// Fingerprint for demo URL, expires on June 2, 2019, needs to be updated well before this date +const uint8_t fingerprint[20] = {0x5A, 0xCF, 0xFE, 0xF0, 0xF1, 0xA6, 0xF4, 0x5F, 0xD2, 0x11, 0x11, 0xC6, 0x1D, 0x2F, 0x0E, 0xBC, 0x39, 0x8D, 0x50, 0xE0}; + +ESP8266WiFiMulti WiFiMulti; + +void setup() { + + Serial.begin(115200); + // Serial.setDebugOutput(true); + + Serial.println(); + Serial.println(); + Serial.println(); + + for (uint8_t t = 4; t > 0; t--) { + Serial.printf("[SETUP] WAIT %d...\n", t); + Serial.flush(); + delay(1000); + } + + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); +} + +void loop() { + // wait for WiFi connection + if ((WiFiMulti.run() == WL_CONNECTED)) { + + BearSSL::WiFiClientSecure *client = new BearSSL::WiFiClientSecure; + + client->setFingerprint(fingerprint); + + HTTPClient https; + + Serial.print("[HTTPS] begin...\n"); + if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS + + + Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = https.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + Serial.printf("[HTTPS] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + String payload = https.getString(); + Serial.println(payload); + } + } else { + Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); + } + + https.end(); + } else { + Serial.printf("[HTTPS] Unable to connect\n"); + } + + delete client; + } + + delay(10000); +} diff --git a/libraries/HTTPClient/src/HTTPClient.cpp b/libraries/HTTPClient/src/HTTPClient.cpp index e77c2445218..3948969e880 100644 --- a/libraries/HTTPClient/src/HTTPClient.cpp +++ b/libraries/HTTPClient/src/HTTPClient.cpp @@ -26,13 +26,18 @@ #include #include + +#ifdef HTTPCLIENT_1_0_COMPATIBLE #include #include +#endif + #include #include #include "HTTPClient.h" +#ifdef HTTPCLIENT_1_0_COMPATIBLE class TransportTraits { public: @@ -78,6 +83,7 @@ class TLSTraits : public TransportTraits const char* _clicert; const char* _clikey; }; +#endif // HTTPCLIENT_1_0_COMPATIBLE /** * constructor @@ -91,8 +97,8 @@ HTTPClient::HTTPClient() */ HTTPClient::~HTTPClient() { - if(_tcp) { - _tcp->stop(); + if(_client) { + _client->stop(); } if(_currentHeaders) { delete[] _currentHeaders; @@ -107,6 +113,61 @@ void HTTPClient::clear() } +/** + * parsing the url for all needed parameters + * @param client Client& + * @param url String + * @param https bool + * @return success bool + */ +bool HTTPClient::begin(WiFiClient &client, String url) { +// end(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + _client = &client; + + // check for : (http: or https:) + int index = url.indexOf(':'); + if(index < 0) { + log_d("failed to parse protocol\n"); + return false; + } + + String protocol = url.substring(0, index); + if(protocol != "http" && protocol != "https") { + log_d("unknown protocol '%s'\n", protocol.c_str()); + return false; + } + + _port = (protocol == "https" ? 443 : 80); + return beginInternal(url, protocol.c_str()); +} + + +/** + * directly supply all needed parameters + * @param client Client& + * @param host String + * @param port uint16_t + * @param uri String + * @param https bool + * @return success bool + */ +bool HTTPClient::begin(WiFiClient &client, String host, uint16_t port, String uri, bool https) +{ +// end(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + _client = &client; + + clear(); + _host = host; + _port = port; + _uri = uri; + _protocol = (https ? "https" : "http"); + return true; +} + + +#ifdef HTTPCLIENT_1_0_COMPATIBLE bool HTTPClient::begin(String url, const char* CAcert) { _transportTraits.reset(nullptr); @@ -134,6 +195,7 @@ bool HTTPClient::begin(String url) _transportTraits = TransportTraitsPtr(new TransportTraits()); return true; } +#endif // HTTPCLIENT_1_0_COMPATIBLE bool HTTPClient::beginInternal(String url, const char* expectedProtocol) { @@ -182,6 +244,7 @@ bool HTTPClient::beginInternal(String url, const char* expectedProtocol) return true; } +#ifdef HTTPCLIENT_1_0_COMPATIBLE bool HTTPClient::begin(String host, uint16_t port, String uri) { clear(); @@ -222,37 +285,64 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcer _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key)); return true; } +#endif // HTTPCLIENT_1_0_COMPATIBLE /** * end * called after the payload is handled */ void HTTPClient::end(void) +{ + disconnect(); +} + + + +/** + * disconnect + * close the TCP socket + */ +void HTTPClient::disconnect() { if(connected()) { - if(_tcp->available() > 0) { - log_d("still data in buffer (%d), clean up.", _tcp->available()); - _tcp->flush(); + if(_client) { + if(_client->available() > 0) { + log_d("still data in buffer (%d), clean up.\n", _client->available()); + while(_client->available() > 0) { + _client->read(); + } + } + } if(_reuse && _canReuse) { - log_d("tcp keep open for reuse"); + log_d("tcp keep open for reuse\n"); } else { - log_d("tcp stop"); - _tcp->stop(); + log_d("tcp stop\n"); + if(_client) { + _client->stop(); + _client = nullptr; + } +#ifdef HTTPCLIENT_1_0_COMPATIBLE + if(_tcpDeprecated) { + _transportTraits.reset(nullptr); + _tcpDeprecated.reset(nullptr); + } +#endif } } else { - log_v("tcp is closed"); + log_d("tcp is closed\n"); } } + /** * connected * @return connected status */ bool HTTPClient::connected() { - if(_tcp) { - return ((_tcp->available() > 0) || _tcp->connected()); + if(_client) { + return ((_client->available() > 0) || _client->connected()); } return false; } @@ -310,7 +400,7 @@ void HTTPClient::setTimeout(uint16_t timeout) { _tcpTimeout = timeout; if(connected() && !_secure) { - _tcp->setTimeout(timeout); + _client->setTimeout(timeout); } } @@ -398,7 +488,7 @@ int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) // send Payload if needed if(payload && size > 0) { - if(_tcp->write(&payload[0], size) != size) { + if(_client->write(&payload[0], size) != size) { return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } } @@ -477,7 +567,7 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) int bytesRead = stream->readBytes(buff, readBytes); // write it to Stream - int bytesWrite = _tcp->write((const uint8_t *) buff, bytesRead); + int bytesWrite = _client->write((const uint8_t *) buff, bytesRead); bytesWritten += bytesWrite; // are all Bytes a writen to stream ? @@ -485,11 +575,11 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite); // check for write error - if(_tcp->getWriteError()) { - log_d("stream write error %d", _tcp->getWriteError()); + if(_client->getWriteError()) { + log_d("stream write error %d", _client->getWriteError()); //reset write error for retry - _tcp->clearWriteError(); + _client->clearWriteError(); } // some time for the stream @@ -498,7 +588,7 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) int leftBytes = (readBytes - bytesWrite); // retry to send the missed bytes - bytesWrite = _tcp->write((const uint8_t *) (buff + bytesWrite), leftBytes); + bytesWrite = _client->write((const uint8_t *) (buff + bytesWrite), leftBytes); bytesWritten += bytesWrite; if(bytesWrite != leftBytes) { @@ -510,8 +600,8 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) } // check for write error - if(_tcp->getWriteError()) { - log_d("stream write error %d", _tcp->getWriteError()); + if(_client->getWriteError()) { + log_d("stream write error %d", _client->getWriteError()); free(buff); return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } @@ -562,7 +652,7 @@ int HTTPClient::getSize(void) WiFiClient& HTTPClient::getStream(void) { if (connected() && !_secure) { - return *_tcp; + return *_client; } log_w("getStream: not connected"); @@ -577,7 +667,7 @@ WiFiClient& HTTPClient::getStream(void) WiFiClient* HTTPClient::getStreamPtr(void) { if(connected()) { - return _tcp.get(); + return _client; } log_w("getStreamPtr: not connected"); @@ -617,7 +707,7 @@ int HTTPClient::writeToStream(Stream * stream) if(!connected()) { return returnError(HTTPC_ERROR_CONNECTION_LOST); } - String chunkHeader = _tcp->readStringUntil('\n'); + String chunkHeader = _client->readStringUntil('\n'); if(chunkHeader.length() <= 0) { return returnError(HTTPC_ERROR_READ_TIMEOUT); @@ -654,7 +744,7 @@ int HTTPClient::writeToStream(Stream * stream) // read trailing \r\n at the end of the chunk char buf[2]; - auto trailing_seq_len = _tcp->readBytes((uint8_t*)buf, 2); + auto trailing_seq_len = _client->readBytes((uint8_t*)buf, 2); if (trailing_seq_len != 2 || buf[0] != '\r' || buf[1] != '\n') { return returnError(HTTPC_ERROR_READ_TIMEOUT); } @@ -822,38 +912,47 @@ bool HTTPClient::connect(void) if(connected()) { log_d("already connected, try reuse!"); - while(_tcp->available() > 0) { - _tcp->read(); + while(_client->available() > 0) { + _client->read(); } return true; } - if (!_transportTraits) { +#ifdef HTTPCLIENT_1_0_COMPATIBLE + if(!_client) { + _tcpDeprecated = _transportTraits->create(); + _client = _tcpDeprecated.get(); + } +#endif + + if (!_client) { log_d("HTTPClient::begin was not called or returned error"); return false; } - _tcp = _transportTraits->create(); - - - if (!_transportTraits->verify(*_tcp, _host.c_str())) { - log_d("transport level verify failed"); - _tcp->stop(); - return false; - } + _client->setTimeout(_tcpTimeout); - if(!_tcp->connect(_host.c_str(), _port)) { + if(!_client->connect(_host.c_str(), _port)) { log_d("failed connect to %s:%u", _host.c_str(), _port); return false; } log_d(" connected to %s:%u", _host.c_str(), _port); +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if (_tcpDeprecated && !_transportTraits->verify(*_client, _host.c_str())) { + log_d("transport level verify failed"); + _client->stop(); + return false; + } +#endif + + // set Timeout for readBytesUntil and readStringUntil - setTimeout(_tcpTimeout); +// setTimeout(_tcpTimeout); /* #ifdef ESP8266 - _tcp->setNoDelay(true); + _client->setNoDelay(true); #endif */ return connected(); @@ -907,7 +1006,7 @@ bool HTTPClient::sendHeader(const char * type) header += _headers + "\r\n"; - return (_tcp->write((const uint8_t *) header.c_str(), header.length()) == header.length()); + return (_client->write((const uint8_t *) header.c_str(), header.length()) == header.length()); } /** @@ -928,9 +1027,9 @@ int HTTPClient::handleHeaderResponse() unsigned long lastDataTime = millis(); while(connected()) { - size_t len = _tcp->available(); + size_t len = _client->available(); if(len > 0) { - String headerLine = _tcp->readStringUntil('\n'); + String headerLine = _client->readStringUntil('\n'); headerLine.trim(); // remove \r lastDataTime = millis(); @@ -1026,7 +1125,7 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) while(connected() && (len > 0 || len == -1)) { // get available data size - size_t sizeAvailable = _tcp->available(); + size_t sizeAvailable = _client->available(); if(sizeAvailable) { @@ -1043,7 +1142,7 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) } // read data - int bytesRead = _tcp->readBytes(buff, readBytes); + int bytesRead = _client->readBytes(buff, readBytes); // write it to Stream int bytesWrite = stream->write(buff, bytesRead); @@ -1124,7 +1223,7 @@ int HTTPClient::returnError(int error) log_w("error(%d): %s", error, errorToString(error).c_str()); if(connected()) { log_d("tcp stop"); - _tcp->stop(); + _client->stop(); } } return error; diff --git a/libraries/HTTPClient/src/HTTPClient.h b/libraries/HTTPClient/src/HTTPClient.h index b1570e1dff2..55106421b49 100644 --- a/libraries/HTTPClient/src/HTTPClient.h +++ b/libraries/HTTPClient/src/HTTPClient.h @@ -27,6 +27,8 @@ #ifndef HTTPClient_H_ #define HTTPClient_H_ +#define HTTPCLIENT_1_0_COMPATIBLE + #include #include #include @@ -117,8 +119,10 @@ typedef enum { HTTPC_TE_CHUNKED } transferEncoding_t; +#ifdef HTTPCLIENT_1_0_COMPATIBLE class TransportTraits; typedef std::unique_ptr TransportTraitsPtr; +#endif class HTTPClient { @@ -126,11 +130,20 @@ class HTTPClient HTTPClient(); ~HTTPClient(); +/* + * Since both begin() functions take a reference to client as a parameter, you need to + * ensure the client object lives the entire time of the HTTPClient + */ + bool begin(WiFiClient &client, String url); + bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false); + +#ifdef HTTPCLIENT_1_0_COMPATIBLE bool begin(String url); bool begin(String url, const char* CAcert); bool begin(String host, uint16_t port, String uri = "/"); bool begin(String host, uint16_t port, String uri, const char* CAcert); bool begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key); +#endif void end(void); @@ -181,6 +194,7 @@ class HTTPClient }; bool beginInternal(String url, const char* expectedProtocol); + void disconnect(); void clear(); int returnError(int error); bool connect(void); @@ -189,8 +203,12 @@ class HTTPClient int writeToStreamDataBlock(Stream * stream, int len); +#ifdef HTTPCLIENT_1_0_COMPATIBLE TransportTraitsPtr _transportTraits; - std::unique_ptr _tcp; + std::unique_ptr _tcpDeprecated; +#endif + + WiFiClient* _client; /// request handling String _host; From 50fdf60d56c143566fa05e61d78d350564557266 Mon Sep 17 00:00:00 2001 From: Jeroen88 Date: Sun, 14 Oct 2018 09:53:52 +0200 Subject: [PATCH 4/5] Reverting accidentally changed files to master --- .../BasicHttpClient/BasicHttpClient.ino | 139 +++++++------ .../BasicHttpsClient/BasicHttpsClient.ino | 81 -------- libraries/HTTPClient/src/HTTPClient.cpp | 187 +++++------------- libraries/HTTPClient/src/HTTPClient.h | 20 +- 4 files changed, 127 insertions(+), 300 deletions(-) delete mode 100644 libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino diff --git a/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino index 21a97172efe..9ee620ab5a5 100644 --- a/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino +++ b/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino @@ -1,76 +1,101 @@ /** - BasicHTTPClient.ino - - Created on: 24.05.2015 - -*/ + * BasicHTTPClient.ino + * + * Created on: 24.05.2015 + * + */ #include -#include -#include - -#include - -#include - -ESP8266WiFiMulti WiFiMulti; +#include +#include + +#include + +#define USE_SERIAL Serial + +WiFiMulti wifiMulti; + +/* +const char* ca = \ +"-----BEGIN CERTIFICATE-----\n" \ +"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ +"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ +"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ +"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ +"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ +"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ +"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ +"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ +"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ +"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ +"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ +"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ +"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ +"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ +"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ +"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ +"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ +"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ +"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ +"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ +"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ +"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ +"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ +"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ +"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ +"-----END CERTIFICATE-----\n"; +*/ void setup() { - Serial.begin(115200); - // Serial.setDebugOutput(true); + USE_SERIAL.begin(115200); - Serial.println(); - Serial.println(); - Serial.println(); + USE_SERIAL.println(); + USE_SERIAL.println(); + USE_SERIAL.println(); - for (uint8_t t = 4; t > 0; t--) { - Serial.printf("[SETUP] WAIT %d...\n", t); - Serial.flush(); - delay(1000); - } + for(uint8_t t = 4; t > 0; t--) { + USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); + USE_SERIAL.flush(); + delay(1000); + } - WiFi.mode(WIFI_STA); - WiFiMulti.addAP("SSID", "PASSWORD"); + wifiMulti.addAP("SSID", "PASSWORD"); } void loop() { - // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - - WiFiClient client; - - HTTPClient http; - - Serial.print("[HTTP] begin...\n"); - if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP - - - Serial.print("[HTTP] GET...\n"); - // start connection and send HTTP header - int httpCode = http.GET(); - - // httpCode will be negative on error - if (httpCode > 0) { - // HTTP header has been send and Server response header has been handled - Serial.printf("[HTTP] GET... code: %d\n", httpCode); - - // file found at server - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { - String payload = http.getString(); - Serial.println(payload); + // wait for WiFi connection + if((wifiMulti.run() == WL_CONNECTED)) { + + HTTPClient http; + + USE_SERIAL.print("[HTTP] begin...\n"); + // configure traged server and url + //http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS + http.begin("http://example.com/index.html"); //HTTP + + USE_SERIAL.print("[HTTP] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if(httpCode > 0) { + // HTTP header has been send and Server response header has been handled + USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); + + // file found at server + if(httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + USE_SERIAL.println(payload); + } + } else { + USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } - } else { - Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - http.end(); - } else { - Serial.printf("[HTTP} Unable to connect\n"); + http.end(); } - } - delay(10000); + delay(5000); } diff --git a/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino deleted file mode 100644 index e0eb2879b26..00000000000 --- a/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino +++ /dev/null @@ -1,81 +0,0 @@ -/** - BasicHTTPSClient.ino - - Created on: 20.08.2018 - -*/ - -#include - -#include -#include - -#include - -#include -// Fingerprint for demo URL, expires on June 2, 2019, needs to be updated well before this date -const uint8_t fingerprint[20] = {0x5A, 0xCF, 0xFE, 0xF0, 0xF1, 0xA6, 0xF4, 0x5F, 0xD2, 0x11, 0x11, 0xC6, 0x1D, 0x2F, 0x0E, 0xBC, 0x39, 0x8D, 0x50, 0xE0}; - -ESP8266WiFiMulti WiFiMulti; - -void setup() { - - Serial.begin(115200); - // Serial.setDebugOutput(true); - - Serial.println(); - Serial.println(); - Serial.println(); - - for (uint8_t t = 4; t > 0; t--) { - Serial.printf("[SETUP] WAIT %d...\n", t); - Serial.flush(); - delay(1000); - } - - WiFi.mode(WIFI_STA); - WiFiMulti.addAP("SSID", "PASSWORD"); -} - -void loop() { - // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - - BearSSL::WiFiClientSecure *client = new BearSSL::WiFiClientSecure; - - client->setFingerprint(fingerprint); - - HTTPClient https; - - Serial.print("[HTTPS] begin...\n"); - if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS - - - Serial.print("[HTTPS] GET...\n"); - // start connection and send HTTP header - int httpCode = https.GET(); - - // httpCode will be negative on error - if (httpCode > 0) { - // HTTP header has been send and Server response header has been handled - Serial.printf("[HTTPS] GET... code: %d\n", httpCode); - - // file found at server - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { - String payload = https.getString(); - Serial.println(payload); - } - } else { - Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); - } - - https.end(); - } else { - Serial.printf("[HTTPS] Unable to connect\n"); - } - - delete client; - } - - delay(10000); -} diff --git a/libraries/HTTPClient/src/HTTPClient.cpp b/libraries/HTTPClient/src/HTTPClient.cpp index 3948969e880..e77c2445218 100644 --- a/libraries/HTTPClient/src/HTTPClient.cpp +++ b/libraries/HTTPClient/src/HTTPClient.cpp @@ -26,18 +26,13 @@ #include #include - -#ifdef HTTPCLIENT_1_0_COMPATIBLE #include #include -#endif - #include #include #include "HTTPClient.h" -#ifdef HTTPCLIENT_1_0_COMPATIBLE class TransportTraits { public: @@ -83,7 +78,6 @@ class TLSTraits : public TransportTraits const char* _clicert; const char* _clikey; }; -#endif // HTTPCLIENT_1_0_COMPATIBLE /** * constructor @@ -97,8 +91,8 @@ HTTPClient::HTTPClient() */ HTTPClient::~HTTPClient() { - if(_client) { - _client->stop(); + if(_tcp) { + _tcp->stop(); } if(_currentHeaders) { delete[] _currentHeaders; @@ -113,61 +107,6 @@ void HTTPClient::clear() } -/** - * parsing the url for all needed parameters - * @param client Client& - * @param url String - * @param https bool - * @return success bool - */ -bool HTTPClient::begin(WiFiClient &client, String url) { -// end(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - - _client = &client; - - // check for : (http: or https:) - int index = url.indexOf(':'); - if(index < 0) { - log_d("failed to parse protocol\n"); - return false; - } - - String protocol = url.substring(0, index); - if(protocol != "http" && protocol != "https") { - log_d("unknown protocol '%s'\n", protocol.c_str()); - return false; - } - - _port = (protocol == "https" ? 443 : 80); - return beginInternal(url, protocol.c_str()); -} - - -/** - * directly supply all needed parameters - * @param client Client& - * @param host String - * @param port uint16_t - * @param uri String - * @param https bool - * @return success bool - */ -bool HTTPClient::begin(WiFiClient &client, String host, uint16_t port, String uri, bool https) -{ -// end(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - - _client = &client; - - clear(); - _host = host; - _port = port; - _uri = uri; - _protocol = (https ? "https" : "http"); - return true; -} - - -#ifdef HTTPCLIENT_1_0_COMPATIBLE bool HTTPClient::begin(String url, const char* CAcert) { _transportTraits.reset(nullptr); @@ -195,7 +134,6 @@ bool HTTPClient::begin(String url) _transportTraits = TransportTraitsPtr(new TransportTraits()); return true; } -#endif // HTTPCLIENT_1_0_COMPATIBLE bool HTTPClient::beginInternal(String url, const char* expectedProtocol) { @@ -244,7 +182,6 @@ bool HTTPClient::beginInternal(String url, const char* expectedProtocol) return true; } -#ifdef HTTPCLIENT_1_0_COMPATIBLE bool HTTPClient::begin(String host, uint16_t port, String uri) { clear(); @@ -285,64 +222,37 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcer _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key)); return true; } -#endif // HTTPCLIENT_1_0_COMPATIBLE /** * end * called after the payload is handled */ void HTTPClient::end(void) -{ - disconnect(); -} - - - -/** - * disconnect - * close the TCP socket - */ -void HTTPClient::disconnect() { if(connected()) { - if(_client) { - if(_client->available() > 0) { - log_d("still data in buffer (%d), clean up.\n", _client->available()); - while(_client->available() > 0) { - _client->read(); - } - } - + if(_tcp->available() > 0) { + log_d("still data in buffer (%d), clean up.", _tcp->available()); + _tcp->flush(); } if(_reuse && _canReuse) { - log_d("tcp keep open for reuse\n"); + log_d("tcp keep open for reuse"); } else { - log_d("tcp stop\n"); - if(_client) { - _client->stop(); - _client = nullptr; - } -#ifdef HTTPCLIENT_1_0_COMPATIBLE - if(_tcpDeprecated) { - _transportTraits.reset(nullptr); - _tcpDeprecated.reset(nullptr); - } -#endif + log_d("tcp stop"); + _tcp->stop(); } } else { - log_d("tcp is closed\n"); + log_v("tcp is closed"); } } - /** * connected * @return connected status */ bool HTTPClient::connected() { - if(_client) { - return ((_client->available() > 0) || _client->connected()); + if(_tcp) { + return ((_tcp->available() > 0) || _tcp->connected()); } return false; } @@ -400,7 +310,7 @@ void HTTPClient::setTimeout(uint16_t timeout) { _tcpTimeout = timeout; if(connected() && !_secure) { - _client->setTimeout(timeout); + _tcp->setTimeout(timeout); } } @@ -488,7 +398,7 @@ int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) // send Payload if needed if(payload && size > 0) { - if(_client->write(&payload[0], size) != size) { + if(_tcp->write(&payload[0], size) != size) { return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } } @@ -567,7 +477,7 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) int bytesRead = stream->readBytes(buff, readBytes); // write it to Stream - int bytesWrite = _client->write((const uint8_t *) buff, bytesRead); + int bytesWrite = _tcp->write((const uint8_t *) buff, bytesRead); bytesWritten += bytesWrite; // are all Bytes a writen to stream ? @@ -575,11 +485,11 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite); // check for write error - if(_client->getWriteError()) { - log_d("stream write error %d", _client->getWriteError()); + if(_tcp->getWriteError()) { + log_d("stream write error %d", _tcp->getWriteError()); //reset write error for retry - _client->clearWriteError(); + _tcp->clearWriteError(); } // some time for the stream @@ -588,7 +498,7 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) int leftBytes = (readBytes - bytesWrite); // retry to send the missed bytes - bytesWrite = _client->write((const uint8_t *) (buff + bytesWrite), leftBytes); + bytesWrite = _tcp->write((const uint8_t *) (buff + bytesWrite), leftBytes); bytesWritten += bytesWrite; if(bytesWrite != leftBytes) { @@ -600,8 +510,8 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) } // check for write error - if(_client->getWriteError()) { - log_d("stream write error %d", _client->getWriteError()); + if(_tcp->getWriteError()) { + log_d("stream write error %d", _tcp->getWriteError()); free(buff); return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } @@ -652,7 +562,7 @@ int HTTPClient::getSize(void) WiFiClient& HTTPClient::getStream(void) { if (connected() && !_secure) { - return *_client; + return *_tcp; } log_w("getStream: not connected"); @@ -667,7 +577,7 @@ WiFiClient& HTTPClient::getStream(void) WiFiClient* HTTPClient::getStreamPtr(void) { if(connected()) { - return _client; + return _tcp.get(); } log_w("getStreamPtr: not connected"); @@ -707,7 +617,7 @@ int HTTPClient::writeToStream(Stream * stream) if(!connected()) { return returnError(HTTPC_ERROR_CONNECTION_LOST); } - String chunkHeader = _client->readStringUntil('\n'); + String chunkHeader = _tcp->readStringUntil('\n'); if(chunkHeader.length() <= 0) { return returnError(HTTPC_ERROR_READ_TIMEOUT); @@ -744,7 +654,7 @@ int HTTPClient::writeToStream(Stream * stream) // read trailing \r\n at the end of the chunk char buf[2]; - auto trailing_seq_len = _client->readBytes((uint8_t*)buf, 2); + auto trailing_seq_len = _tcp->readBytes((uint8_t*)buf, 2); if (trailing_seq_len != 2 || buf[0] != '\r' || buf[1] != '\n') { return returnError(HTTPC_ERROR_READ_TIMEOUT); } @@ -912,47 +822,38 @@ bool HTTPClient::connect(void) if(connected()) { log_d("already connected, try reuse!"); - while(_client->available() > 0) { - _client->read(); + while(_tcp->available() > 0) { + _tcp->read(); } return true; } -#ifdef HTTPCLIENT_1_0_COMPATIBLE - if(!_client) { - _tcpDeprecated = _transportTraits->create(); - _client = _tcpDeprecated.get(); - } -#endif - - if (!_client) { + if (!_transportTraits) { log_d("HTTPClient::begin was not called or returned error"); return false; } - _client->setTimeout(_tcpTimeout); + _tcp = _transportTraits->create(); + + + if (!_transportTraits->verify(*_tcp, _host.c_str())) { + log_d("transport level verify failed"); + _tcp->stop(); + return false; + } - if(!_client->connect(_host.c_str(), _port)) { + if(!_tcp->connect(_host.c_str(), _port)) { log_d("failed connect to %s:%u", _host.c_str(), _port); return false; } log_d(" connected to %s:%u", _host.c_str(), _port); -#ifdef HTTPCLIENT_1_1_COMPATIBLE - if (_tcpDeprecated && !_transportTraits->verify(*_client, _host.c_str())) { - log_d("transport level verify failed"); - _client->stop(); - return false; - } -#endif - - // set Timeout for readBytesUntil and readStringUntil -// setTimeout(_tcpTimeout); + setTimeout(_tcpTimeout); /* #ifdef ESP8266 - _client->setNoDelay(true); + _tcp->setNoDelay(true); #endif */ return connected(); @@ -1006,7 +907,7 @@ bool HTTPClient::sendHeader(const char * type) header += _headers + "\r\n"; - return (_client->write((const uint8_t *) header.c_str(), header.length()) == header.length()); + return (_tcp->write((const uint8_t *) header.c_str(), header.length()) == header.length()); } /** @@ -1027,9 +928,9 @@ int HTTPClient::handleHeaderResponse() unsigned long lastDataTime = millis(); while(connected()) { - size_t len = _client->available(); + size_t len = _tcp->available(); if(len > 0) { - String headerLine = _client->readStringUntil('\n'); + String headerLine = _tcp->readStringUntil('\n'); headerLine.trim(); // remove \r lastDataTime = millis(); @@ -1125,7 +1026,7 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) while(connected() && (len > 0 || len == -1)) { // get available data size - size_t sizeAvailable = _client->available(); + size_t sizeAvailable = _tcp->available(); if(sizeAvailable) { @@ -1142,7 +1043,7 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) } // read data - int bytesRead = _client->readBytes(buff, readBytes); + int bytesRead = _tcp->readBytes(buff, readBytes); // write it to Stream int bytesWrite = stream->write(buff, bytesRead); @@ -1223,7 +1124,7 @@ int HTTPClient::returnError(int error) log_w("error(%d): %s", error, errorToString(error).c_str()); if(connected()) { log_d("tcp stop"); - _client->stop(); + _tcp->stop(); } } return error; diff --git a/libraries/HTTPClient/src/HTTPClient.h b/libraries/HTTPClient/src/HTTPClient.h index 55106421b49..b1570e1dff2 100644 --- a/libraries/HTTPClient/src/HTTPClient.h +++ b/libraries/HTTPClient/src/HTTPClient.h @@ -27,8 +27,6 @@ #ifndef HTTPClient_H_ #define HTTPClient_H_ -#define HTTPCLIENT_1_0_COMPATIBLE - #include #include #include @@ -119,10 +117,8 @@ typedef enum { HTTPC_TE_CHUNKED } transferEncoding_t; -#ifdef HTTPCLIENT_1_0_COMPATIBLE class TransportTraits; typedef std::unique_ptr TransportTraitsPtr; -#endif class HTTPClient { @@ -130,20 +126,11 @@ class HTTPClient HTTPClient(); ~HTTPClient(); -/* - * Since both begin() functions take a reference to client as a parameter, you need to - * ensure the client object lives the entire time of the HTTPClient - */ - bool begin(WiFiClient &client, String url); - bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false); - -#ifdef HTTPCLIENT_1_0_COMPATIBLE bool begin(String url); bool begin(String url, const char* CAcert); bool begin(String host, uint16_t port, String uri = "/"); bool begin(String host, uint16_t port, String uri, const char* CAcert); bool begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key); -#endif void end(void); @@ -194,7 +181,6 @@ class HTTPClient }; bool beginInternal(String url, const char* expectedProtocol); - void disconnect(); void clear(); int returnError(int error); bool connect(void); @@ -203,12 +189,8 @@ class HTTPClient int writeToStreamDataBlock(Stream * stream, int len); -#ifdef HTTPCLIENT_1_0_COMPATIBLE TransportTraitsPtr _transportTraits; - std::unique_ptr _tcpDeprecated; -#endif - - WiFiClient* _client; + std::unique_ptr _tcp; /// request handling String _host; From 8f5f251016e70b3ac982528b88b0cdb410299427 Mon Sep 17 00:00:00 2001 From: Jeroen88 Date: Sun, 14 Oct 2018 23:23:44 +0200 Subject: [PATCH 5/5] Add small delay after baudrate detection --- cores/esp32/HardwareSerial.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cores/esp32/HardwareSerial.cpp b/cores/esp32/HardwareSerial.cpp index 65cfac254dc..0ad44258451 100644 --- a/cores/esp32/HardwareSerial.cpp +++ b/cores/esp32/HardwareSerial.cpp @@ -64,6 +64,7 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in end(); if(detectedBaudRate) { + delay(100); // Give some time... _uart = uartBegin(_uart_nr, detectedBaudRate, config, rxPin, txPin, 256, invert); } else { log_e("Could not detect baudrate. Serial data at the port must be present within the timeout for detection to be possible");