Hi, I’m running in SEMI_AUTOMATIC mode and finding that after I turn on WiFi and connect to the cloud, the TCPClient will always fail to connect on its first attempt. Subsequent attempts are fine.
I’ve been careful to ensure everything is set up correctly waiting for WiFi.ready() and Spark.connected() and its even reporting a local IP address before I go to make the connection.
Is this an issue with the TCPClient class?
Here’s my debugging from two cycles of my main loop, note that the first time it fails:
Turning on WiFi.
Connecting WiFi.
Waiting for WiFi to be ready......... WiFi is ready!
Connecting to cloud.. Cloud connected!
IP Address: 192.168.0.5
Connecting TCPClient...
connection failed
Turning on WiFi.
Connecting WiFi.
Waiting for WiFi to be ready WiFi is ready!
Already on cloud!
IP Address: 192.168.0.5
Connecting TCPClient...
connected
And here’s my sample application that creates these results:
#include "application.h"
unsigned int nextTime = 0; // Next time to contact the server
SYSTEM_MODE(SEMI_AUTOMATIC);
void setup() {
Serial.begin(9600);
delay(2000); // delay for me to connect serial terminal
}
void loop() {
if (nextTime > millis()) {
return;
}
Serial.println("\n\nTurning on WiFi.");
WiFi.on();
Serial.println("Connecting WiFi.");
WiFi.connect();
Serial.print("Waiting for WiFi to be ready");
while(!WiFi.ready()) {
Serial.print(".");
delay(100);
}
Serial.println(" WiFi is ready!");
if(Spark.connected()) {
Serial.println("Already on cloud!");
}
else {
Serial.print("Connecting to cloud");
Spark.connect();
while(!Spark.connected()) {
Serial.print(".");
delay(100);
}
Serial.println(" Cloud connected!");
}
Serial.print("IP Address: ");
IPAddress localAddr = WiFi.localIP();
byte oct1 = localAddr[0];
byte oct2 = localAddr[1];
byte oct3 = localAddr[2];
byte oct4 = localAddr[3];
char ipChars[16];
sprintf(ipChars, "%d.%d.%d.%d", oct1, oct2, oct3, oct4);
Serial.println(ipChars);
TCPClient myClient;
Serial.println("Connecting TCPClient...");
if (myClient.connect("www.timeapi.org", 80))
{
Serial.println("connected");
}
else
{
Serial.println("connection failed");
}
//Serial.println("Turning off WiFi gracefully.");
//Spark.disconnect();
//WiFi.disconnect();
//WiFi.off();
//Serial.println("WiFi is off!");
nextTime = millis() + 10000;
}
EDIT: Just to be clear, if I were to uncomment the last part of code turning off the WiFi, the TCPClient will fail to connect every time. It’s only after being turned on for a while that it can connect successfully.