knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.78k stars 1.46k forks source link

Issue while setting keep alive zero. #1033

Open kabirwbt opened 7 months ago

kabirwbt commented 7 months ago

On my esp8266, If I set the keep alive parameter to zero and connect to a broker, despite being connected to broker successfully, connected() returns false and my reconnect loop triggers automatically. I compiled the example provided in the following link : https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino.

I just added the following line to void setup(), at the absolute bottom: client.setKeepAlive(0);

Attempting MQTT connection...connected Attempting MQTT connection...connected This message is printed in a rapid manner, infinitely.

Am I doing something wrong? Should connected() not return true in my case?

kabirwbt commented 7 months ago

My guess is that some other block of code, maybe the ping mechanism is disconnecting the client and causing the connected() to return false. EDIT: after some digging: https://github.com/knolleary/pubsubclient/blob/2d228f2f862a95846c65a8518c79f48dfc8f188c/src/PubSubClient.cpp#L376 is causing the connection to close. Shouldn't the pinging mechanism be disabled via setting the keepalive parameter to 0 ?

ChuckMash commented 6 months ago

Yep, looks like keepalive 0 is not correctly respected.

Try changing the following line

https://github.com/knolleary/pubsubclient/blob/2d228f2f862a95846c65a8518c79f48dfc8f188c/src/PubSubClient.cpp#L373 to

if (((t - lastInActivity > this->keepAlive*1000UL) || (t - lastOutActivity > this->keepAlive*1000UL)) && keepAlive != 0) {

I've not done any long term testing, but I'm having no issues with this change so far.