Compare commits

..
10 Commits
24 changed files with 548 additions and 2750 deletions
+8 -31
View File
@@ -45,11 +45,6 @@ Chunked responses are recognized and handled transparently.
---
---
### Releases v1.0.1
1. Restore cpp code besides Impl.h code to use in case of `multiple definition` linker error. Thanks to [Daniel Brunner](https://github.com/0xFEEDC0DE64) to report and make PR in [**Fixed linker errors when included in multiple .cpp files**](https://github.com/khoih-prog/AsyncHTTPRequest_Generic/pull/1). See [**HOWTO Fix `Multiple Definitions` Linker Error**](https://github.com/khoih-prog/AsyncHTTPRequest_Generic#HOWTO-Fix-Multiple-Definitions-Linker-Error)
### Releases v1.0.0
1. Initial coding to add support to **STM32F/L/H/G/WB/MP1** using built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc).
@@ -217,19 +212,6 @@ theses files must be copied into the corresponding directory:
---
---
### HOWTO Fix `Multiple Definitions` Linker Error
The current library implementation, using xyz-Impl.h instead of standard xyz.cpp, possibly creates certain `Multiple Definitions` Linker error in certain use cases. Although it's simple to just modify several lines of code, either in the library or in the application, the library is adding a separate source directory, named src_cpp, besides the standard src directory.
To use the old standard cpp way, just
1. **Rename the h-only src directory into src_h.**
2. **Then rename the cpp src_cpp directory into src.**
3. Close then reopen the application code in Arduino IDE, etc. to recompile from scratch.
---
---
### Examples
Also see examples:
@@ -460,7 +442,7 @@ AsyncHTTPRequest @ IP : 192.168.2.72
**************************************
abbreviation: EDT
client_ip: aaa.bbb.ccc.ddd
client_ip: 216.154.52.212
datetime: 2020-09-13T18:22:59.555816-04:00
day_of_week: 0
day_of_year: 257
@@ -477,7 +459,7 @@ week_number: 37
**************************************
abbreviation: EDT
client_ip: aaa.bbb.ccc.ddd
client_ip: 216.154.52.212
datetime: 2020-09-13T18:27:57.586325-04:00
day_of_week: 0
day_of_year: 257
@@ -507,7 +489,7 @@ After waiting 3.43 secs more in setup(), connection result is connected. Local I
H
**************************************
abbreviation: EDT
client_ip: aaa.bbb.ccc.ddd
client_ip: 216.154.52.212
datetime: 2020-09-13T19:35:37.951609-04:00
day_of_week: 0
day_of_year: 257
@@ -539,7 +521,7 @@ After waiting 2.35 secs more in setup(), connection result is connected. Local I
H
**************************************
abbreviation: EDT
client_ip: aaa.bbb.ccc.ddd
client_ip: 216.154.52.212
datetime: 2020-09-13T19:37:02.118166-04:00
day_of_week: 0
day_of_year: 257
@@ -557,7 +539,7 @@ week_number: 37
HHHHHHHHH HHHHHHHHHH HHHHHHHHHH H
**************************************
abbreviation: EDT
client_ip: aaa.bbb.ccc.ddd
client_ip: 216.154.52.212
datetime: 2020-09-13T19:42:01.507586-04:00
day_of_week: 0
day_of_year: 257
@@ -588,7 +570,7 @@ HTTP WebServer is @ IP : 192.168.2.81
**************************************
abbreviation: EDT
client_ip: aaa.bbb.ccc.ddd
client_ip: 216.154.52.212
datetime: 2020-09-13T19:56:28.295033-04:00
day_of_week: 0
day_of_year: 257
@@ -708,10 +690,6 @@ Submit issues to: [AsyncHTTPRequest_Generic issues](https://github.com/khoih-pro
---
---
### Releases v1.0.1
1. Restore cpp code besides Impl.h code to use in case of `multiple definition` linker error. Thanks to [Daniel Brunner](https://github.com/0xFEEDC0DE64) to report and make PR in [**Fixed linker errors when included in multiple .cpp files**](https://github.com/khoih-prog/AsyncHTTPRequest_Generic/pull/1). See [**HOWTO Fix `Multiple Definitions` Linker Error**](https://github.com/khoih-prog/AsyncHTTPRequest_Generic#HOWTO-Fix-Multiple-Definitions-Linker-Error)
### Releases v1.0.0
1. Initial coding to add support to **STM32F/L/H/G/WB/MP1** using built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc).
@@ -724,14 +702,13 @@ Submit issues to: [AsyncHTTPRequest_Generic issues](https://github.com/khoih-pro
This library is based on, modified, bug-fixed and improved from:
1. [Bob Lemaire's **asyncHTTPrequest Library**](https://github.com/boblemaire/asyncHTTPrequest) to use the better **asynchronous** features of these following Async TCP Libraries : ( [`ESPAsyncTCP`](https://github.com/me-no-dev/ESPAsyncTCP), [`AsyncTCP`](https://github.com/me-no-dev/AsyncTCP), and [`STM32AsyncTCP`](https://github.com/philbowles/STM32AsyncTCP) ).
1. [Bob Lemaire's asyncHTTPrequest Library](https://github.com/boblemaire/asyncHTTPrequest)
2. Thanks to [Daniel Brunner](https://github.com/0xFEEDC0DE64) to report and make PR in [Fixed linker errors when included in multiple .cpp files](https://github.com/khoih-prog/AsyncHTTPRequest_Generic/pull/1) leading to v1.0.1. See [**HOWTO Fix `Multiple Definitions` Linker Error**](https://github.com/khoih-prog/AsyncHTTPRequest_Generic#HOWTO-Fix-Multiple-Definitions-Linker-Error)
to use the better **asynchronous** features of these following Async TCP Libraries : ( [`ESPAsyncTCP`](https://github.com/me-no-dev/ESPAsyncTCP), [`AsyncTCP`](https://github.com/me-no-dev/AsyncTCP), and [`STM32AsyncTCP`](https://github.com/philbowles/STM32AsyncTCP) ).
<table>
<tr>
<td align="center"><a href="https://github.com/boblemaire"><img src="https://github.com/boblemaire.png" width="100px;" alt="boblemaire"/><br /><sub><b>⭐️ Bob Lemaire</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/0xFEEDC0DE64"><img src="https://github.com/0xFEEDC0DE64.png" width="100px;" alt="0xFEEDC0DE64"/><br /><sub><b>Daniel Brunner</b></sub></a><br /></td>
</tr>
</table>
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#include "defines.h"
+1 -2
View File
@@ -19,12 +19,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
/*
Currently support
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
/**
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
// Dweet.io POST client. Connects to dweet.io once every ten seconds, sends a POST request and a request body.
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
//************************************************************************************************************
//
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
//************************************************************************************************************
//
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
//************************************************************************************************************
//
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#include "defines.h"
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#include "defines.h"
+6 -14
View File
@@ -1,8 +1,8 @@
{
"name":"AsyncHTTPRequest_Generic",
"version": "1.0.1",
"description":"Simple Async HTTP Request library, supporting GET and POST, on top of AsyncTCP libraries, such as AsyncTCP, ESPAsyncTCP, AsyncTCP_STM32, etc.. for ESP32, ESP8266 and currently STM32 with built-in LAN8742A Ethernet.",
"keywords":"async,tcp,http,ESP8266,ESP32,ESPAsyncTCP,AsyncTCP,stm32,ethernet,wifi,lan8742a",
"version": "1.0.0",
"description":"Simple Async HTTP Request library, supporting GET and POST, on top of AsyncTCP libraries, such as AsyncTCP, ESPAsyncTCP, etc... for ESP32, ESP8266.",
"keywords":"async,tcp,http,ESP8266,ESP32,ESPAsyncTCP,AsyncTCP,ethernet,wifi,lan8742a",
"authors": [
{
"name": "Bob Lemaire",
@@ -13,7 +13,7 @@
"url": "https://github.com/khoih-prog",
"email": "khoih.prog@gmail.com",
"maintainer": true
}
}
],
"repository":
{
@@ -37,16 +37,8 @@
"platforms": ["espressif8266", "espressif32"]
},
{
"name": "STM32duino LwIP",
"platforms": "ststm32"
},
{
"name": "STM32duino STM32Ethernet",
"platforms": "ststm32"
},
{
"name": "STM32 AsyncTCP",
"platforms": "ststm32"
"name": "https://github.com/0xFEEDC0DE64/optional.git",
"platforms": ["espressif8266", "espressif32"]
}
]
}
+4 -4
View File
@@ -1,12 +1,12 @@
name=AsyncHTTPRequest_Generic
version=1.0.1
version=1.0.0
author=Bob Lemaire,Khoi Hoang
maintainer=Khoi Hoang <khoih.prog@gmail.com>
license=MIT
sentence=Simple Async HTTP Request library, supporting GET and POST, on top of AsyncTCP libraries, such as AsyncTCP, ESPAsyncTCP, AsyncTCP_STM32, etc.. for ESP32, ESP8266 and currently STM32 with built-in LAN8742A Ethernet.
paragraph=This AsyncHTTPRequest_Generic Library, supporting GET and POST, for ESP32, ESP8266 and STM32 with built-in LAN8742A Ethernet, such as Nucleo-144 F767ZI, etc.
sentence=Simple Async HTTP Request library, supporting GET and POST, on top of AsyncTCP libraries, such as AsyncTCP, ESPAsyncTCP, etc.. for ESP32, ESP8266
paragraph=This AsyncHTTPRequest_Generic Library, supporting GET and POST, for ESP32, ESP8266.
category=Communication,AsyncTCP,AsyncHTTP
url=https://github.com/khoih-prog/AsyncHTTPRequest_Generic
architectures=*
depends=AsyncTCP,ESP AsyncTCP,ESPAsync_WiFiManager,STM32duino LwIP,STM32duino STM32Ethernet,STM32 AsyncTCP
depends=AsyncTCP,ESP AsyncTCP,ESPAsync_WiFiManager
includes=AsyncHTTPRequest_Generic.h
+3 -123
View File
@@ -15,13 +15,11 @@
; ESP32
; SAMD
; NRF52
; STM32
; ============================================================
;default_envs = ESP8266
default_envs = ESP32
;default_envs = SAMD
;default_envs = NRF52
;default_envs = STM32
[env]
; ============================================================
@@ -33,22 +31,16 @@ upload_speed = 921600
;monitor_speed = 9600
;monitor_port = COM11
lib_deps =
lib_deps =
; PlatformIO 4.x
AsyncTCP@~1.1.1
ESPAsyncTCP@~1.2.2
STM32AsyncTCP@~1.0.0
STM32duino LwIP@~2.1.2
STM32duino STM32Ethernet@~1.2.0
ESPAsync_WiFiManager@~1.1.2
; PlatformIO 5.x
; PlatformIO 5.x
; me-no-dev/AsyncTCP@~1.1.1
; me-no-dev/ESPAsyncTCP@~1.2.2
; philbowles/STM32AsyncTCP@~1.0.0
; stm32duino/STM32duino LwIP@~2.1.2
; stm32duino/STM32duino STM32Ethernet@~1.2.0
; khoih-prog/ESPAsync_WiFiManager@~1.1.2
build_flags =
; set your debug output (default=Serial)
; -D DEBUG_ESP_PORT=Serial
@@ -234,115 +226,3 @@ board = feather52840
;board = mdbt50qrx
;board = ninab302
;board = ninab112
[env:STM32]
platform = ststm32
framework = arduino
; ============================================================
; Choose your board by uncommenting one of the following lines
; ============================================================
; ============================================================
; Board configuration Nucleo-144
; ============================================================
;board = nucleo_f207zg
;board = nucleo_f429zi
;board = nucleo_f746zg
;board = nucleo_f756zg
;board = nucleo_f767zi
;board = nucleo_h743zi
;board = nucleo_l496zg
;board = nucleo_l496zg-p
;board = nucleo_l4r5zi
;board = nucleo_l4r5zi-p
; ============================================================
; Board configuration Nucleo-64
; ============================================================
;board = nucleo_f030r8
;board = nucleo_f072rb
;board = nucleo_f091rc
;board = nucleo_f103rb
;board = nucleo_f302r8
;board = nucleo_f303re
;board = nucleo_f401re
;board = nucleo_f411re
;board = nucleo_f446re
;board = nucleo_g071rb
;board = nucleo_g431rb
;board = nucleo_g474re
;board = nucleo_l053r8
;board = nucleo_l073rz
;board = nucleo_l152re
;board = nucleo_l433rc_p
;board = nucleo_l452re
;board = nucleo_l452re-p
;board = nucleo_l476rg
;board = pnucleo_wb55rg
; ============================================================
; Board configuration Nucleo-32
; ============================================================
;board = nucleo_f031k6
;board = nucleo_l031k6
;board = nucleo_l412kb
;board = nucleo_l432lc
;board = nucleo_f303k8
;board = nucleo_g431kb
; ============================================================
; Board configuration Discovery Boards
; ============================================================
;board = disco_f030r8
;board = disco_f072rb
;board = disco_f030r8
;board = disco_f100rb
;board = disco_f407vg
;board = disco_f413zh
;board = disco_f746ng
;board = disco_g0316
;board = disco_l475vg_iot
;board = disco_f072cz-lrwan1
; ============================================================
; Board configuration STM32MP1 Boards
; ============================================================
;board = stm32mp157a-dk1
;board = stm32mp157c-dk2
; ============================================================
; Board configuration Generic Boards
; ============================================================
;board = bluepill_f103c6
;board = bluepill_f103c8
;board = blackpill_f103c8
;board = stm32f103cx
;board = stm32f103rx
;board = stm32f103tx
;board = stm32f103vx
;board = stm32f103zx
;board = stm32f103zet6
;board = maplemini_f103cb
;board = blackpill_f303cc
;board = black_f407ve
;board = black_f407vg
;board = black_f407ze
;board = black_f407zg
;board = blue_f407ve_mini
;board = blackpill_f401cc
;board = blackpill_f411ce
;board = coreboard_f401rc
;board = feather_f405
; ============================================================
; Board configuration Many more Boards to be filled
; ============================================================
@@ -1,5 +1,5 @@
/****************************************************************************************************************************
AsyncHTTPRequest_Impl_Generic.h - Dead simple AsyncHTTPRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet
AsyncHTTPRequest.cpp - 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)
@@ -17,41 +17,103 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#pragma once
#include "AsyncHTTPRequest.h"
//**************************************************************************************************************
AsyncHTTPRequest::AsyncHTTPRequest(): _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)
, _request(nullptr), _response(nullptr), _chunks(nullptr), _headers(nullptr)
namespace {
#if ESP32
class LockHelper
{
#ifdef ESP32
threadLock = xSemaphoreCreateRecursiveMutex();
public:
LockHelper(QueueHandle_t _xMutex) :
xMutex{_xMutex}
{
xSemaphoreTakeRecursive(xMutex, portMAX_DELAY);
}
~LockHelper()
{
xSemaphoreGiveRecursive(xMutex);
}
private:
const QueueHandle_t xMutex;
};
#define _lock LockHelper lock{this->threadLock}
#define _unlock
#elif ESP8266
#define _lock
#define _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) || \
defined(STM32WB) || defined(STM32MP1) )
#define _lock
#define _unlock
#endif
}
std::optional<URL> parseURL(const String &url)
{
int hostBeg = 0;
URL _URL;
_URL.scheme = "HTTP://";
if (url.substring(0, 7).equalsIgnoreCase("HTTP://"))
{
hostBeg += 7;
}
else if (url.substring(0, 8).equalsIgnoreCase("HTTPS://"))
return {};
int pathBeg = url.indexOf('/', hostBeg);
if (pathBeg < 0)
return {};
int hostEnd = pathBeg;
int portBeg = url.indexOf(':', hostBeg);
if (portBeg > 0 && portBeg < pathBeg)
{
_URL.port = url.substring(portBeg + 1, pathBeg).toInt();
hostEnd = portBeg;
}
else
_URL.port = 80;
_URL.host = url.substring(hostBeg, hostEnd);
int queryBeg = url.indexOf('?');
if (queryBeg < 0)
queryBeg = url.length();
_URL.path = url.substring(pathBeg, queryBeg);
_URL.query = url.substring(queryBeg);
AHTTP_LOGDEBUG2("_parseURL(): scheme+host", _URL.scheme, _URL.host);
AHTTP_LOGDEBUG3("_parseURL(): port+path+query", _URL.port, _URL.path, _URL.query);
return _URL;
}
//**************************************************************************************************************
AsyncHTTPRequest::~AsyncHTTPRequest()
{
if (_client)
_client->close(true);
delete _URL;
delete _headers;
delete _request;
delete _response;
delete _chunks;
delete[] _connectedHost;
#ifdef ESP32
vSemaphoreDelete(threadLock);
@@ -71,73 +133,67 @@ void AsyncHTTPRequest::setDebug(bool debug)
}
//**************************************************************************************************************
bool AsyncHTTPRequest::debug()
bool AsyncHTTPRequest::debug() const
{
return (_debug);
return _debug;
}
//**************************************************************************************************************
bool AsyncHTTPRequest::open(const char* method, const char* URL)
bool AsyncHTTPRequest::open(const URL &url, HTTPmethod method)
{
AHTTP_LOGDEBUG3("open(", method, ", url =", URL);
AHTTP_LOGDEBUG3("open(url =", url.toString(), ", method =", toString<String>(method));
if (_readyState != readyStateUnsent && _readyState != readyStateDone)
switch (_readyState)
{
case ReadyState::Idle:
case ReadyState::Unsent:
case ReadyState::Done:
break;
default:
return false;
}
_requestStartTime = millis();
delete _URL;
delete _headers;
delete _request;
delete _response;
delete _chunks;
_URL = nullptr;
_headers = nullptr;
_response = nullptr;
_request = nullptr;
_chunks = nullptr;
_chunked = false;
_contentRead = 0;
_readyState = readyStateUnsent;
_readyState = ReadyState::Unsent;
_HTTPmethod = method;
if (strcmp(method, "GET") == 0)
{
_HTTPmethod = HTTPmethodGET;
}
else if (strcmp(method, "POST") == 0)
{
_HTTPmethod = HTTPmethodPOST;
}
else
return false;
_URL = url;
if (!_parseURL(URL))
{
return false;
}
if ( _client && _client->connected() && (strcmp(_URL->host, _connectedHost) != 0 || _URL->port != _connectedPort))
if ( _client && _client->connected() && (_URL.host != _connectedHost || _URL.port != _connectedPort))
{
return false;
}
char* hostName = new char[strlen(_URL->host) + 10];
sprintf(hostName, "%s:%d", _URL->host, _URL->port);
_addHeader("host", hostName);
delete[] hostName;
_addHeader("host", _URL.host + ':' + _URL.port);
_lastActivity = millis();
return _connect();
}
//**************************************************************************************************************
void AsyncHTTPRequest::onReadyStateChange(readyStateChangeCB cb, void* arg)
void AsyncHTTPRequest::onReadyStateChange(readyStateChangeCB cb, callback_arg_t arg)
{
_readyStateChangeCB = cb;
_readyStateChangeCBarg = arg;
}
//**************************************************************************************************************
void AsyncHTTPRequest::onReadyStateChangeArg(callback_arg_t arg)
{
_readyStateChangeCBarg = arg;
}
//**************************************************************************************************************
void AsyncHTTPRequest::setTimeout(int seconds)
{
@@ -153,7 +209,7 @@ bool AsyncHTTPRequest::send()
_lock;
if ( ! _buildRequest())
if (!_buildRequest())
return false;
_send();
@@ -263,13 +319,13 @@ void AsyncHTTPRequest::abort()
_unlock;
}
//**************************************************************************************************************
reqStates AsyncHTTPRequest::readyState()
ReadyState AsyncHTTPRequest::readyState() const
{
return _readyState;
}
//**************************************************************************************************************
int AsyncHTTPRequest::responseHTTPcode()
int AsyncHTTPRequest::responseHTTPcode() const
{
return _HTTPcode;
}
@@ -281,7 +337,7 @@ String AsyncHTTPRequest::responseText()
_lock;
if ( ! _response || _readyState < readyStateLoading || ! available())
if ( ! _response || _readyState < ReadyState::Loading || ! available())
{
AHTTP_LOGDEBUG("responseText() no data");
@@ -297,7 +353,7 @@ String AsyncHTTPRequest::responseText()
{
AHTTP_LOGDEBUG("responseText() no buffer");
_HTTPcode = HTTPCODE_TOO_LESS_RAM;
_HTTPcode = HttpCode::TOO_LESS_RAM;
_client->abort();
_unlock;
@@ -317,7 +373,7 @@ String AsyncHTTPRequest::responseText()
//**************************************************************************************************************
size_t AsyncHTTPRequest::responseRead(uint8_t* buf, size_t len)
{
if ( ! _response || _readyState < readyStateLoading || ! available())
if ( ! _response || _readyState < ReadyState::Loading || ! available())
{
//DEBUG_HTTP("responseRead() no data\r\n");
AHTTP_LOGDEBUG("responseRead() no data");
@@ -338,9 +394,9 @@ size_t AsyncHTTPRequest::responseRead(uint8_t* buf, size_t len)
}
//**************************************************************************************************************
size_t AsyncHTTPRequest::available()
size_t AsyncHTTPRequest::available() const
{
if (_readyState < readyStateLoading)
if (_readyState < ReadyState::Loading)
return 0;
if (_chunked && (_contentLength - _contentRead) < _response->available())
@@ -352,9 +408,9 @@ size_t AsyncHTTPRequest::available()
}
//**************************************************************************************************************
size_t AsyncHTTPRequest::responseLength()
size_t AsyncHTTPRequest::responseLength() const
{
if (_readyState < readyStateLoading)
if (_readyState < ReadyState::Loading)
return 0;
return _contentLength;
@@ -370,12 +426,12 @@ void AsyncHTTPRequest::onData(onDataCB cb, void* arg)
}
//**************************************************************************************************************
uint32_t AsyncHTTPRequest::elapsedTime()
uint32_t AsyncHTTPRequest::elapsedTime() const
{
if (_readyState <= readyStateOpened)
if (_readyState <= ReadyState::Opened)
return 0;
if (_readyState != readyStateDone)
if (_readyState != ReadyState::Done)
{
return millis() - _requestStartTime;
}
@@ -384,7 +440,7 @@ uint32_t AsyncHTTPRequest::elapsedTime()
}
//**************************************************************************************************************
String AsyncHTTPRequest::version()
String AsyncHTTPRequest::version() const
{
return String(AsyncHTTPRequest_Generic_version);
}
@@ -398,64 +454,6 @@ String AsyncHTTPRequest::version()
P R R OOO T EEEEE CCC T EEEEE DDDD
_______________________________________________________________________________________________________________*/
//**************************************************************************************************************
bool AsyncHTTPRequest::_parseURL(const char* url)
{
return _parseURL(String(url));
}
//**************************************************************************************************************
bool AsyncHTTPRequest::_parseURL(String url)
{
delete _URL;
int hostBeg = 0;
_URL = new URL;
_URL->scheme = new char[8];
strcpy(_URL->scheme, "HTTP://");
if (url.substring(0, 7).equalsIgnoreCase("HTTP://"))
{
hostBeg += 7;
}
else if (url.substring(0, 8).equalsIgnoreCase("HTTPS://"))
{
return false;
}
int pathBeg = url.indexOf('/', hostBeg);
if (pathBeg < 0)
return false;
int hostEnd = pathBeg;
int portBeg = url.indexOf(':', hostBeg);
if (portBeg > 0 && portBeg < pathBeg)
{
_URL->port = url.substring(portBeg + 1, pathBeg).toInt();
hostEnd = portBeg;
}
_URL->host = new char[hostEnd - hostBeg + 1];
strcpy(_URL->host, url.substring(hostBeg, hostEnd).c_str());
int queryBeg = url.indexOf('?');
if (queryBeg < 0)
queryBeg = url.length();
_URL->path = new char[queryBeg - pathBeg + 1];
strcpy(_URL->path, url.substring(pathBeg, queryBeg).c_str());
_URL->query = new char[url.length() - queryBeg + 1];
strcpy(_URL->query, url.substring(queryBeg).c_str());
AHTTP_LOGDEBUG2("_parseURL(): scheme+host", _URL->scheme, _URL->host);
AHTTP_LOGDEBUG3("_parseURL(): port+path+query", _URL->port, _URL->path, _URL->query);
return true;
}
//**************************************************************************************************************
bool AsyncHTTPRequest::_connect()
{
@@ -466,11 +464,8 @@ bool AsyncHTTPRequest::_connect()
_client = new AsyncClient();
}
delete[] _connectedHost;
_connectedHost = new char[strlen(_URL->host) + 1];
strcpy(_connectedHost, _URL->host);
_connectedPort = _URL->port;
_connectedHost = _URL.host;
_connectedPort = _URL.port;
_client->onConnect([](void *obj, AsyncClient * client)
{
@@ -494,12 +489,12 @@ bool AsyncHTTPRequest::_connect()
if ( ! _client->connected())
{
if ( ! _client->connect(_URL->host, _URL->port))
if ( ! _client->connect(_URL.host.c_str(), _URL.port))
{
AHTTP_LOGDEBUG3("client.connect failed:", _URL->host, ",", _URL->port);
AHTTP_LOGDEBUG3("client.connect failed:", _URL.host, ",", _URL.port);
_HTTPcode = HTTPCODE_NOT_CONNECTED;
_setReadyState(readyStateDone);
_HTTPcode = HttpCode::NOT_CONNECTED;
_setReadyState(ReadyState::Done);
return false;
}
@@ -523,16 +518,12 @@ bool AsyncHTTPRequest::_buildRequest()
if ( ! _request)
_request = new xbuf;
_request->write(_HTTPmethod == HTTPmethodGET ? "GET " : "POST ");
_request->write(_URL->path);
_request->write(_URL->query);
_request->write(toString<String>(_HTTPmethod));
_request->write(' ');
_request->write(_URL.path);
_request->write(_URL.query);
_request->write(" HTTP/1.1\r\n");
AHTTP_LOGDEBUG3(_HTTPmethod == HTTPmethodGET ? "GET " : "POST ", _URL->path, _URL->query, " HTTP/1.1\r\n" );
delete _URL;
_URL = nullptr;
header* hdr = _headers;
while (hdr)
@@ -541,14 +532,12 @@ bool AsyncHTTPRequest::_buildRequest()
_request->write(':');
_request->write(hdr->value);
_request->write("\r\n");
AHTTP_LOGDEBUG3(hdr->name, ":", hdr->value, "\r\n" );
hdr = hdr->next;
}
delete _headers;
_headers = nullptr;
_request->write("\r\n");
return true;
@@ -603,13 +592,13 @@ size_t AsyncHTTPRequest::_send()
}
//**************************************************************************************************************
void AsyncHTTPRequest::_setReadyState(reqStates newState)
void AsyncHTTPRequest::_setReadyState(ReadyState readyState)
{
if (_readyState != newState)
if (_readyState != readyState)
{
_readyState = newState;
_readyState = readyState;
AHTTP_LOGDEBUG1("_setReadyState :", _readyState);
AHTTP_LOGDEBUG1("_setReadyState :", int(_readyState));
if (_readyStateChangeCB)
{
@@ -642,9 +631,9 @@ void AsyncHTTPRequest::_processChunks()
if (chunkLength == 0)
{
char* connectionHdr = respHeaderValue("connection");
const auto connectionHdr = respHeaderValue("connection");
if (connectionHdr && (strcasecmp_P(connectionHdr, PSTR("disconnect")) == 0))
if (connectionHdr && connectionHdr == "disconnect")
{
AHTTP_LOGDEBUG("*all chunks received - closing TCP");
@@ -658,7 +647,7 @@ void AsyncHTTPRequest::_processChunks()
_requestEndTime = millis();
_lastActivity = 0;
_timeout = 0;
_setReadyState(readyStateDone);
_setReadyState(ReadyState::Done);
return;
}
@@ -681,7 +670,7 @@ void AsyncHTTPRequest::_onConnect(AsyncClient* client)
_lock;
_client = client;
_setReadyState(readyStateOpened);
_setReadyState(ReadyState::Opened);
_response = new xbuf;
_contentLength = 0;
_contentRead = 0;
@@ -714,7 +703,7 @@ void AsyncHTTPRequest::_onPoll(AsyncClient* client)
if (_timeout && (millis() - _lastActivity) > (_timeout * 1000))
{
_client->close();
_HTTPcode = HTTPCODE_TIMEOUT;
_HTTPcode = HttpCode::TIMEOUT;
AHTTP_LOGDEBUG("_onPoll timeout");
}
@@ -742,26 +731,25 @@ void AsyncHTTPRequest::_onDisconnect(AsyncClient* client)
_lock;
if (_readyState < readyStateOpened)
if (_readyState < ReadyState::Opened)
{
_HTTPcode = HTTPCODE_NOT_CONNECTED;
_HTTPcode = HttpCode::NOT_CONNECTED;
}
else if (_HTTPcode > 0 &&
(_readyState < readyStateHdrsRecvd || (_contentRead + _response->available()) < _contentLength))
(_readyState < ReadyState::HdrsRecvd || (_contentRead + _response->available()) < _contentLength))
{
_HTTPcode = HTTPCODE_CONNECTION_LOST;
_HTTPcode = HttpCode::CONNECTION_LOST;
}
delete _client;
_client = nullptr;
delete[] _connectedHost;
_connectedHost = nullptr;
_connectedHost = String{};
_connectedPort = -1;
_requestEndTime = millis();
_lastActivity = 0;
_setReadyState(readyStateDone);
_setReadyState(ReadyState::Done);
_unlock;
}
@@ -784,24 +772,24 @@ void AsyncHTTPRequest::_onData(void* Vbuf, size_t len)
}
// if headers not complete, collect them. If still not complete, just return.
if (_readyState == readyStateOpened)
if (_readyState == ReadyState::Opened)
{
if ( ! _collectHeaders())
return;
}
// If there's data in the buffer and not Done, advance readyState to Loading.
if (_response->available() && _readyState != readyStateDone)
if (_response->available() && _readyState != ReadyState::Done)
{
_setReadyState(readyStateLoading);
_setReadyState(ReadyState::Loading);
}
// If not chunked and all data read, close it up.
if ( ! _chunked && (_response->available() + _contentRead) >= _contentLength)
{
char* connectionHdr = respHeaderValue("connection");
const auto connectionHdr = respHeaderValue("connection");
if (connectionHdr && (strcasecmp_P(connectionHdr, PSTR("disconnect")) == 0))
if (connectionHdr && connectionHdr == "disconnect")
{
AHTTP_LOGDEBUG("*all data received - closing TCP");
@@ -815,7 +803,7 @@ void AsyncHTTPRequest::_onData(void* Vbuf, size_t len)
_requestEndTime = millis();
_lastActivity = 0;
_timeout = 0;
_setReadyState(readyStateDone);
_setReadyState(ReadyState::Done);
}
// If onData callback requested, do so.
@@ -847,7 +835,7 @@ bool AsyncHTTPRequest::_collectHeaders()
// If empty line, all headers are in, advance readyState.
if (headerLine.length() == 2)
{
_setReadyState(readyStateHdrsRecvd);
_setReadyState(ReadyState::HdrsRecvd);
}
// If line is HTTP header, capture HTTPcode.
else if (headerLine.substring(0, 7) == "HTTP/1.")
@@ -868,20 +856,20 @@ bool AsyncHTTPRequest::_collectHeaders()
_addHeader(name.c_str(), value.c_str());
}
}
} while (_readyState == readyStateOpened);
} while (_readyState == ReadyState::Opened);
// If content-Length header, set _contentLength
header *hdr = _getHeader("Content-Length");
if (hdr)
{
_contentLength = strtol(hdr->value, nullptr, 10);
_contentLength = hdr->value.toInt();
}
// If chunked specified, try to set _contentLength to size of first chunk
hdr = _getHeader("Transfer-Encoding");
if (hdr && strcasecmp_P(hdr->value, PSTR("chunked")) == 0)
if (hdr && hdr->value == "chunked")
{
AHTTP_LOGDEBUG("*transfer-encoding: chunked");
@@ -908,7 +896,7 @@ bool AsyncHTTPRequest::_collectHeaders()
//**************************************************************************************************************
void AsyncHTTPRequest::setReqHeader(const char* name, const char* value)
{
if (_readyState <= readyStateOpened && _headers)
if (_readyState <= ReadyState::Opened && _headers)
{
_addHeader(name, value);
}
@@ -917,7 +905,7 @@ void AsyncHTTPRequest::setReqHeader(const char* name, const char* value)
//**************************************************************************************************************
void AsyncHTTPRequest::setReqHeader(const char* name, int32_t value)
{
if (_readyState <= readyStateOpened && _headers)
if (_readyState <= ReadyState::Opened && _headers)
{
setReqHeader(name, String(value).c_str());
}
@@ -928,7 +916,7 @@ void AsyncHTTPRequest::setReqHeader(const char* name, int32_t value)
//**************************************************************************************************************
void AsyncHTTPRequest::setReqHeader(const char* name, const __FlashStringHelper* value)
{
if (_readyState <= readyStateOpened && _headers)
if (_readyState <= ReadyState::Opened && _headers)
{
char* _value = _charstar(value);
_addHeader(name, _value);
@@ -939,7 +927,7 @@ void AsyncHTTPRequest::setReqHeader(const char* name, const __FlashStringHelper*
//**************************************************************************************************************
void AsyncHTTPRequest::setReqHeader(const __FlashStringHelper *name, const char* value)
{
if (_readyState <= readyStateOpened && _headers)
if (_readyState <= ReadyState::Opened && _headers)
{
char* _name = _charstar(name);
_addHeader(_name, value);
@@ -950,7 +938,7 @@ void AsyncHTTPRequest::setReqHeader(const __FlashStringHelper *name, const char*
//**************************************************************************************************************
void AsyncHTTPRequest::setReqHeader(const __FlashStringHelper *name, const __FlashStringHelper* value)
{
if (_readyState <= readyStateOpened && _headers)
if (_readyState <= ReadyState::Opened && _headers)
{
char* _name = _charstar(name);
char* _value = _charstar(value);
@@ -963,7 +951,7 @@ void AsyncHTTPRequest::setReqHeader(const __FlashStringHelper *name, const __Fla
//**************************************************************************************************************
void AsyncHTTPRequest::setReqHeader(const __FlashStringHelper *name, int32_t value)
{
if (_readyState <= readyStateOpened && _headers)
if (_readyState <= ReadyState::Opened && _headers)
{
char* _name = _charstar(name);
setReqHeader(_name, String(value).c_str());
@@ -976,7 +964,7 @@ void AsyncHTTPRequest::setReqHeader(const __FlashStringHelper *name, int32_t val
//**************************************************************************************************************
int AsyncHTTPRequest::respHeaderCount()
{
if (_readyState < readyStateHdrsRecvd)
if (_readyState < ReadyState::HdrsRecvd)
return 0;
int count = 0;
@@ -992,76 +980,69 @@ int AsyncHTTPRequest::respHeaderCount()
}
//**************************************************************************************************************
char* AsyncHTTPRequest::respHeaderName(int ndx)
String AsyncHTTPRequest::respHeaderName(int ndx)
{
if (_readyState < readyStateHdrsRecvd)
return nullptr;
if (_readyState < ReadyState::HdrsRecvd)
return {};
header* hdr = _getHeader(ndx);
if ( ! hdr)
return nullptr;
return {};
return hdr->name;
}
//**************************************************************************************************************
char* AsyncHTTPRequest::respHeaderValue(const char* name)
String AsyncHTTPRequest::respHeaderValue(const String &name)
{
if (_readyState < readyStateHdrsRecvd)
return nullptr;
if (_readyState < ReadyState::HdrsRecvd)
return {};
header* hdr = _getHeader(name);
if ( ! hdr)
return nullptr;
return {};
return hdr->value;
}
//**************************************************************************************************************
char* AsyncHTTPRequest::respHeaderValue(int ndx)
String AsyncHTTPRequest::respHeaderValue(int ndx)
{
if (_readyState < readyStateHdrsRecvd)
return nullptr;
if (_readyState < ReadyState::HdrsRecvd)
return {};
header* hdr = _getHeader(ndx);
if ( ! hdr)
return nullptr;
return {};
return hdr->value;
}
//**************************************************************************************************************
bool AsyncHTTPRequest::respHeaderExists(const char* name)
bool AsyncHTTPRequest::respHeaderExists(const String &name)
{
if (_readyState < readyStateHdrsRecvd)
if (_readyState < ReadyState::HdrsRecvd)
return false;
header* hdr = _getHeader(name);
if ( ! hdr)
return false;
return true;
return _getHeader(name);
}
#if (ESP32 || ESP8266)
//**************************************************************************************************************
char* AsyncHTTPRequest::respHeaderValue(const __FlashStringHelper *name)
String AsyncHTTPRequest::respHeaderValue(const __FlashStringHelper *name)
{
if (_readyState < readyStateHdrsRecvd)
return nullptr;
if (_readyState < ReadyState::HdrsRecvd)
return {};
char* _name = _charstar(name);
header* hdr = _getHeader(_name);
delete[] _name;
header* hdr = _getHeader(name);
if ( ! hdr)
return nullptr;
return {};
return hdr->value;
}
@@ -1069,17 +1050,10 @@ char* AsyncHTTPRequest::respHeaderValue(const __FlashStringHelper *name)
//**************************************************************************************************************
bool AsyncHTTPRequest::respHeaderExists(const __FlashStringHelper *name)
{
if (_readyState < readyStateHdrsRecvd)
if (_readyState < ReadyState::HdrsRecvd)
return false;
char* _name = _charstar(name);
header* hdr = _getHeader(_name);
delete[] _name;
if ( ! hdr)
return false;
return true;
return _getHeader(name);
}
#endif
@@ -1107,14 +1081,14 @@ String AsyncHTTPRequest::headers()
}
//**************************************************************************************************************
AsyncHTTPRequest::header* AsyncHTTPRequest::_addHeader(const char* name, const char* value)
AsyncHTTPRequest::header* AsyncHTTPRequest::_addHeader(const String &name, const String &value)
{
_lock;
header* hdr = (header*) &_headers;
while (hdr->next)
{
if (strcasecmp(name, hdr->next->name) == 0)
if (name.equalsIgnoreCase(hdr->next->name))
{
header* oldHdr = hdr->next;
hdr->next = hdr->next->next;
@@ -1128,24 +1102,22 @@ AsyncHTTPRequest::header* AsyncHTTPRequest::_addHeader(const char* name, const
}
hdr->next = new header;
hdr->next->name = new char[strlen(name) + 1];
strcpy(hdr->next->name, name);
hdr->next->value = new char[strlen(value) + 1];
strcpy(hdr->next->value, value);
hdr->next->name = name;
hdr->next->value = value;
_unlock;
return hdr->next;
}
//**************************************************************************************************************
AsyncHTTPRequest::header* AsyncHTTPRequest::_getHeader(const char* name)
AsyncHTTPRequest::header* AsyncHTTPRequest::_getHeader(const String &name)
{
_lock;
header* hdr = _headers;
while (hdr)
{
if (strcasecmp(name, hdr->name) == 0)
if (name.equalsIgnoreCase(hdr->name))
break;
hdr = hdr->next;
+318
View File
@@ -0,0 +1,318 @@
/****************************************************************************************************************************
AsyncHTTPRequest_Generic.h - 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)
AsyncHTTPRequest_STM32 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/AsyncHTTPRequest_Generic
Licensed under MIT license
Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>
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 <https://www.gnu.org/licenses/>.
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
*****************************************************************************************************************************/
#pragma once
#define AsyncHTTPRequest_Generic_version "1.0.0"
#include <Arduino.h>
#include <WString.h>
#include <optional>
#include "AsyncHTTPRequest_Debug.h"
#ifndef DEBUG_IOTA_PORT
#define DEBUG_IOTA_PORT Serial
#endif
#ifdef DEBUG_IOTA_HTTP
#define DEBUG_IOTA_HTTP_SET true
#else
#define DEBUG_IOTA_HTTP_SET false
#endif
#if ESP32
#include <AsyncTCP.h>
#elif ESP8266
#include <ESPAsyncTCP.h>
#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) || \
defined(STM32WB) || defined(STM32MP1) )
#include "STM32AsyncTCP.h"
#endif
#include <pgmspace.h>
#include <utility/xbuf.h>
#define DEBUG_HTTP(format,...) if(_debug){\
DEBUG_IOTA_PORT.printf("Debug(%3ld): ", millis()-_requestStartTime);\
DEBUG_IOTA_PORT.printf_P(PSTR(format),##__VA_ARGS__);}
#define DEFAULT_RX_TIMEOUT 3 // Seconds for timeout
namespace HttpCode
{
enum
{
CONNECTION_REFUSED = -1,
SEND_HEADER_FAILED = -2,
SEND_PAYLOAD_FAILED = -3,
NOT_CONNECTED = -4,
CONNECTION_LOST = -5,
NO_STREAM = -6,
NO_HTTP_SERVER = -7,
TOO_LESS_RAM = -8,
ENCODING = -9,
STREAM_WRITE = -10,
TIMEOUT = -11,
};
inline String toString(int code)
{
switch (code)
{
case CONNECTION_REFUSED: return "CONNECTION_REFUSED";
case SEND_HEADER_FAILED: return "SEND_HEADER_FAILED";
case SEND_PAYLOAD_FAILED: return "SEND_PAYLOAD_FAILED";
case NOT_CONNECTED: return "NOT_CONNECTED";
case CONNECTION_LOST: return "CONNECTION_LOST";
case NO_STREAM: return "NO_STREAM";
case NO_HTTP_SERVER: return "NO_HTTP_SERVER";
case TOO_LESS_RAM: return "TOO_LESS_RAM";
case ENCODING: return "ENCODING";
case STREAM_WRITE: return "STREAM_WRITE";
case TIMEOUT: return "TIMEOUT";
}
return String{code};
}
}
enum class ReadyState
{
Idle, // Client created, open not yet called
Unsent, // open() has been called, not connected
Opened, // open() has been called, connected
HdrsRecvd, // send() called, response headers available
Loading, // receiving, partial data available
Done // Request complete, all data available.
};
namespace {
//! Helper utility to convert a ReadyState into a string
//! String library agnostic, can be used with std::string or Arduino's WString
template<typename T>
T toString(ReadyState state)
{
switch (state)
{
case ReadyState::Idle: return "Idle";
case ReadyState::Unsent: return "Unsent";
case ReadyState::Opened: return "Opened";
case ReadyState::HdrsRecvd: return "HdrsRecvd";
case ReadyState::Loading: return "Loading";
case ReadyState::Done: return "Done";
}
return T{"Unknown ReadyState("} + int(state) + ')';
}
}
enum class HTTPmethod
{
GET,
POST
};
namespace {
//! Helper utility to convert a HTTPmethod into a string
//! String library agnostic, can be used with std::string or Arduino's WString
template<typename T>
T toString(HTTPmethod method)
{
switch (method)
{
case HTTPmethod::GET: return "GET";
case HTTPmethod::POST: return "POST";
}
return T{"Unknown HTTPmethod("} + int(method) + ')';
}
}
struct URL
{
String scheme;
String user;
String pwd;
String host;
int port;
String path;
String query;
String fragment;
String toString() const
{
return scheme + user + pwd + host + ':' + port + path + query + fragment;
}
};
std::optional<URL> parseURL(const String &url);
class AsyncHTTPRequest
{
using callback_arg_t = void*;
struct header
{
header* next{};
String name;
String value;
~header()
{
delete next;
}
};
using readyStateChangeCB = std::function<void(callback_arg_t, AsyncHTTPRequest*, ReadyState readyState)>;
using onDataCB = std::function<void(void*, AsyncHTTPRequest*, size_t available)>;
public:
~AsyncHTTPRequest();
//External functions in typical order of use:
//__________________________________________________________________________________________________________*/
void setDebug(bool); // Turn debug message on/off
bool debug() const; // is debug on or off?
bool open(const URL &url, HTTPmethod method = HTTPmethod::GET); // Initiate a request
void onReadyStateChange(readyStateChangeCB, callback_arg_t arg = 0); // Optional event handler for ready state change
void onReadyStateChangeArg(callback_arg_t arg = 0); // set event handlers arg
// or you can simply poll readyState()
void setTimeout(int seconds); // overide default timeout (seconds)
void setReqHeader(const char* name, const char* value); // add a request header
void setReqHeader(const char* name, int32_t value); // overload to use integer value
#if (ESP32 || ESP8266)
void setReqHeader(const char* name, const __FlashStringHelper* value);
void setReqHeader(const __FlashStringHelper *name, const char* value);
void setReqHeader(const __FlashStringHelper *name, const __FlashStringHelper* value);
void setReqHeader(const __FlashStringHelper *name, int32_t value);
#endif
bool send(); // Send the request (GET)
bool send(String body); // Send the request (POST)
bool send(const char* body); // Send the request (POST)
bool send(const uint8_t* buffer, size_t len); // Send the request (POST) (binary data?)
bool send(xbuf* body, size_t len); // Send the request (POST) data in an xbuf
void abort(); // Abort the current operation
ReadyState readyState() const; // Return the ready state
int respHeaderCount(); // Retrieve count of response headers
String respHeaderName(int index); // Return header name by index
String respHeaderValue(int index); // Return header value by index
String respHeaderValue(const String &name); // Return header value by name
bool respHeaderExists(const String &name); // Does header exist by name?
#if (ESP32 || ESP8266)
String respHeaderValue(const __FlashStringHelper *name);
bool respHeaderExists(const __FlashStringHelper *name);
#endif
const URL &url() const { return _URL; }
String headers(); // Return all headers as String
void onData(onDataCB, void* arg = 0); // Notify when min data is available
size_t available() const; // response available
size_t responseLength() const; // indicated response length or sum of chunks to date
int responseHTTPcode() const; // HTTP response code or (negative) error code
String responseText(); // response (whole* or partial* as string)
size_t responseRead(uint8_t* buffer, size_t len); // Read response into buffer
uint32_t elapsedTime() const; // Elapsed time of in progress transaction or last completed (ms)
String version() const; // Version of AsyncHTTPRequest
//___________________________________________________________________________________________________________________________________
private:
HTTPmethod _HTTPmethod;
ReadyState _readyState{ReadyState::Idle};
int16_t _HTTPcode{0}; // HTTP response code or (negative) exception code
bool _chunked{false}; // Processing chunked response
bool _debug{DEBUG_IOTA_HTTP_SET}; // Debug state
uint32_t _timeout{DEFAULT_RX_TIMEOUT}; // Default or user overide RxTimeout in seconds
uint32_t _lastActivity{0}; // Time of last activity
uint32_t _requestStartTime{0}; // Time last open() issued
uint32_t _requestEndTime{0}; // Time of last disconnect
URL _URL{}; // -> URL data structure
String _connectedHost; // Host when connected
int _connectedPort{-1}; // Port when connected
AsyncClient* _client{nullptr}; // ESPAsyncTCP AsyncClient instance
size_t _contentLength{0}; // content-length header value or sum of chunk headers
size_t _contentRead{0}; // number of bytes retrieved by user since last open()
readyStateChangeCB _readyStateChangeCB{}; // optional callback for readyState change
callback_arg_t _readyStateChangeCBarg{}; // associated user argument
onDataCB _onDataCB{nullptr}; // optional callback when data received
void* _onDataCBarg{nullptr}; // associated user argument
#ifdef ESP32
SemaphoreHandle_t threadLock{xSemaphoreCreateRecursiveMutex()};
#endif
// request and response String buffers and header list (same queue for request and response).
xbuf* _request{nullptr}; // Tx data buffer
xbuf* _response{nullptr}; // Rx data buffer for headers
xbuf* _chunks{nullptr}; // First stage for chunked response
header* _headers{nullptr}; // request or (readyState > readyStateHdrsRcvd) response headers
// Protected functions
header* _addHeader(const String &name, const String &value);
header* _getHeader(const String &name);
header* _getHeader(int idx);
bool _buildRequest();
void _processChunks();
bool _connect();
size_t _send();
void _setReadyState(ReadyState readyState);
#if (ESP32 || ESP8266)
char* _charstar(const __FlashStringHelper *str);
#endif
// callbacks
void _onConnect(AsyncClient*);
void _onDisconnect(AsyncClient*);
void _onData(void*, size_t);
void _onError(AsyncClient*, int8_t);
void _onPoll(AsyncClient*);
bool _collectHeaders();
};
@@ -17,14 +17,13 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#pragma once
#ifdef ASYNC_HTTP_DEBUG_PORT
@@ -67,4 +66,3 @@
#define AHTTP_LOGDEBUG1(x,y) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.println(y); }
#define AHTTP_LOGDEBUG2(x,y,z) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.println(z); }
#define AHTTP_LOGDEBUG3(x,y,z,w) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.print(z); A_DBG_PORT.print(" "); A_DBG_PORT.println(w); }
-267
View File
@@ -1,267 +0,0 @@
/****************************************************************************************************************************
AsyncHTTPRequest_Generic.h - 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)
AsyncHTTPRequest_STM32 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/AsyncHTTPRequest_Generic
Licensed under MIT license
Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#pragma once
#define AsyncHTTPRequest_Generic_version "1.0.0"
#include <Arduino.h>
#include "AsyncHTTPRequest_Debug_Generic.h"
#ifndef DEBUG_IOTA_PORT
#define DEBUG_IOTA_PORT Serial
#endif
#ifdef DEBUG_IOTA_HTTP
#define DEBUG_IOTA_HTTP_SET true
#else
#define DEBUG_IOTA_HTTP_SET false
#endif
#if ESP32
#include <AsyncTCP.h>
#define _lock xSemaphoreTakeRecursive(threadLock,portMAX_DELAY)
#define _unlock xSemaphoreGiveRecursive(threadLock)
#elif ESP8266
#include <ESPAsyncTCP.h>
#define _lock
#define _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) || \
defined(STM32WB) || defined(STM32MP1) )
#include "STM32AsyncTCP.h"
#define _lock
#define _unlock
#endif
#include <pgmspace.h>
#include <utility/xbuf.h>
#define DEBUG_HTTP(format,...) if(_debug){\
DEBUG_IOTA_PORT.printf("Debug(%3ld): ", millis()-_requestStartTime);\
DEBUG_IOTA_PORT.printf_P(PSTR(format),##__VA_ARGS__);}
#define DEFAULT_RX_TIMEOUT 3 // Seconds for timeout
#define HTTPCODE_CONNECTION_REFUSED (-1)
#define HTTPCODE_SEND_HEADER_FAILED (-2)
#define HTTPCODE_SEND_PAYLOAD_FAILED (-3)
#define HTTPCODE_NOT_CONNECTED (-4)
#define HTTPCODE_CONNECTION_LOST (-5)
#define HTTPCODE_NO_STREAM (-6)
#define HTTPCODE_NO_HTTP_SERVER (-7)
#define HTTPCODE_TOO_LESS_RAM (-8)
#define HTTPCODE_ENCODING (-9)
#define HTTPCODE_STREAM_WRITE (-10)
#define HTTPCODE_TIMEOUT (-11)
typedef enum
{
readyStateUnsent = 0, // Client created, open not yet called
readyStateOpened = 1, // open() has been called, connected
readyStateHdrsRecvd = 2, // send() called, response headers available
readyStateLoading = 3, // receiving, partial data available
readyStateDone = 4 // Request complete, all data available.
} reqStates;
class AsyncHTTPRequest
{
struct header
{
header* next;
char* name;
char* value;
header(): next(nullptr), name(nullptr), value(nullptr)
{};
~header()
{
delete[] name;
delete[] value;
delete next;
}
};
struct URL
{
char* scheme;
char* user;
char* pwd;
char* host;
int port;
char* path;
char* query;
char* fragment;
URL(): scheme(nullptr), user(nullptr), pwd(nullptr), host(nullptr),
port(80), path(nullptr), query(nullptr), fragment(nullptr)
{};
~URL()
{
delete[] scheme;
delete[] user;
delete[] pwd;
delete[] host;
delete[] path;
delete[] query;
delete[] fragment;
}
};
typedef std::function<void(void*, AsyncHTTPRequest*, int readyState)> readyStateChangeCB;
typedef std::function<void(void*, AsyncHTTPRequest*, size_t available)> onDataCB;
public:
AsyncHTTPRequest();
~AsyncHTTPRequest();
//External functions in typical order of use:
//__________________________________________________________________________________________________________*/
void setDebug(bool); // Turn debug message on/off
bool debug(); // is debug on or off?
bool open(const char* /*GET/POST*/, const char* URL); // Initiate a request
void onReadyStateChange(readyStateChangeCB, void* arg = 0); // Optional event handler for ready state change
// or you can simply poll readyState()
void setTimeout(int); // overide default timeout (seconds)
void setReqHeader(const char* name, const char* value); // add a request header
void setReqHeader(const char* name, int32_t value); // overload to use integer value
#if (ESP32 || ESP8266)
void setReqHeader(const char* name, const __FlashStringHelper* value);
void setReqHeader(const __FlashStringHelper *name, const char* value);
void setReqHeader(const __FlashStringHelper *name, const __FlashStringHelper* value);
void setReqHeader(const __FlashStringHelper *name, int32_t value);
#endif
bool send(); // Send the request (GET)
bool send(String body); // Send the request (POST)
bool send(const char* body); // Send the request (POST)
bool send(const uint8_t* buffer, size_t len); // Send the request (POST) (binary data?)
bool send(xbuf* body, size_t len); // Send the request (POST) data in an xbuf
void abort(); // Abort the current operation
reqStates readyState(); // Return the ready state
int respHeaderCount(); // Retrieve count of response headers
char* respHeaderName(int index); // Return header name by index
char* respHeaderValue(int index); // Return header value by index
char* respHeaderValue(const char* name); // Return header value by name
bool respHeaderExists(const char* name); // Does header exist by name?
#if (ESP32 || ESP8266)
char* respHeaderValue(const __FlashStringHelper *name);
bool respHeaderExists(const __FlashStringHelper *name);
#endif
String headers(); // Return all headers as String
void onData(onDataCB, void* arg = 0); // Notify when min data is available
size_t available(); // response available
size_t responseLength(); // indicated response length or sum of chunks to date
int responseHTTPcode(); // HTTP response code or (negative) error code
String responseText(); // response (whole* or partial* as string)
size_t responseRead(uint8_t* buffer, size_t len); // Read response into buffer
uint32_t elapsedTime(); // Elapsed time of in progress transaction or last completed (ms)
String version(); // Version of AsyncHTTPRequest
//___________________________________________________________________________________________________________________________________
private:
enum {HTTPmethodGET, HTTPmethodPOST} _HTTPmethod;
reqStates _readyState;
int16_t _HTTPcode; // HTTP response code or (negative) exception code
bool _chunked; // Processing chunked response
bool _debug; // Debug state
uint32_t _timeout; // Default or user overide RxTimeout in seconds
uint32_t _lastActivity; // Time of last activity
uint32_t _requestStartTime; // Time last open() issued
uint32_t _requestEndTime; // Time of last disconnect
URL* _URL; // -> URL data structure
char* _connectedHost; // Host when connected
int _connectedPort; // Port when connected
AsyncClient* _client; // ESPAsyncTCP AsyncClient instance
size_t _contentLength; // content-length header value or sum of chunk headers
size_t _contentRead; // number of bytes retrieved by user since last open()
readyStateChangeCB _readyStateChangeCB; // optional callback for readyState change
void* _readyStateChangeCBarg; // associated user argument
onDataCB _onDataCB; // optional callback when data received
void* _onDataCBarg; // associated user argument
#ifdef ESP32
SemaphoreHandle_t threadLock;
#endif
// request and response String buffers and header list (same queue for request and response).
xbuf* _request; // Tx data buffer
xbuf* _response; // Rx data buffer for headers
xbuf* _chunks; // First stage for chunked response
header* _headers; // request or (readyState > readyStateHdrsRcvd) response headers
// Protected functions
header* _addHeader(const char*, const char*);
header* _getHeader(const char*);
header* _getHeader(int);
bool _buildRequest();
bool _parseURL(const char*);
bool _parseURL(String);
void _processChunks();
bool _connect();
size_t _send();
void _setReadyState(reqStates);
#if (ESP32 || ESP8266)
char* _charstar(const __FlashStringHelper *str);
#endif
// callbacks
void _onConnect(AsyncClient*);
void _onDisconnect(AsyncClient*);
void _onData(void*, size_t);
void _onError(AsyncClient*, int8_t);
void _onPoll(AsyncClient*);
bool _collectHeaders();
};
#include "AsyncHTTPRequest_Impl_Generic.h"
@@ -1,5 +1,5 @@
/****************************************************************************************************************************
src_cpp/utility/xbuf_Impl.h - Dead simple AsyncHTTPRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet
xbuf_Impl.h - 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)
@@ -17,14 +17,16 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#ifndef xbuf_Impl_h
#define xbuf_Impl_h
#include "utility/xbuf.h"
xbuf::xbuf(const uint16_t segSize) : _head(nullptr), _tail(nullptr), _used(0), _free(0), _offset(0)
@@ -390,3 +392,4 @@ void xbuf::remSeg()
_offset = 0;
}
#endif // xbuf_Impl_h
+5 -4
View File
@@ -17,12 +17,11 @@
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
/********************************************************************************************
@@ -45,6 +44,9 @@
********************************************************************************************/
#pragma once
#ifndef xbuf_h
#define xbuf_h
#include <Arduino.h>
struct xseg
@@ -146,5 +148,4 @@ class xbuf: public Print
};
#include "utility/xbuf_Impl.h"
#endif // xbuf_h
-392
View File
@@ -1,392 +0,0 @@
/****************************************************************************************************************************
xbuf_Impl.h - 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)
AsyncHTTPRequest_STM32 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/AsyncHTTPRequest_Generic
Licensed under MIT license
Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#pragma once
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()
{
flush();
}
//*******************************************************************************************************************
size_t xbuf::write(const uint8_t byte)
{
return write((uint8_t*) &byte, 1);
}
//*******************************************************************************************************************
size_t xbuf::write(const char* buf)
{
return write((uint8_t*)buf, strlen(buf));
}
//*******************************************************************************************************************
size_t xbuf::write(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 supply = len;
while (supply)
{
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 supply = len;
if (supply > buf->available())
{
supply = buf->available();
}
size_t read = 0;
while (supply)
{
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 byte = 0;
read((uint8_t*) &byte, 1);
return byte;
}
//*******************************************************************************************************************
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 read = 0;
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, _head->data + _offset, chunk);
_offset += chunk;
_used -= chunk;
read += chunk;
if (_offset == _segSize)
{
remSeg();
_offset = 0;
}
}
if ( ! _used)
{
flush();
}
return read;
}
//*******************************************************************************************************************
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)
{
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)
{
seg = seg->next;
offset = 0;
}
}
return read;
}
//*******************************************************************************************************************
size_t xbuf::available()
{
return _used;
}
//*******************************************************************************************************************
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)
{
size_t targetLen = strlen(target);
if (targetLen > _segSize || targetLen > _used)
return -1;
size_t searchPos = _offset + begin;
size_t searchEnd = _offset + _used - targetLen;
if (searchPos > searchEnd)
return -1;
size_t searchSeg = searchPos / _segSize;
xseg* seg = _head;
while (searchSeg)
{
seg = seg->next;
searchSeg --;
}
size_t segPos = searchPos % _segSize;
while (searchPos <= searchEnd)
{
size_t compLen = targetLen;
if (compLen <= (_segSize - segPos))
{
if (memcmp(target, seg->data + segPos, compLen) == 0)
{
return searchPos - _offset;
}
}
else
{
size_t compLen = _segSize - segPos;
if (memcmp(target, seg->data + segPos, compLen) == 0)
{
compLen = targetLen - compLen;
if (memcmp(target + targetLen - compLen, seg->next->data, compLen) == 0)
{
return searchPos - _offset;
}
}
}
searchPos++;
segPos++;
if (segPos == _segSize)
{
seg = seg->next;
segPos = 0;
}
}
return -1;
}
//*******************************************************************************************************************
String xbuf::readStringUntil(const char target)
{
return readString(indexOf(target) + 1);
}
//*******************************************************************************************************************
String xbuf::readStringUntil(const char* target)
{
int index = indexOf(target);
if (index < 0)
return String();
return readString(index + strlen(target));
}
//*******************************************************************************************************************
String xbuf::readString(int endPos)
{
String result;
if ( ! result.reserve(endPos + 1))
{
return result;
}
if (endPos > _used)
{
endPos = _used;
}
if (endPos > 0 && result.reserve(endPos + 1))
{
while (endPos--)
{
result += (char)_head->data[_offset++];
_used--;
if (_offset >= _segSize)
{
remSeg();
}
}
}
return result;
}
//*******************************************************************************************************************
String xbuf::peekString(int endPos)
{
String result;
xseg* seg = _head;
size_t offset = _offset;
if (endPos > _used)
{
endPos = _used;
}
if (endPos > 0 && result.reserve(endPos + 1))
{
while (endPos--)
{
result += (char)seg->data[offset++];
if ( offset >= _segSize)
{
seg = seg->next;
offset = 0;
}
}
}
return result;
}
//*******************************************************************************************************************
void xbuf::flush()
{
while (_head)
remSeg();
_tail = nullptr;
_offset = 0;
_used = 0;
_free = 0;
}
//*******************************************************************************************************************
void xbuf::addSeg()
{
if (_tail)
{
_tail->next = (xseg*) new uint32_t[_segSize / 4 + 1];
_tail = _tail->next;
}
else
{
_tail = _head = (xseg*) new uint32_t[_segSize / 4 + 1];
}
_tail->next = nullptr;
_free += _segSize;
}
//*******************************************************************************************************************
void xbuf::remSeg()
{
if (_head)
{
xseg *next = _head->next;
delete[] (uint32_t*) _head;
_head = next;
if ( ! _head)
{
_tail = nullptr;
}
}
_offset = 0;
}
-70
View File
@@ -1,70 +0,0 @@
/****************************************************************************************************************************
src_cpp/AsyncHTTPRequest_Debug_Generic.h - 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)
AsyncHTTPRequest_STM32 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/AsyncHTTPRequest_Generic
Licensed under MIT license
Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#pragma once
#ifdef ASYNC_HTTP_DEBUG_PORT
#define A_DBG_PORT ASYNC_HTTP_DEBUG_PORT
#else
#define A_DBG_PORT Serial
#endif
// Change _ASYNC_HTTP_LOGLEVEL_ to set tracing and logging verbosity
// 0: DISABLED: no logging
// 1: ERROR: errors
// 2: WARN: errors and warnings
// 3: INFO: errors, warnings and informational (default)
// 4: DEBUG: errors, warnings, informational and debug
#ifndef _ASYNC_HTTP_LOGLEVEL_
#define _ASYNC_HTTP_LOGLEVEL_ 0
#endif
#define AHTTP_LOGERROR(x) if(_ASYNC_HTTP_LOGLEVEL_>0) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.println(x); }
#define AHTTP_LOGERROR0(x) if(_ASYNC_HTTP_LOGLEVEL_>0) { A_DBG_PORT.print(x); }
#define AHTTP_LOGERROR1(x,y) if(_ASYNC_HTTP_LOGLEVEL_>0) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.println(y); }
#define AHTTP_LOGERROR2(x,y,z) if(_ASYNC_HTTP_LOGLEVEL_>0) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.println(z); }
#define AHTTP_LOGERROR3(x,y,z,w) if(_ASYNC_HTTP_LOGLEVEL_>0) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.print(z); A_DBG_PORT.print(" "); A_DBG_PORT.println(w); }
#define AHTTP_LOGWARN(x) if(_ASYNC_HTTP_LOGLEVEL_>1) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.println(x); }
#define AHTTP_LOGWARN0(x) if(_ASYNC_HTTP_LOGLEVEL_>1) { A_DBG_PORT.print(x); }
#define AHTTP_LOGWARN1(x,y) if(_ASYNC_HTTP_LOGLEVEL_>1) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.println(y); }
#define AHTTP_LOGWARN2(x,y,z) if(_ASYNC_HTTP_LOGLEVEL_>1) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.println(z); }
#define AHTTP_LOGWARN3(x,y,z,w) if(_ASYNC_HTTP_LOGLEVEL_>1) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.print(z); A_DBG_PORT.print(" "); A_DBG_PORT.println(w); }
#define AHTTP_LOGINFO(x) if(_ASYNC_HTTP_LOGLEVEL_>2) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.println(x); }
#define AHTTP_LOGINFO0(x) if(_ASYNC_HTTP_LOGLEVEL_>2) { A_DBG_PORT.print(x); }
#define AHTTP_LOGINFO1(x,y) if(_ASYNC_HTTP_LOGLEVEL_>2) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.println(y); }
#define AHTTP_LOGINFO2(x,y,z) if(_ASYNC_HTTP_LOGLEVEL_>2) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.println(z); }
#define AHTTP_LOGINFO3(x,y,z,w) if(_ASYNC_HTTP_LOGLEVEL_>2) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.print(z); A_DBG_PORT.print(" "); A_DBG_PORT.println(w); }
#define AHTTP_LOGDEBUG(x) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.println(x); }
#define AHTTP_LOGDEBUG0(x) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print(x); }
#define AHTTP_LOGDEBUG1(x,y) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.println(y); }
#define AHTTP_LOGDEBUG2(x,y,z) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.println(z); }
#define AHTTP_LOGDEBUG3(x,y,z,w) if(_ASYNC_HTTP_LOGLEVEL_>3) { A_DBG_PORT.print("[AHTTP] "); A_DBG_PORT.print(x); A_DBG_PORT.print(" "); A_DBG_PORT.print(y); A_DBG_PORT.print(" "); A_DBG_PORT.print(z); A_DBG_PORT.print(" "); A_DBG_PORT.println(w); }
File diff suppressed because it is too large Load Diff
-265
View File
@@ -1,265 +0,0 @@
/****************************************************************************************************************************
src_cpp/AsyncHTTPRequest_Generic.h - 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)
AsyncHTTPRequest_STM32 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/AsyncHTTPRequest_Generic
Licensed under MIT license
Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
#pragma once
#define AsyncHTTPRequest_Generic_version "1.0.0"
#include <Arduino.h>
#include "AsyncHTTPRequest_Debug_Generic.h"
#ifndef DEBUG_IOTA_PORT
#define DEBUG_IOTA_PORT Serial
#endif
#ifdef DEBUG_IOTA_HTTP
#define DEBUG_IOTA_HTTP_SET true
#else
#define DEBUG_IOTA_HTTP_SET false
#endif
#if ESP32
#include <AsyncTCP.h>
#define _lock xSemaphoreTakeRecursive(threadLock,portMAX_DELAY)
#define _unlock xSemaphoreGiveRecursive(threadLock)
#elif ESP8266
#include <ESPAsyncTCP.h>
#define _lock
#define _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) || \
defined(STM32WB) || defined(STM32MP1) )
#include "STM32AsyncTCP.h"
#define _lock
#define _unlock
#endif
#include <pgmspace.h>
#include <utility/xbuf.h>
#define DEBUG_HTTP(format,...) if(_debug){\
DEBUG_IOTA_PORT.printf("Debug(%3ld): ", millis()-_requestStartTime);\
DEBUG_IOTA_PORT.printf_P(PSTR(format),##__VA_ARGS__);}
#define DEFAULT_RX_TIMEOUT 3 // Seconds for timeout
#define HTTPCODE_CONNECTION_REFUSED (-1)
#define HTTPCODE_SEND_HEADER_FAILED (-2)
#define HTTPCODE_SEND_PAYLOAD_FAILED (-3)
#define HTTPCODE_NOT_CONNECTED (-4)
#define HTTPCODE_CONNECTION_LOST (-5)
#define HTTPCODE_NO_STREAM (-6)
#define HTTPCODE_NO_HTTP_SERVER (-7)
#define HTTPCODE_TOO_LESS_RAM (-8)
#define HTTPCODE_ENCODING (-9)
#define HTTPCODE_STREAM_WRITE (-10)
#define HTTPCODE_TIMEOUT (-11)
typedef enum
{
readyStateUnsent = 0, // Client created, open not yet called
readyStateOpened = 1, // open() has been called, connected
readyStateHdrsRecvd = 2, // send() called, response headers available
readyStateLoading = 3, // receiving, partial data available
readyStateDone = 4 // Request complete, all data available.
} reqStates;
class AsyncHTTPRequest
{
struct header
{
header* next;
char* name;
char* value;
header(): next(nullptr), name(nullptr), value(nullptr)
{};
~header()
{
delete[] name;
delete[] value;
delete next;
}
};
struct URL
{
char* scheme;
char* user;
char* pwd;
char* host;
int port;
char* path;
char* query;
char* fragment;
URL(): scheme(nullptr), user(nullptr), pwd(nullptr), host(nullptr),
port(80), path(nullptr), query(nullptr), fragment(nullptr)
{};
~URL()
{
delete[] scheme;
delete[] user;
delete[] pwd;
delete[] host;
delete[] path;
delete[] query;
delete[] fragment;
}
};
typedef std::function<void(void*, AsyncHTTPRequest*, int readyState)> readyStateChangeCB;
typedef std::function<void(void*, AsyncHTTPRequest*, size_t available)> onDataCB;
public:
AsyncHTTPRequest();
~AsyncHTTPRequest();
//External functions in typical order of use:
//__________________________________________________________________________________________________________*/
void setDebug(bool); // Turn debug message on/off
bool debug(); // is debug on or off?
bool open(const char* /*GET/POST*/, const char* URL); // Initiate a request
void onReadyStateChange(readyStateChangeCB, void* arg = 0); // Optional event handler for ready state change
// or you can simply poll readyState()
void setTimeout(int); // overide default timeout (seconds)
void setReqHeader(const char* name, const char* value); // add a request header
void setReqHeader(const char* name, int32_t value); // overload to use integer value
#if (ESP32 || ESP8266)
void setReqHeader(const char* name, const __FlashStringHelper* value);
void setReqHeader(const __FlashStringHelper *name, const char* value);
void setReqHeader(const __FlashStringHelper *name, const __FlashStringHelper* value);
void setReqHeader(const __FlashStringHelper *name, int32_t value);
#endif
bool send(); // Send the request (GET)
bool send(String body); // Send the request (POST)
bool send(const char* body); // Send the request (POST)
bool send(const uint8_t* buffer, size_t len); // Send the request (POST) (binary data?)
bool send(xbuf* body, size_t len); // Send the request (POST) data in an xbuf
void abort(); // Abort the current operation
reqStates readyState(); // Return the ready state
int respHeaderCount(); // Retrieve count of response headers
char* respHeaderName(int index); // Return header name by index
char* respHeaderValue(int index); // Return header value by index
char* respHeaderValue(const char* name); // Return header value by name
bool respHeaderExists(const char* name); // Does header exist by name?
#if (ESP32 || ESP8266)
char* respHeaderValue(const __FlashStringHelper *name);
bool respHeaderExists(const __FlashStringHelper *name);
#endif
String headers(); // Return all headers as String
void onData(onDataCB, void* arg = 0); // Notify when min data is available
size_t available(); // response available
size_t responseLength(); // indicated response length or sum of chunks to date
int responseHTTPcode(); // HTTP response code or (negative) error code
String responseText(); // response (whole* or partial* as string)
size_t responseRead(uint8_t* buffer, size_t len); // Read response into buffer
uint32_t elapsedTime(); // Elapsed time of in progress transaction or last completed (ms)
String version(); // Version of AsyncHTTPRequest
//___________________________________________________________________________________________________________________________________
private:
enum {HTTPmethodGET, HTTPmethodPOST} _HTTPmethod;
reqStates _readyState;
int16_t _HTTPcode; // HTTP response code or (negative) exception code
bool _chunked; // Processing chunked response
bool _debug; // Debug state
uint32_t _timeout; // Default or user overide RxTimeout in seconds
uint32_t _lastActivity; // Time of last activity
uint32_t _requestStartTime; // Time last open() issued
uint32_t _requestEndTime; // Time of last disconnect
URL* _URL; // -> URL data structure
char* _connectedHost; // Host when connected
int _connectedPort; // Port when connected
AsyncClient* _client; // ESPAsyncTCP AsyncClient instance
size_t _contentLength; // content-length header value or sum of chunk headers
size_t _contentRead; // number of bytes retrieved by user since last open()
readyStateChangeCB _readyStateChangeCB; // optional callback for readyState change
void* _readyStateChangeCBarg; // associated user argument
onDataCB _onDataCB; // optional callback when data received
void* _onDataCBarg; // associated user argument
#ifdef ESP32
SemaphoreHandle_t threadLock;
#endif
// request and response String buffers and header list (same queue for request and response).
xbuf* _request; // Tx data buffer
xbuf* _response; // Rx data buffer for headers
xbuf* _chunks; // First stage for chunked response
header* _headers; // request or (readyState > readyStateHdrsRcvd) response headers
// Protected functions
header* _addHeader(const char*, const char*);
header* _getHeader(const char*);
header* _getHeader(int);
bool _buildRequest();
bool _parseURL(const char*);
bool _parseURL(String);
void _processChunks();
bool _connect();
size_t _send();
void _setReadyState(reqStates);
#if (ESP32 || ESP8266)
char* _charstar(const __FlashStringHelper *str);
#endif
// callbacks
void _onConnect(AsyncClient*);
void _onDisconnect(AsyncClient*);
void _onData(void*, size_t);
void _onError(AsyncClient*, int8_t);
void _onPoll(AsyncClient*);
bool _collectHeaders();
};
-148
View File
@@ -1,148 +0,0 @@
/****************************************************************************************************************************
xbuf.h - 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)
AsyncHTTPRequest_STM32 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/AsyncHTTPRequest_Generic
Licensed under MIT license
Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>
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 <https://www.gnu.org/licenses/>.
Version: 1.0.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 14/09/2020 Initial coding to add support to STM32 using built-in Ethernet (Nucleo-144, DISCOVERY, etc).
1.0.1 K Hoang 09/10/2020 Restore cpp code besides Impl.h code.
*****************************************************************************************************************************/
/********************************************************************************************
xbuf is a dynamic buffering system that supports reading and writing much like cbuf.
The class has it's own provision for writing from buffers, Strings and other xbufs
as well as the inherited Print functions.
Rather than use a large contiguous heap allocation, xbuf uses a linked chain of segments
to dynamically grow and shrink with the contents.
There are other benefits as well to using smaller heap allocation units:
1) A buffer can work fine in a fragmented heap environment (admittedly contributing to it)
2) xbuf contents can be copied from one buffer to another without the need for
2x heap during the copy.
The segment size defaults to 64 but can be dynamically set in the constructor at creation.
The inclusion of indexOf and read/peek until functions make it useful for handling
data streams like HTTP, and in fact is why it was created.
NOTE: The size of the indexOf() search string is limited to the segment size.
It could be extended but didn't seem to be a practical consideration.
********************************************************************************************/
#pragma once
#include <Arduino.h>
struct xseg
{
xseg *next;
uint8_t data[];
};
class xbuf: public Print
{
public:
xbuf(const uint16_t segSize = 64);
virtual ~xbuf();
size_t write(const uint8_t);
size_t write(const char*);
size_t write(const uint8_t*, const size_t);
size_t write(xbuf*, const size_t);
size_t write(String);
size_t available();
int indexOf(const char, const size_t begin = 0);
int indexOf(const char*, const size_t begin = 0);
uint8_t read();
size_t read(uint8_t*, size_t);
String readStringUntil(const char);
String readStringUntil(const char*);
String readString(int);
String readString()
{
return readString(available());
}
void flush();
uint8_t peek();
size_t peek(uint8_t*, const size_t);
String peekStringUntil(const char target)
{
return peekString(indexOf(target, 0));
}
String peekStringUntil(const char* target)
{
return peekString(indexOf(target, 0));
}
String peekString()
{
return peekString(_used);
}
String peekString(int);
/* In addition to the above functions,
the following inherited functions from the Print class are available.
size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3)));
size_t printf_P(PGM_P format, ...) __attribute__((format(printf, 2, 3)));
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);
size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);
*/
protected:
xseg *_head;
xseg *_tail;
uint16_t _used;
uint16_t _free;
uint16_t _offset;
uint16_t _segSize;
void addSeg();
void remSeg();
};