Skip to content

ESP32 HTTPClient request times out. #3589

@pratikguru

Description

@pratikguru

Hardware:

Board: ESP32 Dev Module
Core Installation version: ?1.0.0? ?1.0.1-rc4? ?1.0.1? ?1.0.1-git? ?1.0.2? ?1.0.3?
IDE name: ?Arduino IDE?
Flash Frequency: ?40Mhz?
PSRAM enabled: yes
Upload Speed: 115200
Computer OS: Windows 10

Description:

I've set up a simple HTTP client-server model that sends GET and POST requests. The clients send's a GET request and the server seems to receive it ( Confirming since the handler prints a message. ), but the server fails to send a response and the client goes into a timeout.

The below sketches of code depict the issue with the debug outputs.

#include <WiFiClient.h>
#include <ESPmDNS.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <ArduinoJson.h>

long long timer;
WiFiMulti   wifiMulti; 
const char* ssid     = "API2";
const char* password = "lawl123456";
const char* host     = "192.168.4.1";
int         port     = 2424;
void setup() {
  Serial.begin(115200);
}

void scanNetwork() {
  // A function for scanning the network for the best suitable network to connect too.
  WiFi.disconnect();
  WiFi.begin( ssid, password );
  while( WiFi.status() != WL_CONNECTED ) {
    Serial.print( "." );
    delay( 150 );
  }
  Serial.println();
}

void loop() {
    int disconnectCounter = 0;
    while( 1 ) {
      if ( (long long)millis() - (long long)timer >= 5000 ) {
       timer = millis();
       if( WiFi.status() != WL_CONNECTED ) {
        scanNetwork();
       }

        
       if( (WiFi.status() == WL_CONNECTED) ) {
        WiFiClient txClient;
        if( !txClient.connect(host, port) ){
            Serial.println( "Connection error" );
        }
        else {
          HTTPClient httpClient;
          
          httpClient.begin( "http://192.168.4.1:2424/incoming" );
          httpClient.addHeader("Content-Type","text/plain");
          httpClient.setTimeout( 5000 ); 
          //Serial.println( httpClient.GET() );
          Serial.println(httpClient.POST("{\"device_type\":\"beacon\", \"rssi\":\"34\", \"person\":\"me\", \"magno\":\"45db\"}"));
          Serial.println( httpClient.getString() );
          
          httpClient.end();
      }
    }
    else {
      disconnectCounter++;
      if ( disconnectCounter >= 5 ) {
        Serial.println( "Restarting chip" );
        ESP.restart();
      }
      Serial.println( "Restarting in: " + String(5 - disconnectCounter) );
    }
   }
  }
}

Above is the client code.

Below is the server code.

#include <WiFiClient.h>
#include <ESPmDNS.h>
#include <WebServer.h>
#include <ArduinoJson.h>

const char* ssid     = "API2";
const char* password = "lawl123456";

IPAddress local_ip(192,168,4,5);
IPAddress gateway(192,168,4,5);
IPAddress subnet(255, 255, 255, 0);
WebServer server(2424);

const char* ROOMID = "420";

long long timer;
void      setWifi(const char* name, const char* password);

void setup() {
  Serial.begin(115200);
  setWifi(ssid, password);
 
  if ( MDNS.begin("esp32") ){
    Serial.println("MDNS responder started");
  }
  
  server.on("/incoming",       handleIncoming );
  server.on("/",               handleRoot );
  server.on("/identification", handleIdentification );
  
  server.begin();
  Serial.println("HTTP server started");
}


void handleIdentification() {
  Serial.println("Identification requested");
  server.send(200,"application/json", "{\"id\":" + String("\"") +  String(ROOMID) +"\"}");
  return;
}


void handleIncoming() {
  String buffer = "";
  
  if(server.method() != HTTP_POST) {
    Serial.println("Incorrect request received!");
    server.send(403, "text/json", "{\"Message\":\"Incorrect request received!\"}");
    return;
  }
  
  buffer += server.arg(0);
  StaticJsonDocument<512> doc;
  DeserializationError error = deserializeJson(doc, buffer);
  
  if(error){
    Serial.println(error.c_str());
    server.send(500, "text/json", "{\"ack\":" + String(error.c_str()) +"\"}");
    return;
  }
  
  if (!doc["device_type"]|| !doc["rssi"] || !doc["person"] || !doc["magno"]) {
    Serial.println("Incorrect fields");
    server.send(500, "text/json", "{\"Message\":\"Incorrect fields received!\"}");
    return;
  }

  if(doc["device_type"] != "beacon") {
    Serial.println("Ping from unexpected recepient!");
    server.send(500, "text/json", "{\"Message\":\"Ping from unexpected recepient!\"}");
    return;
  }
  
  String deviceType = doc["device_type"];
  String rssi       = doc["rssi"];
  String person     = doc["person"];
  String magno      = doc["magno"];

  Serial.println("----------------------------------------");
  Serial.println("Device Type:" + String(deviceType));
  Serial.println("Rssi: " + String(rssi));
  Serial.println("Magno: " + String(magno));
  Serial.println("person: " + String(person));
  Serial.println("----------------------------------------");
  server.send(200, "text/plain", "{\"ack\":\"Incoming data received\"}");
}

void handleRoot() {
  String message = "";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  Serial.println(message);
  server.send(200, "text/json", "{\"ack\":\"success\"}");
  return;
}


void setWifi( const char* name, const char* password ) {
  while(!WiFi.softAP(name, password)) {
    Serial.println(".");
    delay(150);
  }
  Serial.println("WIFI < " + String(ssid) + " > ... Started");
  Serial.println(WiFi.softAPIP());
  Serial.println("Server Started");
  return;
}

void loop( void ) {
  server.handleClient();
}

Debug Messages:

The server debug output.

[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 16 - AP_STADISCONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 18 - AP_PROBEREQRECVED
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: -1, ERR: 104
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
----------------------------------------
Device Type:beacon
Rssi: 34
Magno: 45db
person: me
----------------------------------------
[D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128

The client's debug output.

[D][HTTPClient.cpp:1025] connect():  connected to 192.168.4.1:2424
[W][HTTPClient.cpp:1318] returnError(): error(-11): read Timeout
[D][HTTPClient.cpp:1320] returnError(): tcp stop
-11
[W][HTTPClient.cpp:1318] returnError(): error(-4): not connected
[D][HTTPClient.cpp:383] disconnect(): tcp is closed

[D][HTTPClient.cpp:276] beginInternal(): host: 192.168.4.1 port: 2424 url: /incoming
[D][HTTPClient.cpp:1025] connect():  connected to 192.168.4.1:2424
[W][HTTPClient.cpp:1318] returnError(): error(-11): read Timeout
[D][HTTPClient.cpp:1320] returnError(): tcp stop
-11
[W][HTTPClient.cpp:1318] returnError(): error(-4): not connected
[D][HTTPClient.cpp:383] disconnect(): tcp is closed

[D][HTTPClient.cpp:276] beginInternal(): host: 192.168.4.1 port: 2424 url: /incoming
[D][HTTPClient.cpp:1025] connect():  connected to 192.168.4.1:2424
[W][HTTPClient.cpp:1318] returnError(): error(-11): read Timeout
[D][HTTPClient.cpp:1320] returnError(): tcp stop
-11
[W][HTTPClient.cpp:1318] returnError(): error(-4): not connected
[D][HTTPClient.cpp:383] disconnect(): tcp is closed

[D][HTTPClient.cpp:276] beginInternal(): host: 192.168.4.1 port: 2424 url: /incoming
[D][HTTPClient.cpp:1025] connect():  connected to 192.168.4.1:2424

Has anyone faced this issue? I've been caught up for a long time and can't seem to figure out what seems to be the problem. Occasionally a few times the response is received or it goes into GURU MEDITATION ERROR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: StaleIssue is stale stage (outdated/stuck)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions