C

Getting Started

Before getting started, make sure that required libraries are installed by visiting the setup page

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