So I got my Ethernet shield up and running, but it seems very unreliable. I have tried to connect to both google and a local server with the same results.
Here is my code for connecting:
boolean httpRequest(String request, void (*_requestCompleteFunction)(byte), long retryConnectTime, boolean async)
{
byte connection = -1;
// find unused connection
for (byte i = 0; i < MAX_NUM_CONNECTIONS; i++)
{
if (!requestPending[i])
{
connection = i;
break;
}
}
if (connection == -1)
{
logError("Max number of connections exceeded");
return false;
}
Serial.println("Connecting on " + String(connection) + "...");
// stop previous connection
client[connection].stop();
boolean cncted = true;
long startTime = millis();
int count = 0;
// always attempt at least twice and continue attempting for 5 seconds
while (count < 2 || millis() - startTime < retryConnectTime)
{
cncted = client[connection].connect(server, 80);
count ++;
if (cncted)
break;
}
if (cncted)
{
Serial.println("Connecetd!");
client[connection].println("GET " + request);
client[connection].println();
requestResponse[connection] = "";
requestCompleteFunction[connection] = _requestCompleteFunction;
requestPending[connection] = true;
requestResponseStarted[connection] = false;
return true;
}
else
{
logError("Failed to connect to server " + String(server[0]) + '.' + String(server[1]) + '.' + String(server[2]) + '.' + String(server[3]));
return false;
}
}
Here is the code for reading responses:
void loop()
{
for (byte i = 0; i < MAX_NUM_CONNECTIONS; i++)
{
if (requestPending[i])
{
if (client[i].connected())
{
if (client[i].available())
{
char c = char(client[i].read());
requestResponseStarted[i] = true;
requestResponse[i] += c;
Serial.print(c);
}
}
else
{
if (requestResponseStarted[i])
{
(*requestCompleteFunction[i])(i);
requestPending[i] = false;
client[i].stop();
}
}
}
}
}
Here are my symptoms:
-
Ethernet.begin(mac, ip); Ethernet.localIP(); sometimes gives me 0.0.0.0
-
client.connect(server, 80); Does one of the following:
-
Connects immediately
-
The first attempt "times out" after 5 seconds. Next attempts connect immediately or fail
-
The first few attempts will fail before one succeeds
-
After connecting, client.connected() always returns true, but the response will:
-
Return immediately
-
Never return
-
Take a very long time to return
-
Only part of it will return
Am I doing something wrong or is that just the nature of the thing?
Thanks,
- Mike
WebClientTest.ino (4.76 KB)