-->
Page 1 of 1

client.connect() failed on the second time

PostPosted: Sat Mar 23, 2019 8:35 pm
by LameLemon
I am trying to get my es8266 to connect to api.openweathermap.org, it works fine the first time, but on the second loop after a set interval it fails to connect. I make sure to close the old connection before the next one too, I've tried 10 minutes, 1 minute and 5 minutes intervals, also adding a delay after client.connect(). I have checked by using client.connected() to make sure it's disconnected as well.

Any help or advice is appreciated, thank you.

Below is the shortened code:

Code: Select allvoid httpRequest() {
  client.stop();
  Serial.println("Making request");
  int con_val = client.connect(server, 80);
  Serial.println(con_val);
  if (con_val) {
    // GET request
    client.println("GET /data/2.5/weather?q="+City+"&units=metric&APPID=" +app_id+" HTTP/1.1");
    client.println("Host: api.openweathermap.org");
    client.println("User-Agent: ArduinoWiFi");
    client.println("Connection: close");
    client.println();
   
    unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println("Client timed out");
        client.stop();
        return;
      }
    }
   
    char c = 0;
    while (client.available()) {
       /* Verify JSON HERE */
      }
    }
  }
  else {
    Serial.println("Connection failed");
    return;
  }
}

Re: client.connect() failed on the second time

PostPosted: Tue Mar 26, 2019 2:06 am
by DIRR70
Hello LameLemon,

Instead of using a global object for the WiFi client try using a local one. That gives you a "freshly" initialized client for each request:

Code: Select allvoid httpRequest() {
  WiFiClient client;
  Serial.println("Making request");


Also I would suggest, to stop the client at the end of the request, not before you've started:

Code: Select all  // ...
  char c = 0;
  while (client.available()) {
    c = client.read();
  }
  client.stop();


If that won't help please paste the full code.