adafruit / Adafruit_MQTT_Library

Arduino library for MQTT support
MIT License
572 stars 291 forks source link

ping() being pretty slow #96

Open DoNck opened 6 years ago

DoNck commented 6 years ago

Hi there !

I tried the mqtt_esp8266_callback example on an ESP8266 and was pretty suprised by how long ping() was taking to ping my local mosquitto server.

I made a small change to monitor how it was operating :

  Serial.println("Sending a ping...");\  
  unsigned long StartTime = millis();
  if (! mqtt.ping()) {
    Serial.println("PING FAILURE");
    mqtt.disconnect();
  }else{
    unsigned long elapsedTime= millis() - StartTime;
    Serial.print("ping() took: ");
    Serial.print(elapsedTime);
    Serial.println(" ms");
  }

and here are the (pretty stable) results :

Sending a ping...
ping() took: 600 ms
Sending a ping...
ping() took: 513 ms
Sending a ping...
ping() took: 513 ms

Did you experience the same delay ? Is it a bug ?

I ran the test pinging a raspberry pi zero (raspbian) + mosquitto and a mosquitto server running on a windows laptop, results are the same. I run Arduino 1.8.5 + the Arduino esp8266 2.3.0 board extension.

Best regards !

sommersoft commented 6 years ago

I was looking into a separate "timing issue" with the Adafruit_IO io.run() function, came across this and wanted to see if they were related.

However, I think I see why the pings are taking a minimum of 500ms. ping() calls processPacketsUntil():

// Process ping reply.
    len = processPacketsUntil(buffer, MQTT_CTRL_PINGRESP, PING_TIMEOUT_MS);

PING_TIMEOUT_MS is set to 500 in Adafruit_MQTT.h processPacketsUntil() passes PING_TIMOUT_MS onto readFullPacket(), which then passes it to readPacket().

I haven't narrowed down how readPacket() uses the timeout (C++ is not my strong suit). And none of the functions seem to break out if the PINGRESP is received before timout. However, if you change PING_TIMEOUT_MS in Adafruit_MQTT.h, it lowers the ping response. I tested setting it to 200, and here is the result:

Sending a ping...
ping() took: 269 ms
Sending a ping...
ping() took: 264 ms

EDIT: I ran this on an Adafruit Huzzah ESP8266, Arduino 1.8.5, and was pinging Adafruit IO account(io.adafruit.com).