What is MQTT?

MQTT is a lightweight messaging protocol that is used to send small data from sensors and devices to other places or devices over internet.Due to its lightweight nature it is very suitable for mobile application and IoT , This makes MQTT very popular and interesting. more reading.

MQTT structure

Sender and receiver are clients of MQTT.They are always connected through MQTT broker.The sender publish message to a particular topic in MQTT broker then the broker broadcast this message to all other receiver who already subscribed to this topic.

Eg:we have 3 temperature  senser and one gateway.The gateway subscribe to a topic called “TEMPERATURE”.The sensors will publish temperature in every 2 hour to  the topic TEMPERATURE.whenever a sensor publish message the broker send it to gateway.

goetz_mqtt_1

How to setup MQTT broker

Broker can be installed in local machine or can be use any public free mqtt broker.Installation in local machine .there are a bunch of public MQTT brokers for free, which are

Server Broker Port Websocket
iot.eclipse.org Mosquitto 1883 / 8883 n/a
broker.hivemq.com HiveMQ 1883 8000
test.mosquitto.org Mosquitto 1883 / 8883 / 8884 8080 / 8081
test.mosca.io mosca 1883 80
broker.mqttdashboard.com HiveMQ 1883

will explain how to use this very soon.

MQTT :available libraries

MQTT supports various programming languages.Download the desired library of paho mqtt from here .This tutorial if focused in C library.

Download paho-mqtt C lib from here.Extract file.Go to this location in terminal and run following commands.

make
make install

Libs MQTTAsync.h and  MQTTClient.h are able to include in your source once the library installation is completed.

Writing first Application

Publish application:This application publish message in the  topic “ExampleTopic”.

Subscribe application:Which is subscribed to topic”ExampleTopic”.

publish app(synchronous)

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h" /*synchronous */

#define ADDRESS "iot.eclipse.org:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "ExampleTopic"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L

 MQTTClient client;
 MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
 MQTTClient_message pubmsg = MQTTClient_message_initializer;
 MQTTClient_deliveryToken token;
 int rc;

void publishMessage()
{
 pubmsg.payload = PAYLOAD;
 pubmsg.payloadlen = strlen(PAYLOAD);
 pubmsg.qos = QOS;
 pubmsg.retained = 0;

 MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
 printf("\n*******************Message send********************\n");
 printf("Waiting for up to %d seconds for publication of %s\n"
 "on topic %s for client with ClientID: %s\n",
 (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
 rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
 printf("\nMessage with delivery token %d delivered\n", token);
}
int main(int argc, char* argv[])
{
 char ch;
 MQTTClient_create(&client, ADDRESS, CLIENTID,
 MQTTCLIENT_PERSISTENCE_NONE, NULL);/*on success,returna a non-zero value to client */
 conn_opts.keepAliveInterval = 20;
 conn_opts.cleansession = 1;

if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
 {
 printf("Failed to connect, return code %d\n", rc);
 exit(EXIT_FAILURE);"iot.eclipse.org:1883"
 }
 printf("press any key to send message press Q or q to Quit\n");
 while((ch=getchar())!='Q' && ch!='q')
 {
 if(ch!='\n')
 publishMessage();
 }
 MQTTClient_disconnect(client, 10000);
 MQTTClient_destroy(&client);
 return rc;
}

subscribe app (synchronous)

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

#define ADDRESS "iot.eclipse.org:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "ExampleTopic"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L

volatile MQTTClient_deliveryToken deliveredtoken;

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

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
 int i;
 char* payloadptr;

 printf("\n**********************Message arrived**********************\n");
 printf(" topic: %s\n", topicName);
 printf(" message: ");

 payloadptr = message->payload;
 for(i=0; i<message->payloadlen; i++)
 {
 putchar(*payloadptr++);
 }
 putchar('\n');
 MQTTClient_freeMessage(&message);
 MQTTClient_free(topicName);
 return 1;
}

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

int main(int argc, char* argv[])
{
 MQTTClient client;
 MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
 int rc;
 int ch;

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

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

 if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
 {
 printf("Failed to connect, return code %d\n", rc);
 exit(EXIT_FAILURE);
 }
 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(client, TOPIC, QOS);

 do 
 {
 ch = getchar();
 } while(ch!='Q' && ch != 'q');

 MQTTClient_disconnect(client, 10000);
 MQTTClient_destroy(&client);
 return rc;
}

MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) : function sets the callback for subscription of topic. Whenever a message come msgarrv,delivered functions execute.When connection lost connlost calls.

In order to see the real action open the appication in seperate terminal.

subscription and publishing in same application

(Little busy.. update soon…!)

 

 

Advertisements