I have wrote a sketch in which I connect my esp8266-07 to CloudMQTT broker. In my code I'm always checking whether my esp is connected to the broker or not. I use client.connected() for this matter.
first question:
there are sometimes that ESP gets disconnected (client.state() == -4). what are the causes of this problem? why this happens more that 4 times in a minute???? My internet connection is stable!
second question:
sometimes when I'm using client.connect(ID, username, pass); ESP freezes for 10 or 15 seconds and then it doesn't connect the broker (client.state() == -2) . why this is happening and more importantly, how can I pass this delay?????
I don't know whether my code helps you to find the solution or not but this is my function. this function is called in every main loop and gets functional in every other 60 loops thanks to the variable time_out:
void make_connection(void)
{
if (time_out == 1)
{
switch (connect_cycle_stat)
{
case 0:
{
Serial.printf("\nmake_connection ==>");
Serial.printf("\ncase %d. ", connect_cycle_stat);
if (WiFi.softAP(ap_ssid, ap_pass))
{
server.begin();
connect_cycle_stat++;
time_out = 0;
}
break;
}
case 1:
{
Serial.printf("\nmake_connection ==>");
Serial.printf("\ncase %d. ", connect_cycle_stat);
Serial.printf("\nWiFi.status() = %d", WiFi.status());
if (WiFi.status() == WL_CONNECTED)
{
time_out = 0;
connect_cycle_stat++;
uint8_t mac[6];
WiFi.macAddress(mac);
device_ID += macToStr(mac);
//update_esp();
}
else
{
WiFi.begin(wifi_ssid, wifi_pass);
}
break;
}
case 2:
{
Serial.printf("\nmake_connection ==>");
Serial.printf("\ncase %d. ", connect_cycle_stat);
Serial.printf("\nmqtt_client.connected() = %d", mqtt_client.connected());
Serial.printf("\nWiFi.status() = %d", WiFi.status());
if (mqtt_client.connected() == true)
{
mqtt_client.publish(out_topic.c_str(), "Hello from ESP8266");
mqtt_client.subscribe("steamer/appClient");
// will handle the incoming messages for the topics subscribed.
mqtt_client.setCallback(callback);
connect_cycle_stat++;
}
else
{
//mqtt_client.disconnect();
delay(100);
mqtt_client.connect(device_ID.c_str(), mqtt_user, mqtt_pass);
}
break;
}
case 3:
{
Serial.printf("\nmake_connection ==>");
Serial.printf("\ncase %d. ", connect_cycle_stat);
Serial.printf("\nmqtt_client.connected() = %d", mqtt_client.connected());
Serial.printf("\nWiFi.status() = %d", WiFi.status());
if (mqtt_client.connected() == false)
{
//mqtt_client.disconnect();
delay(100);
connect_cycle_stat--;
}
if (WiFi.status() != WL_CONNECTED)
{
WiFi.begin(wifi_ssid, wifi_pass);
connect_cycle_stat = 1;
}
break;
}
}
}
time_out++;
if (time_out > 60) time_out = 0;
}