Hi Cindy,
please see the code below.
The code should work like this:
- We have a MQTT broker running on an Ubuntu Linux machine in the local network.
- We start our application, which should collect 1000 messages and then quit the application.
- We then start a MQTT client running on an Ubuntu Linux machine that publishes on the same topic each time a 25 Byte long message, with a counter included in the message, for 1000 times. The sending is controlled by a Python script and amounts to about max. 5 messages per second.
- Our client, the one on the STM32F4 receives these messages, the "tx_event_flags_get" reports only on about 992, sometimes 993.
- How do we know, that all messages where received?
- first, we have a second subscribing client on the Ubuntu machine, this client reports all messages, hence the broker receives all published messages and sends them all to the subcribers.
- second, we restart the above mentioned python script, now the missing messages come first and this time, the counter only goes to 984, (if we set our counter for remaining_msg let us say to 2000 or 3000.
- alternatively to second, we can trigger 8 more single messages from the publishing client and we will see the "lost" messages first, before the single messages are shown.
Hence, the application works nicely, but the messages are not shown as received till the end.
#define DEMO_MESSAGE_EVENT 1
#define DEMO_ALL_EVENTS 3
/* Subscribe to the topic with QoS level 1. */
ret = nxd_mqtt_client_subscribe(&mqtt_client,
TOPIC_NAME,
STRLEN(TOPIC_NAME),
QOS1);
if (ret != NX_SUCCESS) { Error_Handler(); }
message_count = 0;
remaining_msg = NB_MESSAGE;
while(remaining_msg)
{
waitForMessage = 1;
/* Now wait for the broker to publish the message. */
while(waitForMessage)
{
waitForMessage = tx_event_flags_get(&mqtt_app_flag,
DEMO_ALL_EVENTS,
TX_OR_CLEAR,
&events,
1); //TX_WAIT_FOREVER);
}
if(events & DEMO_MESSAGE_EVENT)
{
/* Try to get message from the broker */
ret = nxd_mqtt_client_message_get(&mqtt_client,
topic_buffer,
sizeof(topic_buffer),
&topic_length,
message_buffer,
sizeof(message_buffer),
&message_length);
topic_buffer[topic_length] = 0;
message_buffer[message_length] = 0;
if(ret == NXD_MQTT_SUCCESS)
{
remaining_msg -- ;
message_count ++ ;
}
else if(ret == NXD_MQTT_NO_MESSAGE)
{
// do nothing
}
else
{
Error_Handler();
}
}
}
/* Now unsubscribe the topic. */
ret = nxd_mqtt_client_unsubscribe(&mqtt_client, TOPIC_NAME, STRLEN(TOPIC_NAME));
if (ret != NX_SUCCESS) { Error_Handler(); }