Trying to write simple MQTT
application with Paho
library. I'm planning to create simple fire and forget not blocking function :
void send(char* data)
{
..
}
For this purpose I'm planning to use MQTTAsync client. But how to pass data to connect event. I suppose it is not good style to define char * dataToSend
globally.
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
printf("Successful connection\n");
opts.onSuccess = onSend;
opts.context = client;
pubmsg.payload = dataToSend;
pubmsg.payloadlen = strlen(dataToSend);
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
CodePudding user response:
It is possible to pass it using a structure in the context.
Something like:
typedef MQTTContext {
MQTTAsync client;
char* dataToSend;
};
This will allow to get buffer (and MQTTclient) from this context structure.
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTContext* ctx = (MQTTContext*)context;
// retreive client
MQTTAsync client = ctx->client;
...
// retreive message to publish
pubmsg.payload = ctx->dataToSend;
...
}
In your send function you could store message in this context structure
void send(char* data)
{
MQTTAsync client;
// store in context structure client and message to publish
MQTTContext* ctx = (MQTTContext*)malloc(sizeof(MQTTContext));
ctx->client = client;
ctx->dataToSend = data;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
...
conn_opts.context = ctx;
MQTTAsync_connect(client, &conn_opts);
}
CodePudding user response:
You probably need to add some more context to the question, but the short answer is you don't.
You connect the client once when you launch the application and reuse the same client object for the life of the application. So when you want to send a message you should be already connected, no need to use the onConnect
callback.
What you might do is use the onConnect
callback to set a flag so the send
function knows that the client has finished connecting if it is going to be called very soon after the application starts, just to make sure the client has finished connecting first.