Giter Club home page Giter Club logo

khoih-prog / asynchttprequest_generic Goto Github PK

View Code? Open in Web Editor NEW
89.0 6.0 29.0 1.54 MB

Simple Async HTTP Request library, supporting GET, POST, PUT, PATCH, DELETE and HEAD, on top of AsyncTCP libraries, such as AsyncTCP, ESPAsyncTCP, AsyncTCP_STM32, etc.. for ESP32 (including ESP32_S2, ESP32_S3 and ESP32_C3), WT32_ETH01 (ESP32 + LAN8720), ESP8266 (WiFi or W5x00) and currently STM32 with built-in LAN8742A Ethernet.

License: GNU General Public License v3.0

C 44.26% C++ 55.40% Shell 0.33%
esp32 esp8266 stm32 wt32-eth01 async http-client async-http-client stm32f7 wifi ethernet

asynchttprequest_generic's People

Contributors

1618033 avatar khoih-prog avatar per1234 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

asynchttprequest_generic's Issues

HTTPS

Hello.

Does it support HTTPS?

Add support for sending PUT, PATCH, DELETE request

Hello,

thanks for a nice library, good work.

I would be nice to add a support for sending remaining HTTP methods, too.
The requests PUT, PATCH, DELETE are technically the same as POST, they just have a different name.


Arduino IDE version: 1.8.13
ESP32 Core Version 1.0.4
OS: macOS Catalina v10.15.5

Context:

I have tried to send PUT, PATCH and DELETE and it always end up in an endless loop (Guru Meditation Error).

How to reproduce:

  1. load examples/AsyncHTTPRequest_ESP/AsyncHTTPRequest_ESP.ino demo sketch
  2. change GET request (line 108) to POST
    request.open("POST", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
  3. compile and run on esp32 ... code is still working fine
  4. now change it to PUT and compile
    request.open("PUT", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
  5. now it is constantly restarting
    Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.

Full sketch:

This is a full code for testing PUT, PATCH and DELETE methods. Uncommend one line in the end of setup() function

/****************************************************************************************************************************
  AsyncHTTPRequest_ESP.ino - Dead simple AsyncHTTPRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet
  
  For ESP8266, ESP32 and STM32 with built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc)
  
  AsyncHTTPRequest_Generic is a library for the ESP8266, ESP32 and currently STM32 run built-in Ethernet WebServer
  
  Based on and modified from asyncHTTPrequest Library (https://github.com/boblemaire/asyncHTTPrequest)
  
  Built by Khoi Hoang https://github.com/khoih-prog/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.2
  
  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.
  1.0.2    K Hoang     09/11/2020 Make Mutex Lock and delete more reliable and error-proof
 *****************************************************************************************************************************/
//************************************************************************************************************
//
// There are scores of ways to use AsyncHTTPRequest.  The important thing to keep in mind is that
// it is asynchronous and just like in JavaScript, everything is event driven.  You will have some
// reason to initiate an asynchronous HTTP request in your program, but then sending the request
// headers and payload, gathering the response headers and any payload, and processing
// of that response, can (and probably should) all be done asynchronously.
//
// In this example, a Ticker function is setup to fire every 300 seconds to initiate a request.
// Everything is handled in AsyncHTTPRequest without blocking.
// The callback onReadyStateChange is made progressively and like most JS scripts, we look for
// readyState == 4 (complete) here.  At that time the response is retrieved and printed.
//
// Note that there is no code in loop().  A code entered into loop would run oblivious to
// the ongoing HTTP requests.  The Ticker could be removed and periodic calls to sendRequest()
// could be made in loop(), resulting in the same asynchronous handling.
//
// For demo purposes, debug is turned on for handling of the first request.  These are the
// events that are being handled in AsyncHTTPRequest.  They all begin with Debug(nnn) where
// nnn is the elapsed time in milliseconds since the transaction was started.
//
//*************************************************************************************************************

#if !( defined(ESP8266) ||  defined(ESP32) )
  #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting.
#endif

// Level from 0-4
#define ASYNC_HTTP_DEBUG_PORT     Serial
#define _ASYNC_HTTP_LOGLEVEL_     4    

// 300s = 5 minutes to not flooding
#define HTTP_REQUEST_INTERVAL     30  //300

int status;     // the Wifi radio's status

const char* ssid        = "77002";
const char* password    = "nob48.jute.netstone";

#if (ESP8266)
  #include <ESP8266WiFi.h>
#elif (ESP32)
  #include <WiFi.h>
#endif

#include <AsyncHTTPRequest_Generic.h>           // https://github.com/khoih-prog/AsyncHTTPRequest_Generic
#include <Ticker.h>

AsyncHTTPRequest request;
Ticker ticker;

// GET REQUEST ARE WORKING FINE
void sendGetRequest() 
{
  Serial.println("Sending GET request...");
  
  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    // GET IS WORKING CORRECLY
    request.open("GET", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
    request.send();
  }
  else
  {
    Serial.println("Can't send request");
  }
}

// POST REQUESTS ARE WORKING FINE
void sendPostRequest() 
{
  Serial.println("Sending POST request...");
  
  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    request.open("POST", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
    request.send("dummy request body");
  }
  else
  {
    Serial.println("Can't send request");
  }
}

// PUT REQUESTS END UP IN Guru Meditation Error
void sendPutRequest() 
{
  Serial.println("Sending PUT request...");
  
  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    request.open("PUT", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
    request.send("dummy request body");
  }
  else
  {
    Serial.println("Can't send request");
  }
}

// PATCH REQUESTS END UP IN Guru Meditation Error
void sendPatchRequest() 
{
  Serial.println("Sending PATCH request...");
  
  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    request.open("PATCH", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
    request.send("dummy request body");
  }
  else
  {
    Serial.println("Can't send request");
  }
}

// DELETE REQUESTS END UP IN Guru Meditation Error
void sendDeleteRequest() 
{
  Serial.println("Sending DELETE request...");
  
  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    request.open("DELETE", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
    request.send("dummy request body");
  }
  else
  {
    Serial.println("Can't send request");
  }
}

void requestCB(void* optParm, AsyncHTTPRequest* request, int readyState) 
{
  if (readyState == readyStateDone) 
  {
    Serial.println("\n**************************************");
    Serial.println(request->responseText());
    Serial.println("**************************************");
    
    //request->setDebug(false);
  }
}

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  while (!Serial);
  
  Serial.println("\nStarting AsyncHTTPRequest_ESP using " + String(ARDUINO_BOARD));

  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);
  
  Serial.println("Connecting to WiFi SSID: " + String(ssid));

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.print(F("\nHTTP WebServer is @ IP : "));
  Serial.println(WiFi.localIP());
 
  request.setDebug(true);
  
  request.onReadyStateChange(requestCB);
  //ticker.attach(HTTP_REQUEST_INTERVAL, sendGetRequest);
  
  // Uncomment one
  //sendGetRequest(); // works correctly
  //sendPostRequest(); // works correctly
  //sendPutRequest(); // Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
  sendPatchRequest(); // Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
  //sendDeleteRequest(); // Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
}

void loop()
{ 
}

Thank you

Pushover https post request

Hi, I have read all the information regarding https so I know that it is not currently possible to implement it on esp8266. Unfortunately the Pushover service only accepts POST to https://api.pushover.net/1/messages.json. One library for ESP8266 solves this on the client with setInsecure(). Would it not be possible to implement this as well?
Thank you

setTimeout() hasn't any effect

Describe the bug

If address is a normal address e.g.: http://exampleasynchttp.com/index.html, it gives immediately a "-4" code if not available (good).
But if the address is a ip address like http://192.168.0.44/index.html (this host is down) the timeout takes always about 18 seconds no matter how many seconds you set (not good).

Steps to Reproduce

Copy code from:
https://gist.github.com/miwied/f56aca82c4f976f448dde1a8da051650
Flash it to esp32 and run.

Expected behavior

The request should time out after 3 seconds.

Actual behavior

The request is always timing out after 18 seconds (no matter what you pass into the setTimeout() method).

Additional Information

The _onPoll(AsyncClient *client) method, where the timeout is queried, is never called.

Compile error with ESP8266 and Platformio

Describe the bug

I created a new project in platformio (Win10) (platform ESP8266 board D1) and added the library to the project. When compiling I get the following error:

compiling .pio\build\d1\lib6a0\STM32Ethernet\Dhcp.cpp.o
Compiling .pio\build\d1\lib6a0\STM32Ethernet\Dns.cpp.o
Compiling .pio\build\d1\lib6a0\STM32Ethernet\EthernetClient.cpp.o
Compiling .pio\build\d1\lib6a0\STM32Ethernet\EthernetServer.cpp.o
In file included from .pio\libdeps\d1\STM32Ethernet\src/lwipopts.h:17:0,
                 from .pio\libdeps\d1\STM32duino LwIP\src/lwip/opt.h:51,
                 from .pio\libdeps\d1\STM32duino LwIP\src/lwip/init.h:40,
                 from <userdir>\platformio\packages\[email protected]\cores\esp8266/IPAddress.h:27,
                 from .pio\libdeps\d1\STM32Ethernet\src\STM32Ethernet.h:5,
                 from .pio\libdeps\d1\STM32Ethernet\src\EthernetServer.cpp:5:
.pio\libdeps\d1\STM32Ethernet\src/lwipopts_default.h:89:0: warning: "TCP_MSS" redefined [enabled by default]
 #define TCP_MSS                 (1500 - 40)   /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */
 ^
<command-line>:0:0: note: this is the location of the previous definition
In file included from .pio\libdeps\d1\STM32Ethernet\src/lwipopts.h:17:0,
                 from .pio\libdeps\d1\STM32duino LwIP\src/lwip/opt.h:51,
                 from .pio\libdeps\d1\STM32duino LwIP\src/lwip/init.h:40,
                 from <userdir>platformio\packages\[email protected]\cores\esp8266/IPAddress.h:27,
                 from <userdir>platformio\packages\[email protected]\cores\esp8266/Udp.h:39,
                 from .pio\libdeps\d1\STM32Ethernet\src\EthernetUdp.h:40,
                 from .pio\libdeps\d1\STM32Ethernet\src\Dns.cpp:5:
.pio\libdeps\d1\STM32Ethernet\src/lwipopts_default.h:89:0: warning: "TCP_MSS" redefined [enabled by default]
 #define TCP_MSS                 (1500 - 40)   /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */
 ^
<command-line>:0:0: note: this is the location of the previous definition
In file included from .pio\libdeps\d1\STM32Ethernet\src/lwipopts.h:17:0,
                 from .pio\libdeps\d1\STM32duino LwIP\src/lwip/opt.h:51,
                 from .pio\libdeps\d1\STM32duino LwIP\src/lwip/init.h:40,
                 from <userdir>.platformio\packages\[email protected]\cores\esp8266/IPAddress.h:27,
                 from <userdir>.platformio\packages\[email protected]\cores\esp8266/Udp.h:39,
                 from .pio\libdeps\d1\STM32Ethernet\src\EthernetUdp.h:40,
                 from .pio\libdeps\d1\STM32Ethernet\src\Dhcp.h:7,
                 from .pio\libdeps\d1\STM32Ethernet\src\Dhcp.cpp:6:
.pio\libdeps\d1\STM32Ethernet\src/lwipopts_default.h:89:0: warning: "TCP_MSS" redefined [enabled by default]
 #define TCP_MSS                 (1500 - 40)   /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */
 ^
<command-line>:0:0: note: this is the location of the previous definition
In file included from .pio\libdeps\d1\STM32Ethernet\src\EthernetUdp.h:43:0,
                 from .pio\libdeps\d1\STM32Ethernet\src\Dhcp.h:7,
                 from .pio\libdeps\d1\STM32Ethernet\src\Dhcp.cpp:6:
.pio\libdeps\d1\STM32Ethernet\src\utility/stm32_eth.h:42:23: fatal error: stm32_def.h: No such file or directory

Kind regards
Stefan

ESP8266 issue platformio

Hi, thanks for your work!
I have an issue trying to compile for ESP8266

This error appear:
.pio/libdeps/nodemcuv2/STM32Ethernet/src/utility/stm32_eth.h:42:23: fatal error: stm32_def.h: No such file or directory

lib_deps =
khoih.prog/AsyncHTTPRequest_Generic@^1.1.5

In main.cpp
AsyncHTTPRequest request;

Any idea? Why ESP32 desp for ESP8266?
Many thanks and best regards.

No HTTPS Support!

Description
After two hours of rectifying my own APIs i found out that no mater what i do to my API(s) the issue is with this library itself. i.e. It can't hit anything that contains https!
A clear and concise description of what the bug is.
As long as i put http link it works great. But as soon as we go https, library says, can't send bad request.

Steps to Reproduce

void sendRequest() { static bool requestOpenResult; if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone) { requestOpenResult = request.open("GET", "https://api.openweathermap.org/data/2.5/onecall?lat=-24.32&lon=-46.9983"); if (requestOpenResult){request.send();} else{Serial.println(F("Can't send bad request"));} }else{Serial.println(F("Can't send request"));} }

reponse --
Can't send bad request
Can't send bad request
Can't send bad request
Can't send bad request

  • Arduino IDE version 1.8.19
  • ESP32
  • Trying to get data from api which uses https (SSL)

'Connection' header expects 'disconnect' instead 'close' ?

Hi,
I'm using your library to connect to me-no-dev ESPAsyncWebServer to make a POST request with body.
I had some troubles to make it work beacuse ESPAsyncWebServer accepted only first call but second was not sent because requestState returns 1.
Reading the source code I found that the Connection header is compared to have 'disconnect' value to disconnect TCP connection. So I fixed it to 'close' string and it started to work.
As https://tools.ietf.org/html/rfc2616#page-117 Connection should have 'close' value.
Could you explain why do you use 'disconnect'?
If this is bug could you fix it?

fixed line by me:
if (connectionHdr && (strcasecmp_P(connectionHdr, PSTR("close")) == 0))

Second discovered problem is debugging received data.
Data debug does not pass buffer data length to debug macro and data Vbuf is not null terminated so I read on screen the received body response and some garbage.

BTW I like your library because it support POST and other not GET methods. Thank you very much.

LiquidCrystal_I2C lcd not printing correctly in requestCB async method

When i am printing something on a 16x2 LCD in sendRequest() method it is working correctly but when i am printing inside aysnc method requestCB() lcd not printing correctly even lcd.clear() is also not clearing characters on screen.

I am using Esp32 board + LiquidCrystal_I2C to print http request data on LCD. It is printing something different char on screen.

#include<LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

`void requestCB(void* optParm, AsyncHTTPRequest* request, int readyState) 
{
  (void) optParm;
  
  if (readyState == readyStateDone) 
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SUCCESS HTTP");

    Serial.println(F("\n**************************************"));
    Serial.println(request->responseText());
    Serial.println(F("**************************************"));
    
    request->setDebug(false);
  }
}

Other methods are printing correctly on LCD. Any

POSTing data appears to just append to url

Describe the bug

Using method of POST based on example appears to just still append variables to URL.
Using the examples:
String server_url="http://myserver.domain/posturl.php";
String paramdata = "variable1=value&variable2=value";
requestOpenResult = request.open("POST", (server_url + "?" + paramdata).c_str());

Steps to Reproduce

Above code, checking the server it shows the data being pushed on the url:
x.x.x.x - - [08/Apr/2021:13:47:27 +0100] "POST /posturl.php?variable1=value&variable2=value" HTTP/1.1" 200 147 "-" "-"

Expected behavior

Should see just the POST itself and no parameters on the url (a-la-get style):
x.x.x.x - - [08/Apr/2021:13:47:27 +0100] "POST /posturl.php" HTTP/1.1" 200 147 "-" "-"

Information

Please ensure to specify the following:

  • Arduino IDE version1.8.12
  • ESP8266
  • AsyncHTTPRequest_Generic version 1.1.5

I'm unsure if this is an error in the examples or if it's not possible to POST in this way.

Clarification on the license?

This library is obviously a fork of https://github.com/boblemaire/asyncHTTPrequest. While I much prefer the MIT license used in this project, it is not compatible with GPLv3 used in the original repository. According to the GPL licenses, any derivatives need to be licensed with the same license.

Could this issue be clarified? Did the authors of the original library grant a permission for relicensing? If not, I believe this repository should be relicensed with GPLv3.

Send PUT request

Sending request.open("PUT", "http://domain.com/api/endpoint/"); currently raises Guru Meditation Error.

How to send PUT request? It is technically no different from POST, except its name.

Http GET polling causes crash when host disconnected

A follow up to a previous issue since I am seeing the same issue.

Bug report is as follows:

Describe the bug

Multiple requests to an internal NodeJS server when the server is disconnected causes a crash.

Steps to Reproduce

Use the example "AsyncHTTPRequest_ESP.ino"

Only changes in this sketch are as follows:
Line 49 #define ASYNC_HTTP_LOGLEVEL 4
Line 52 #define HTTP_REQUEST_INTERVAL 10
Line 59 and 60 add SSID and Password
Line 102 change to requestOpenResult = request.open("GET", "http://192.168.59.188/ping.htm");

Expected behavior

When the target is disconnected an HTTP error code should be returned after a very short timeout (ideally controlled by setTimeout() or the like).

Actual behavior

When http://192.168.59.188/ping.htm is available everything works as expected (the ping page just generates an OK) which is printed by the Sketch. However if you connect the ethernet cable, requests receive no response (as expected). However, after several requests (typically 3) the ESP restarts,

Please ensure to specify the following:

  • Arduino IDE version (e.g. 1.8.13) or Platform.io version
    Arduino IDE 1.8.13
  • ESP8266,ESP32 or STM32 Core Version (e.g. ESP8266 core v2.7.4, ESP32 v1.0.5 or STM32 v1.9.0)
    ESP8266 Core 3.0.2

Here is the debug output:

AsyncHTTPRequest @ IP : 192.168.1.23
[AHTTP] open( GET , url = http://192.168.1.21/ping.htm
[AHTTP] _parseURL(): scheme+host HTTP:// 192.168.1.21
[AHTTP] _parseURL(): port+path+query 80 /ping.htm
[AHTTP] open: conneting to hostname = 192.168.1.21:80
[AHTTP] _connect()
[AHTTP] send()
[AHTTP] _buildRequest()
[AHTTP] _HTTPmethod = 0
[AHTTP] GET /ping.htm HTTP/1.1

[AHTTP] host : 192.168.1.21:80

[AHTTP] _send(), _request->available = 50
[AHTTP] *can't send
[AHTTP] open( GET , url = http://192.168.1.21/ping.htm
[AHTTP] _parseURL(): scheme+host HTTP:// 192.168.1.21
[AHTTP] _parseURL(): port+path+query 80 /ping.htm
[AHTTP] open: conneting to hostname = 192.168.1.21:80
[AHTTP] _connect()
[AHTTP] send()
[AHTTP] _buildRequest()
[AHTTP] _HTTPmethod = 0
[AHTTP] GET /ping.htm HTTP/1.1

[AHTTP] host : 192.168.1.21:80

[AHTTP] _send(), _request->available = 50
[AHTTP] *can't send
H[AHTTP] open( GET , url = http://192.168.1.21/ping.htm
[AHTTP] _parseURL(): scheme+host HTTP:// 192.168.1.21
[AHTTP] _parseURL(): port+path+query 80 /ping.htm
[AHTTP] open: conneting to hostname = 192.168.1.21:80
[AHTTP] _connect()
[AHTTP] send()
[AHTTP] _buildRequest()
[AHTTP] _HTTPmethod = 0
[AHTTP] GET /ping.htm HTTP/1.1

[AHTTP] host : 192.168.1.21:80

[AHTTP] _send(), _request->available = 50
[AHTTP] *can't send
H[AHTTP] open( GET , url = http://192.168.1.21/ping.htm
[AHTTP] _parseURL(): scheme+host HTTP:// 192.168.1.21
[AHTTP] _parseURL(): port+path+query 80 /ping.htm
[AHTTP] open: conneting to hostname = 192.168.1.21:80
[AHTTP] _connect()
[AHTTP] send()
[AHTTP] _buildRequest()
[AHTTP] _HTTPmethod = 0
[AHTTP] GET /ping.htm HTTP/1.1

[AHTTP] host : 192.168.1.21:80

[AHTTP] _send(), _request->available = 50
[AHTTP] *can't send
H[AHTTP] _onError handler error = -13
[AHTTP]
_onDisconnect handler
[AHTTP] _setReadyState : 4


[AHTTP] responseText()
[AHTTP] responseText() no data


--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Note: It takes approximately 30 seconds from the first [AHTTP] *can't send till the _onDisconnect handler fires. The reset happens at the time the next request would happen after the _onDisconnect handler fires.

Thanks for your help

Originally posted by @andrewk123 in #16 (comment)

Redundant code

AsyncHTTPRequest_ESP_Multi/AsyncHTTPRequest_ESP_Multi.ino

It looks like the for loop is unnecessary as reqCount[..] is subsequentely overwritten.

void sendRequests() //NUM_DIFFERENT_SITES == 2
{
for (int index = 0; index < NUM_DIFFERENT_SITES; index++)
{
reqCount[index] = 2;
}
reqCount[0] = NUM_ENTRIES_SITE_0; //that is == 2
reqCount[1] = NUM_ENTRIES_SITE_1; //that is == 1
}

Release 1.9 breakes previously running code

On ESP8266:

After updating from 1.8.2 to 1.9.1 my code shows some unexpected behaviour:
The code compilies and runs without crashing but some sequencing seems to be messed up. The request callback seems to be called before sending and the readyState is set to readyStateDone incorrecty. Later the request callback is called again with the actual http request, which seems to have worked annyway. I am guessing the readyState is set incorrecty to readyStateDone somewhere early in the toolchain, which seems to trigger unexpected behaviour.

Callback behaviour is buggy (ESP8266)

I'm on the latest version of the library.
My scenario: every 10 seconds I want to make a POST call to a server containing a JSON body.

The full testing code is available here: https://gist.github.com/dirkvranckaert/93ca29597a9f6732465d23cb9e2b62b3

Here is the log of what I observe:

11:41:06.936 -> ****************************************
11:41:07.010 -> ****************************************
11:41:07.010 -> ****************************************
11:41:07.087 -> 
11:41:07.087 -> 
11:41:07.087 -> Sending new request...
11:41:07.087 -> Network result... 
11:41:07.125 -> NOT_CONNECTED
11:41:07.125 -> -4
11:41:07.125 -> Network result callback done!
11:41:07.162 -> Network result... 
11:41:07.200 -> HTTP OK
11:41:07.200 -> 200
11:41:07.200 -> Network result callback done!
11:41:17.048 -> 
11:41:17.048 -> 
11:41:17.048 -> ****************************************
11:41:17.085 -> ****************************************
11:41:17.119 -> ****************************************
11:41:17.194 -> 
11:41:17.194 -> 
11:41:17.194 -> Sending new request...
11:41:17.339 -> Network result... 
11:41:17.339 -> Bad Request
11:41:17.378 -> 400
11:41:17.378 -> Network result callback done!
11:41:27.091 -> 

So my observation is:

  1. The first network call is executed and reports twice in the callback, first with HTTPCODE_NOT_CONNECTED followed by the regular network response. That seems bizar to me that I first get the not connected followed by a proper response... I'm not sure if that's ok and if I can safely ignore the not connected...
  2. Then we fire the second network call (same call just 10 minutes after), that call is started with success, however it immediately reports back with an HTTP error code 400 (I check my server and the request never arrived so it's definitely a client thing).

This sequence keeps repeating itself exactly like this, calls 3, 5, 7,... are like call 1. The followup calls 4, 6,, 8,... are always like call 2!

In my opinion both are an issue.

Can you please have a look?

Request Large Data is an issue?

Hi, Congratulation for this library.
I would like to check if is there a way to increase the buffer to receive large data (considering that this is the cause ;o) )
Currently I am running the example : AsyncHTTPRequest_ESP.ino

I have replaced the following data:
From:
requestOpenResult = request.open("GET", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");

To:
requestOpenResult = request.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=Peruibe,br&appid=36768002e8b918d8a071d6c331ab713c&q");

This works fine, but when I try to get a full json file in this one:
requestOpenResult = request.open("GET", "https://api.openweathermap.org/data/2.5/onecall?lat=-24.32&lon=-46.9983&exclude={part}&appid=36768002e8b918d8a071d6c331ab713c&q");

No data is comming and I it's triggered the message from that part of the code.
Serial.println("Can't send bad request");

Thanks!

Edson

AsyncHTTPRequest_Generic with. AsyncMqttClient, ESP8266 reboots

I tried to use AsyncHTTP req when i receive message from MQTT topic (using AsyncMqttClient), with code:

  AsyncHTTPRequest request;
  request.onReadyStateChange([](void* optParm, AsyncHTTPRequest* request, int readyState) {
    Serial.println(readyState);
    if (readyState == readyStateDone) {
      Serial.println("\n**************************************");
      Serial.println(request->responseText());
      Serial.println("**************************************");
    }
  });
  request.open("GET", "http://worldtimeapi.org/api/timezone/Europe/Bratislava");
  request.send();

inside void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) of AsyncMQTT client.
When i send message to mqtt topic and received on ESP, board reboots after while it reaches AsyncHttp client

21:30:34.913 -> MQTT | Receive handler:
21:30:34.913 -> /ping
21:30:34.913 -> {"from":"tower","msg":"are u alive?"}aop⸮�
21:30:42.180 -> 
21:30:42.180 ->  ets Jan  8 2013,rst cause:4, boot mode:(3,6)
21:30:42.180 -> 
21:30:42.180 -> wdt reset
21:30:42.180 -> load 0x4010f000, len 1384, room 16 
21:30:42.180 -> tail 8
21:30:42.180 -> chksum 0x2d
21:30:42.180 -> csum 0x2d
21:30:42.180 -> vbc204a9b
21:30:42.180 -> ~ld

Is this client compatible and can it be used alongside with AsyncMqttClient ?

Exception cause 28 in open request

From my production devices from time to time I gather a crash with exception cause 28 (LoadProhibitedCause, so basically a NPE) with the final traces within this library.

Restart reason: 2
Exception cause: 28

0x40206b9d: AsyncHTTPRequest::open(char const*, char const*) at /Users/xyz/Documents/Arduino/libraries/AsyncHTTPRequest_Generic/src/AsyncHTTPRequest_Impl_Generic.h:556
 (inlined by) AsyncHTTPRequest::open(char const*, char const*) at /Users/xyz/Documents/Arduino/libraries/AsyncHTTPRequest_Generic/src/AsyncHTTPRequest_Impl_Generic.h:490

After checking the library locally the error is on this line:
Screenshot 2022-11-18 at 07 09 51

My initialisation code for the open call looks like this:

AsyncHTTPRequest request;
const String HOST = "http://api.myserver.com";
const String BASE_URL = "/v1";

void executeCall() {
  request.setDebug(DEBUG);
  request.onReadyStateChange(handlePostResult);
  String urlMethod = "ping";
  String url = BASE_URL + "/" + urlMethod;
  String fullUrl = HOST + url;
  request.open("POST", fullUrl.c_str());
}

The error is not appearing often, just from time to time. I also cannot reproduce so far locally. But I wonder if sometimes the c_str() could give an empty/false result making the library crash...?!

The error has been installed like this because my production builds are generated with arduino-cli:

arduino-cli lib install --git-url https://github.com/khoih-prog/AsyncHTTPRequest_Generic.git

The version is 1.9.1.

Any other ideas we might be able to investigate?
This is happening in production, I could roll out a new build with a new version, but result won't be seen very fast off course...

HTTPS Support

hello
i think this does not handle https

if (url.substring(0, 7).equalsIgnoreCase("HTTP://"))
{
hostBeg += 7;
}
else if (url.substring(0, 8).equalsIgnoreCase("HTTPS://"))
{
return false;
}

for a project i need https badly can you help

Unable to resolve Multiple Definitions issue

Hello, I am trying to get this library to compile, but I am encountering the multiple definitions linker issue that is mentioned in the documentation. I am having a bit of trouble with the specified workaround.

As far as I can follow, the instructions are:

  1. Rename the src folder containing nothing but .h files to src_h
  2. Rename the src_cpp folder to src

The issue is that the library seems to already have a folder called src_h, which seems to be a duplicate of src.

I have tried simply deleting the src folder and renaming src_cpp, but that results in the following error:
fatal error: AsyncHTTPRequest_Generic.h: No such file or directory #include <AsyncHTTPRequest_Generic.h> ^

Attached is a screenshot of the folders I have.
Screen Shot 2020-12-29 at 15 08 50

Any advice on how to fix this would be greatly appreciated!

Host/Headers not always sent with 1.10.1

Hi
today I updated your library to 1.10.1 and now I spot an issue:

every second call seems to miss header informations, my server returns back:
<h1>Bad Message 400</h1><pre>reason: No Host</pre>

User @dirkvranckaert was already mentioning the same on issue #43, but I can't see if he was having that issue with 1.10.1 or 1.9.1. I did not have the issue with 1.9.1 (but the buggy callback behaviour instead).
#43 (comment)

Unfortunately I struggle to enable debugging, possibly it can be reproduced with the example provided with #43.

I use an ESP32 and the endpoint is an IP-address (no DNS), just in case that might matter. If you need more details, please let me know.

compatibility with ESPAsyncWebServer

Hi,

Please forgive me if it's an easy question. I'm a casual programmer.

I'm trying to use your library and ESPAsyncWebServer library https://github.com/me-no-dev/ESPAsyncWebServer. I've got a compilation error regarding _lock value (which is defined in both project).

I'm trying to understand what this variable is used for in your library but I can't find out. Is there a way to rename/bypass this and getting the two library working together?

Request will get stuck in readyStateOpened after 25 or more successful requests

I have a ESP32-WROOM running this library using the Arduino IDE. This device pings a server every 5 minutes to pull down some new data. I followed an example that works great. The problem is that after anywhere between 10-100 good requests request.readyState() continually says it is in readyStateOpened. This hangs up all future calls and the application is stuck.

I sadly cannot consistently reproduce this, so I can't offer much more details.

My question is why would this happen in general? Is there not a timeout to force it out of this state if there is an issue? Is there anything I can call to completely reset the request module so that I can at least begin using it again? I have tried request.abort() and it doesn't affect the readyState.

Thanks for the help!

HTTPS not supported?

ESP32 crashes when calling a "https://" url. This is 100% replicable on my ESP32 from the provided example: try changing the toronto.txt to an https address and the below issue happens. Since I needed to use this for REST API calls, SSL is required since I need to pass API keys. Here is what happens when I try to call GET on an https address:

Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.
After a bit of googling, I found this happens when there is some sort of null pointer access.
After decoding the backtrace:

0x400d1a59: xbuf::write(char const*) at C:\Users\User\Documents\Arduino\libraries\AsyncHTTPRequest_Generic\src/utility/xbuf_Impl.h line 50 0x400d239a: AsyncHTTPRequest::_buildRequest() at C:\Users\User\Documents\Arduino\libraries\AsyncHTTPRequest_Generic\src/AsyncHTTPRequest_Impl_Generic.h line 527 0x400d24c9: AsyncHTTPRequest::send() at C:\Users\User\Documents\Arduino\libraries\AsyncHTTPRequest_Generic\src/AsyncHTTPRequest_Impl_Generic.h line 156 0x400d2ecb: sendRequest() at C:\Users\User\Desktop\RemoteJi/b_firebaseHandler.ino line 24

Rapid http get polling causes crash when host disconnected

Hi, I'm polling an energy meter with your library, and it works fine, however when I disconnect the host device the timeout mechanism doesn't seem te work and the ESP32 crashes

I used the 'assynchttprequestESP' with my host (energy meter) example, changed the request frequency to 2s, and tried to set the timeout to 1s by '#define DEFAULT_RX_TIMEOUT 1 // Seconds for timeout '

Timeout doesn't seem to do it's job, and also troubling is that it goes through the callbackhandler at some time before crashing and writes false values to my variables.

Am I missing something?

Help with domoticz

hello I try to send sensor values ​​on a home automation server (Domoticz) but always receive a bad request response while the same url in a browser works. Could you help me ?
My code :

static bool requestOpenResult;
  if (reqdom.readyState() == readyStateUnsent || reqdom.readyState() == readyStateDone)
  {
    requestOpenResult = reqdom.open("GET", "http://192.168.1.252:8080/json.htm?type=command&param=udevice&idx=308&nvalue=0&svalue=21.0");

    if (requestOpenResult)
    {
      // Only send() if open() returns true, or crash
      reqdom.send();
    }
    else
    {
      Serial.println(F("Can't send bad request"));
    }
  }
  else
  {
    Serial.println(F("Can't send request"));
  }

Debug :

16:57:00.829 -> Starting AsyncHTTPRequest_ESP using 
16:57:03.427 -> [AHTTP] setDebug( on ) version AsyncHTTPRequest_Generic v1.8.1
16:57:03.427 -> [AHTTP] setDebug( on ) version AsyncHTTPRequest_Generic v1.8.1
16:57:03.427 -> [AHTTP] open( GET , url = http://192.168.1.252:8080/json.htm?type=command&param=udevice&idx=308&nvalue=0&svalue=21.0
16:57:03.460 -> [AHTTP] _parseURL(): scheme+host HTTP:// 192.168.1.252
16:57:03.460 -> [AHTTP] _parseURL(): port+path+query 8080 /json.htm ?type=command&param=udevice&idx=308&nvalue=0&svalue=21.0
16:57:03.460 -> [AHTTP] open: conneting to hostname = 192.168.1.252:8080
16:57:03.460 -> [AHTTP] _connect()
16:57:03.460 -> [AHTTP] send()
16:57:03.460 -> [AHTTP] _buildRequest()
16:57:03.460 -> [AHTTP] _HTTPmethod = 0
16:57:03.494 -> [AHTTP] GET  /json.htm ?type=command&param=udevice&idx=308&nvalue=0&svalue=21.0  HTTP/1.1
16:57:03.494 -> 
16:57:03.494 -> [AHTTP] host : 192.168.1.252:8080 
16:57:03.494 -> 
16:57:03.494 -> [AHTTP] _send(), _request->available = 107
16:57:03.494 -> [AHTTP] !connected
16:57:03.532 -> [AHTTP] _onConnect handler
16:57:03.532 -> [AHTTP] _setReadyState : 1
16:57:03.532 -> [AHTTP] _send(), _request->available = 107
16:57:03.532 -> [AHTTP] *send 107
16:57:03.532 -> [AHTTP] _onData handler HTTP/1.1 400 Bad Request
16:57:03.532 -> Content-Length: 89
16:57:03.532 -> Content-Type: text/html;charset=UTF-8
16:57:03.532 -> 
16:57:03.532 -> <html><head><title>Bad Request</title></head><body><h1>400 Bad Request</h1></body></html> , len = 176
16:57:03.532 -> [AHTTP] _collectHeaders()
16:57:03.532 -> [AHTTP] xbuf::readString: Reserved size =  27
16:57:03.565 -> [AHTTP] xbuf::readString: Reserved size =  21
16:57:03.565 -> [AHTTP] xbuf::readString: Reserved size =  40
16:57:03.565 -> [AHTTP] xbuf::readString: Reserved size =  3
16:57:03.565 -> [AHTTP] _setReadyState : 2
16:57:03.565 -> [AHTTP] _setReadyState : 3
16:57:03.565 -> [AHTTP] *all data received - no disconnect
16:57:03.565 -> [AHTTP] _setReadyState : 4
16:57:03.565 -> 
16:57:03.565 -> **************reqdomCB*****************
16:57:03.565 -> [AHTTP] responseText()
16:57:03.565 -> [AHTTP] xbuf::readString: Reserved size =  90
16:57:03.599 -> [AHTTP] responseText(char) <html><head><title>Bad Request</title></head><body><h1>400 Bad Request</h1></body></html> , avail = 89
16:57:03.599 -> <html><head><title>Bad Request</title></head><body><h1>400 Bad Request</h1></body></html>
16:57:03.599 -> **************reqdomCB*****************
16:57:03.599 -> [AHTTP] 
16:57:03.599 -> _onDisconnect handler
16:57:03.599 -> [AHTTP] _HTTPcode =  400

Compilation for ESP32 in PIO requests STM32 framework files?

Hi, just added the library via platformio.ini, but i guess it is failing to determine the board i am using, as it is requesting some STM32 Ethernet headers, which i do not have and do not plan to install.

Is it strictly neccesary to download STM32 platform?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.