Test the MQTT Connection by Using the Pinging Feature

Last modified by Microchip on 2023/11/10 11:11

We have the option to ping to the broker from our device. We send a pingreq, and when broker receives it, it sends a pingresp back. We can use this for two purposes:

  1. Find out if the MQTT connection is still open.
  2. Reset the keepAlive timer. This timer is meant to close the MQTT connection when enough time elapses without interactions and pinging is the simplest way of interacting.

For every time that you pingreq, you will get a pingresp, and you should process all of them. That is, execute the MQTT_ReceptionHandler(mqttConnnectionInfo) function more times than you send pings.

Write this line wherever you want in app_mqttScheduler to send a pingreq:

mqttSendPingreq(mqttConnnectionInfo);

That function is defined in mqtt_core.c as static. To use it in mqtt_example.c, include mqtt_core.h in mqtt_example.c, that is, write this line at the top of mqtt_example.c:

#include "../mqtt/mqtt_core/mqtt_core.h"

Back to top


Then, go to mqtt_core.c and delete the word static in the function declaration:

Delete the word "static" in this function

Back to top


Delete the word static in the function definition too:

Delete the word "static" in this function

Back to top


Also, declare that function in mqtt.core.h, that is, write the next line at the bottom of mqtt_core.h:

bool mqttSendPingreq(mqttContext *mqttConnectionPtr);

Back to top


Now you can execute mqttSendPingreq(mqttConnnectionInfo) in mqtt_example.c

If pinging is done too soon, when the device is not fully initialized, it may collapse. It is recommended to ping when the appMQTTPublishTimeoutOccured has occurred at least 3 times, as it was for sending a subscribe packet, in the Send Subscribe Packet section 

See example:

Add this variable in mqtt_example.c

uint8_t more_than_once= 0;

uint8_t more_than_once=0;

Code View: Count how many times the timer has been completed

more_than_once++;                       //count how many times the timer has been completed
               if (more_than_once==3){                 //if the timer has been completed 3 or more times
                   mqttSendPingreq(mqttConnnectionInfo);   //ping
                   more_than_once=2;   //the next time, more_than_once will be 3 again, and again
               }

If the code is correctly executed, you should see how the broker receives a PINGREQ and sends a PINGRESP between each publish. Something like this should be in the command prompt:

Broker receives a PINGREQ and sends a PINGRESP between each publish

Back to top