Test the MQTT Connection by Using the Pinging Feature
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:
- Find out if the MQTT connection is still open.
- 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:
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:
Then, go to mqtt_core.c and delete the word static in the function declaration:
Delete the word static in the function definition too:
Also, declare that function in mqtt.core.h, that is, write the next line at the bottom of mqtt_core.h:
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;
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: