1

Does anyone know if you can set the time for the timeout Ethernet Shield library? Let me explain:

I created a very simple function (below) that attempts to connect to an address if it is not accessible returns 0 if it is available returns 1. Problem is that when the site is not available, the microcontroller is waiting for an answer for a long time, wanted to reduce it.

uint8_t ping(const char* address)
{
    EthernetClient http;

    if(http.connect(address, 80)) {
        http.stop();
        return 1;
    }
    else 
        return 0;
}
Renato Tavares
  • 180
  • 4
  • 11

1 Answers1

0

In the stream class there is a setTimeout(ms) function. e.g.

String str;
Serial.setTimeout(5000) ;
str = Serial.readStringUntil('\r');

Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.

int httpGetHeaders() {
  String request, response;
  int result = 0;
  long startOfHttpResponseTime;

  client.setTimeout(1000) ;
  response = "";
  inHeaders = true;
  startOfHttpResponseTime = millis();
  while((client.connected()) && inHeaders && ((long)(millis() - startOfHttpResponseTime) < HTTP_RESPONSE_TIMEOUT)) {
    String header = client.readStringUntil('\n');
    header.trim(); // trim off white spaces including CR and LF at end.
    Serial.print(F("head[")); 
    Serial.print(header.length()); 
    Serial.print(F("]:\"")); 
    Serial.print(header);
    Serial.println(F("\"")); 
    if (!header.length()) { // first blank line indicates end of headers
      inHeaders = false;
      Serial.println(F("No longer in Headers")); 
    }
    else {
      if (header.startsWith("HTTP")) {
        Serial.println(F("HTTP Found")); 
        int firstspace = header.indexOf(" ");
        result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
        Serial.print(F("result = ")); 
        Serial.println(result); 
      }
    }
  }

  Serial.print(F("Result code = "));
  Serial.println(result);
  return result;
}

You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.

mpflaga
  • 2,513
  • 13
  • 13