-->
Page 1 of 1

Struggling with WiFiClient::connect() unreliability

PostPosted: Mon Jan 22, 2018 12:08 pm
by Darren Humphrey
I am trying to connect to a server via TCP and collect some data but I am struggling with WiFiClient::connect() not working all the time. I'd say on the order of 50/50 chance of a connect fail. Though sometimes it works 10 times in a row. The error I get is a "connection refused".

I am powering my generic NodeMCU V2 from 2 usb ports--one is hooked up to the micro usb onboard for programming, the other is connecting VIN to the 5V out of my powered USB hub. I measure 1.3A of current on VIN. When I don't have this external power connected, the failure rate is more like 90%. Is this a power issue? Is there something else I need to do for power reliability?

What is very very odd is that I am getting this failure while I am connected to my mqtt broker. So I KNOW I have a valid WiFI connection because the command that actually triggers the following code is triggered by receiving a MQTT publish message.

Here's my minimal connect code. I have verified that the tcp error is connection refused.

My debug Output:

Wifi status 1
My hostname is ChillOut
IP address: 192.168.1.247
Gateway IP: 192.168.1.1
Subnet: 255.255.255.0
dns IP: 192.168.1.1
Connecting to server :192.168.1.2: on port 8000
Connect result using Hostname is 0
Got IP addr for server: 192.168.1.2
Connect result using IP address is 0


Code:

WiFiClient client;
IPAddress ipAddr;

Serial.printf("Wifi status %d\n",WiFi.isConnected());
Serial.printf("My hostname is %s\n",WiFi.hostname().c_str());
Serial.print("IP address: "); Serial.println(WiFi.localIP());
Serial.print("Gateway IP: "); Serial.println(WiFi.gatewayIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("dns IP: "); Serial.println(WiFi.dnsIP());

Serial.printf("Connecting to server :%s: on port %d\n",serverName,port);

Serial.printf("Connect result using Hostname is %d\n",client.connect( serverName, port ));
client.stop();

if (WiFi.hostByName(serverName, ipAddr, 5000))
{
Serial.printf("Got IP addr for server: ");
Serial.println(ipAddr);
}
Serial.printf("Connect result using IP address is %d\n",client.connect( ipAddr, port ));
client.stop();