Mosquitto C++ sample code to publish message

I start using mosquitto in a C++ program and I think documentation could be a little bit improved by some examples. To use mosquitto, there is a mosquittopp class acting as a wrapper on top of the mosquitto lib. Basically to create your own program you have to herit from that one and it is easy then.

Mosquitto lib can be managed as a thread or directly by calling the different sub function. In my point of view the thread approach is the better as otherwize you have to manage connection / disconnection manually. Mosquitto lib is then event managed, so you can subscribe to the callback event by surcharging the existing function.

Here is an exemple for a program just needing to publish messages to a broker.

class myMosq : public mosqpp::mosquittopp
{
private:
 const char     *     host;
 const char    *     id;
 const char    *     topic;
 int                port;
 int                keepalive;

 void on_connect(int rc);
 void on_disconnect(int rc);
 void on_publish(int mid);
public:
 myMosq(const char *id, const char * _topic, const char *host, int port);
 ~myMosq();
 bool send_message(const char * _message);
};

The initialization are done in the constructor as well as the thread creation :

myMosq::myMosq(const char * _id,const char * _topic, const char * _host, int _port) : mosquittopp(_id)
 {
 mosqpp::lib_init();        // Mandatory initialization for mosquitto library
 this->keepalive = 60;    // Basic configuration setup for myMosq class
 this->id = _id;
 this->port = _port;
 this->host = _host;
 this->topic = _topic;
 connect_async(host,     // non blocking connection to broker request
 port,
 keepalive);
 loop_start();            // Start thread managing connection / publish / subscribe
 };

The destructor, cleanly close what has been opened

myMosq::~myMosq() {
 loop_stop();            // Kill the thread
 mosqpp::lib_cleanup();    // Mosquitto library cleanup
 }

To send a message, we can simplely call the associated function

bool myMosq::send_message(const  char * _message)
 {
 // Send message - depending on QoS, mosquitto lib managed re-submission this the thread
 //
 // * NULL : Message Id (int *) this allow to latter get status of each message
 // * topic : topic to be used
 // * lenght of the message
 // * message
 // * qos (0,1,2)
 // * retain (boolean) - indicates if message is retained on broker or not
 // Should return MOSQ_ERR_SUCCESS
 int ret = publish(NULL,this->topic,strlen(_message),_message,1,false);
 return ( ret == MOSQ_ERR_SUCCESS );
 }

Then you can add some event handler

on_connect / on_disconnect are called by thread each time we exeperience a server connection / disconnection

void myMosq::on_disconnect(int rc) {
 std::cout << ">> myMosq - disconnection(" << rc << ")" << std::endl;
 }
void myMosq::on_connect(int rc)
 {
 if ( rc == 0 ) {
 std::cout << ">> myMosq - connected with server" << std::endl;
 } else {
 std::cout << ">> myMosq - Impossible to connect with server(" << rc << ")" << std::endl;
 }
 }

on_publish is called each time a message succeed to be sent to broker. The parameter is the message id you can set when publish.

void myMosq::on_publish(int mid)
 {
 std::cout << ">> myMosq - Message (" << mid << ") succeed to be published " << std::endl;
 }
This entry was posted in Programming and tagged , , . Bookmark the permalink.

14 Responses to Mosquitto C++ sample code to publish message

  1. Aiert says:

    the article is good, but i have a question, where did you find the libs and the .h files ?
    some detail codes are not clear for me for now, could you please send me your source code if convenient ?

    • Paul says:

      Take a look to mosquitto.org

      • Fran says:

        Hi, i have visited the Mosquitto website but i have not found any example of a client in C++ with source code to run and use it. Could i download your example in any repository?
        Thanks in advance.

      • Paul says:

        I assume you can copy past from the webpages.
        mosquitto source contains some good example also.

  2. Mike says:

    I’m publishing messages in a server, so my goal is to publish as quickly as possible and return control to service clients. I don’t really want to spin up one or more threads to handle the publishing of messages, I was hoping there was an asynchronous way I could publish and not care about getting notifications, just immediately return.

    • Paul says:

      Yes you can do this, you have a full asynchronous API. I assume you should find some exemple in this blog.

  3. Francesco says:

    Hi Paul, thanks a lot for your post. Even if it has more than a year, I still found it very useful. However I’m having troubles with the connect_async method which always returns -1 to me, with the last mosquitto release 1.4.1. Have you by any chance experienced anything like that?

    • Francesco says:

      Actually I realized it just takes a lot of time (in the order of minutes) before establishing the connection, that’s why connect_async returns MOSQ_ERR_CONN_PENDING. Do you have any idea on the cause of this very long delay?

  4. abhinav rondi says:

    Can you help me build an offline broker using c++ ? I want to create a system where I can send messages from one client to another, which are connected to my broker. Also, it would be great if you could give me a sample client for publishing a mesage(assembling the code given above)!!!

  5. Julius says:

    Hi,

    The event handlers doesn’t work for me. Is there anything I have add to code to make them working?

    Thanks

    • Julius says:

      The code below, doesn’t produce anything:
      myMosq *my_Mosq = new myMosq(“BlaBla”, “test”, “remotehost”, 1883);
      my_Mosq->send_message(“Hello world!”);

      No error, no messages to stdout from handlers, no mqtt message.

Leave a Reply

Your email address will not be published. Required fields are marked *