C

Quick guide for C library.

Getting Started

Visit the MQTT overview page for conventions, authentication, and more information.

This documentation uses the Paho MQTT library. This library is open-source, so you can check it out on GitHub.

Install the packages

// Clone the library source
git clone https://github.com/eclipse/paho.mqtt.c.git
cd paho.mqtt.c

// Build the library
make

// Install to the system
sudo make install

Include libraries

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"

Define variables

#define ADDRESS     "tcp://__broker_ip__"
#define CLIENTID    "__device_id__"
#define TOPIC       "__device_id__"
#define PAYLOAD     "{\"Key1\":Value1,\"Key2\":Value2}"
#define QOS         1
#define TIMEOUT     10000L

Set MQTT client options

Set client options and connect to the broker.

MQTTClient client;
MQTTClient_connectOptions options = MQTTClient_connectOptions_initializer;

options.username = "__device_id__";
options.password = "__device_token__";

MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;

MQTTClient_create(&client, ADDRESS, CLIENTID,MQTTCLIENT_PERSISTENCE_NONE, NULL);
options.keepAliveInterval = 20;
options.cleansession = 1;

 if ((rc = MQTTClient_connect(client, &options)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;

Publish data:

MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);

Optional: Close the connection to the broker:

MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);

Example

We strongly recommend using the 8883 port for MQTT over TLS connectivity.

✨ Support and Feedback

If you have further questions or suggestions, feel free to join πŸ‘‡ -> Qubitro Community Discord via this invitation link.

Last updated