MQTT - C/C++ Client

  This article records how to implement the client directly using c/c++ , which is linked to the Mosquito MQTT broker set-up on the Ubuntu 20.04, introduced in MQTTT - Mosquito MQT broker set-up on the Ubuntu 20.04.

 

Install Paho MQTT C Client

 To use MQTT on c/c++, first download the required module from the eclipse foundation. You can download files for your operating system from https://www.eclipse.org/paho/index.php?page=clients/c/index.php.

<Paho MQTT C Client download page>

Of course I use Linux, so I'll refer to the build contents for Linux in the middle of the document for "Building from Source."

apt-get install openssl libssl-dev 
cd /usr/local/src
git clone https://github.com/eclipse/paho.mqtt.c.git
cd paho.mqtt.c.git
make && sudo make install 

 Now we are ready to develop mqtt client using c/c++.

 

Build Example

 We will proceed with the example of mqttt as described in MQTT - Mosquito MQTT broker set-up on the Ubuntu 20.04. In this blog, I used the mosquito_sub and mosquito_sub programs to demonstrate MQTT, and this time I will explain it using the c/c++ example I'll make. Therefore, it is recommended that you preview my previous blog.

I will test in the following system environment and c/c++ example will be developed in 192.168.11.129.

<test configuration>

I made a simple c++ example code for the test as follows.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <string>

#include "MQTTClient.h"

using namespace std;

#define ADDRESS     "tcp://192.168.11.86:1883"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "test"
#define QOS         1


#define color_def     "\033[0m"
#define color_red     "\033[031m"
#define color_green   "\033[032m"
#define color_blue    "\033[034m"
#define color_magenta "\033[035m"
#define color_cyan    "\033[036m"


MQTTClient mqtt_client;
volatile MQTTClient_deliveryToken deliveredtoken;

void connlost(void *context, char *cause)
{
    printf("%s\nConnection lost\n%s", color_red, color_def);
    printf("%s     cause: %s\n%s", color_magenta, cause, color_def);
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int i;
    char* payloadptr;
    printf("%sMessage arrived\n%s", color_green, color_def);
    printf("%s     topic: %s\n%s", color_magenta, topicName, color_def);
    printf("%s   message: ", color_magenta);
    payloadptr = (char *)message->payload;
    for(i=0; i<message->payloadlen; i++)
    {
        putchar(*payloadptr++);
    }
    printf("%s", color_def);
    putchar('\n');

    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
    deliveredtoken = dt;
}

int main(int argc, char * argv[])
{
        int rc, ch;
        MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
        MQTTClient_message pubmsg = MQTTClient_message_initializer;

        rc = MQTTClient_create(&mqtt_client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);

        cout << "client create return:"<< rc <<endl;
        if(rc) return 0;

        MQTTClient_setCallbacks(mqtt_client, NULL, connlost, msgarrvd, delivered);


        conn_opts.keepAliveInterval = 10;
        conn_opts.cleansession = 1;

        conn_opts.username = "dongu";
        conn_opts.password = "dongdong";
        rc = MQTTClient_connect(mqtt_client, &conn_opts);
        cout << "client connect return:"<< rc <<endl;
        if(rc) return 0;

        printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
        MQTTClient_subscribe(mqtt_client, TOPIC, QOS);

        char buff[512];
        MQTTClient_deliveryToken token;
        do
        {
                //ch = getchar();
                memset(buff, 0x00, 512);
                fgets(buff, 512, stdin);
                buff[strlen(buff) -1] = 0x00;;
                if(0 == strcmp(buff, "Q")) break;
                pubmsg.payload = buff;
                pubmsg.payloadlen = strlen(buff) + 1;
                pubmsg.qos = QOS;
                pubmsg.retained = 0;
                MQTTClient_publishMessage(mqtt_client, TOPIC, &pubmsg, &token);

        } while(1);

        MQTTClient_disconnect(mqtt_client, 10000);
        MQTTClient_destroy(&mqtt_client);
        return 0;

}

<sync_mqtt_c.cpp>


To build this code, you must link the libpahomqtt3c.so file using the -lpaho-mqtt3c option. Search the /usr/local/lib directory to find that the paho.mqtt.c libraries you built earlier are installed. If a link error occurs, create a conf file that records the /usr/local/lib directory in the /etc/ld.so.conf directory, and then run the ldconfig command.

root@ubuntu:/usr/local/src/study/mqtt# ls -al /usr/local/lib/
total 2412
drwxr-xr-x  3 root root    4096 Oct 24 04:12 .
drwxr-xr-x 11 root root    4096 Jul  4 23:49 ..
lrwxrwxrwx  1 root root      19 Oct 24 04:12 libpaho-mqtt3a.so -> libpaho-mqtt3a.so.1
lrwxrwxrwx  1 root root      21 Oct 24 04:12 libpaho-mqtt3a.so.1 -> libpaho-mqtt3a.so.1.3
-rw-r--r--  1 root root  600024 Oct 24 04:12 libpaho-mqtt3a.so.1.3
lrwxrwxrwx  1 root root      20 Oct 24 04:12 libpaho-mqtt3as.so -> libpaho-mqtt3as.so.1
lrwxrwxrwx  1 root root      22 Oct 24 04:12 libpaho-mqtt3as.so.1 -> libpaho-mqtt3as.so.1.3
-rw-r--r--  1 root root  679688 Oct 24 04:12 libpaho-mqtt3as.so.1.3
lrwxrwxrwx  1 root root      19 Oct 24 04:12 libpaho-mqtt3c.so -> libpaho-mqtt3c.so.1
lrwxrwxrwx  1 root root      21 Oct 24 04:12 libpaho-mqtt3c.so.1 -> libpaho-mqtt3c.so.1.3
-rw-r--r--  1 root root  546712 Oct 24 04:12 libpaho-mqtt3c.so.1.3
lrwxrwxrwx  1 root root      20 Oct 24 04:12 libpaho-mqtt3cs.so -> libpaho-mqtt3cs.so.1
lrwxrwxrwx  1 root root      22 Oct 24 04:12 libpaho-mqtt3cs.so.1 -> libpaho-mqtt3cs.so.1.3
-rw-r--r--  1 root root  626336 Oct 24 04:12 libpaho-mqtt3cs.so.1.3
drwxrwsr-x  3 root staff   4096 Feb  9  2019 python3.6


Build as follows:

g++ sync_mqtt_c.cpp -lpaho-mqtt3c -o sync_mqtt_c

Now test the built program as follows.
Run the Mosquito_sub program on the 192.168.11.86 host on which the Mosquito service is running, and then run the sync_mqtt_c built on the 192.168.11.219 host. Then run the Mosquito_sub on the 192.168.11.86 host and send the message to the subscribers.


As you can see, messages sent from mosquito_pub are well communicated to sync_mqttt_c as well as mosquito_sub. And the "Hi There" message from mqtt_c is also sent to mosquito_sub.

Wrapping up

We implemented mqtt client using Python in previous example. And now we have implemented mqtt client using c/c++.  mqtt is a powerful platform that can easily develop messaging systems using various languages. It can be useful when developing communication system in enterprise system as well as IoT platform.


If you are interested in MQTT client implemented by Python, see MQTT - Python Client



댓글

이 블로그의 인기 게시물

RabbitMQ - C++ Client #1 : Installing C/C++ Libraries

C/C++ - Everything about time, date