Open W33KX opened 4 years ago
The method I used to solve this issue:
//This happens in main loop
//when message is received
counter++;
if (counter%20 < 1) reconnect();
//rest of code...
//outside the loop with another method function
void reconnect() {
if (mqtt.unsubscribe(nanoID, String(send_topic))) Serial.println("Unsubscribed to \"" + String(send_topic) + "\"");
if (mqtt.disconnect(nanoID)) Serial.println("Disconnected, trying to reconnect");
delay(5);
if (mqtt.connect(nanoID, mqtt_serverID, 1883, "NanoESP" + String(nanoID), username, mqtt_pswd)) {
Serial.println("\nConnected to MQTT server: " + String(mqtt_serverID));
if (mqtt.subscribe(nanoID, String(send_topic), 2)) Serial.println("Subscribed to \"" + String(send_topic) + "\"");
}
else {
Serial.println("MQTT failed");
while (true);
}
}
I've made a mosquitto server on my raspberry pi and my Nano ESP is subscribed to a certain topic on that mqtt server. But the connection seems to hold it for a few seconds. I noticed on the terminal on my Pi that there are only ping requests from my phone (app that publishes to the same topic). I suppose the stayConnected(id) command should remain its connectivity to the server by pinging to it with a certain interval. Is there a way that the pings continue? **UPDATE** I've tried to count how many times I'm able to receive a message and it seems to stop at 20 each time... ***UPDATE*** I seem to have fixed the issue, I've made a counter and when it reaches 20 received messages, it'll disconnect from the server an reconnect again wich solved my problem for the meantime Anyway heres my code for the nano ESP: