mrlenbenquet mrlenbenquet - 22 days ago 20
C++ Question

Use MQTT client pointer amongst C++ functions

I am using the Paho C++ MQTT library to connect to my broker.

I want my code to be organized the following way :

connect();
sendMessage(data);
disconnect();


I already managed to connect, send a message and disconnect but only in the same function because of the MQTT client's scope :

void sendMessage(){
// Connect
mqtt::itoken_ptr conntok = client.connect();
conntok->wait_for_completion();

// Sending message
pubtok = client.publish(topic, char_json, data, qos, false);
pubtok->wait_for_completion(timeout);

// Disconnect
conntok = client.disconnect();
conntok->wait_for_completion();
}


However I want to have those pieces of code in three separate functions (to avoid reconnecting/disconnecting every time I send some data)

I guess that I have to use the mqtt::itoken_ptr conntok that is returned from the client.connect(), but this object has no get_client() function, only mqtt:token does.

The documentation shows that there is a pointer for the async_client class std::shared_ptr ptr_t but I am unsure how to use it since I'm fairly new to C++. The actual client object is private (under the C++ wrapper).

How can I use the same client object in different functions so I can have the following ?

connect(){
mqtt::itoken_ptr conntok = client.connect();
}
sendMessage(){
pubtok = client.publish(topic, char_json, data, qos, false);
pubtok->wait_for_completion(timeout);
}
disconnect(){
conntok = client.disconnect();
conntok->wait_for_completion();
}

Answer

Haven't tested this, but why can't you in pseudo code:

void disconnect(mqtt::iasync_client &client);
void connect(mqtt::iasync_client &client);
void sendMessage(mqtt::iasync_client &client);

controller()
{
   mqtt::async_client client(ADDRESS, CLIENTID);
   connect(client);
   sendMessage(client);
   disconnect(client);
}

connect(&client){
   callback cb;
   client.set_callback(cb); // necessary to avoid segmentation fault
   token = client.connect();
   token->wait_for_completion(timeout);
}

sendMessage(&client){
   callback cb;
   client.set_callback(cb); // necessary to avoid segmentation fault
   pubtok = client.publish(topic, char_json, data, qos, false);
   pubtok->wait_for_completion(timeout);
}

disconnect(&client){
   callback cb;
   client.set_callback(cb);
   conntok = client.disconnect();
   conntok->wait_for_completion();
}
Comments