Hi,
I have put my hands on to MQTT recently and trying samples
to achieve my use case.
Use case : Publish messages received from another module in
asynchronously as and when it receives to the same topic (something like
message will be in queue and client has to read from it).
I have gone through the sample in
'http://www.eclipse.org/paho/files/mqttdoc/Casync/publish.html' and few others
as well. When trying to convert this example to handle multiple messages I had
few problems on managing the callbacks within loops. Lets say after
establishing connection, it calls 'OnConnect' callback where we send message
and again it inturn calls another 'OnSend' callback.
Problem is I tried putting a infinite loop in 'OnConnect'
and send multiple messages but in that case when will it call 'OnSend' as it
lies completely here.
Following is the code snippet
void
onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync_responseOptions opts =
MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg =
MQTTAsync_message_initializer;
int rc;
opts._onSuccess_ = onSend;
opts.context = client;
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
int count = 0;
int messageCnt = 10;
while (count != messageCnt)
{
count++;
std::string message = "Telemetry Data
#MSG_";
std::ostringstream outputString;
outputString << count;
message += outputString.str();
pubmsg.payload = malloc(message.size() + 1);
strcpy_s((char *)pubmsg.payload,
message.size() + 1, message.c_str());
pubmsg.payloadlen = message.length();
if ((rc = MQTTAsync_sendMessage(client,
TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage,
return code %d\n", rc);
exit(-1);
}
}
}
void
onSend(void* context, MQTTAsync_successData* response)
{
MQTTAsync client =
(MQTTAsync)context;
MQTTAsync_disconnectOptions opts
= MQTTAsync_disconnectOptions_initializer;
int rc;
printf("Message with token
value %d delivery confirmed\n", response->token);
}
OnSend
callback never called until this while loop exits and in practical it may be
infinite loop so in that case how I will identify the successfully delivered
are not
Hence
request someone to provide some samples for handling multiple messages publish.
Regards,
Senche