Over a million developers have joined DZone.

Understanding the MQTT Protocol for the Internet of Things

If you still aren't sure what MQTT is in the IoT, this breakdown with code samples should bring some clarity.

· IoT Zone

Access the survey results 'State of Industrial Internet Application Development' to learn about latest challenges, trends and opportunities with Industrial IoT, brought to you in partnership with GE Digital.

I was thinking about how to control my Aeroponic system remotely via the Internet. The Raspberry Pi controlling the system is connected to the Internet via a router. I could access the Raspberry Pi by Port forwarding and stuff like that but it’s complicated. My next option could be using Websockets but I felt it’s overkill for the applications running in the Pi.

Recently I received a Refcard from DZone regarding a protocol called MQTT. I was not aware of this Protocol before. So I thought of doing some experiments with it. I am not going much deeper into the protocol, the DZone refcard did a great job of explaining it well.

In a nutshell, MQTT consist of three parts.

  • Broker
  • Subscribers
  • Publishers

image

The Publisher publishes a message to a specific topic and any Subscriber subscribed to that topic receives the message. The Broker is the central hub. Both Publishers and Subscribers are connected to the Broker and it takes care of delivering the message to all the subscribers subscribed for the topic.

Brokers

We can implement our own broker using RabitMQ or a Mosca plugin for Node.js or any other MQTT brokers available in the market. To experiment with it, I used the CloudMQTT addon in Heroku. I used Heroku just to manage every thing from one central place.

Dev Environment

I created two sets of Node.js applications, one running in my computer as a publisher and another running in my RaspberryPi as a subscriber. Both had no direct connection; instead they were connected to the CloudMQTT broker. Below is some test code.

Publisher Code

var mqtt = require('mqtt');
var client = mqtt.createClient('<<PortNumber>>', 'm11.cloudmqtt.com', {
    username: '<<UserName>>',
    password: '<<Password>>'
});

client.on('connect', function () { // When connected

    // subscribe to a topic
    client.subscribe('TEMPERATURE_READING', function () {
        // when a message arrives, do something with it
        client.on('message', function (topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
        });
    });

    // publish a message to a topic
    client.publish('SET_TEMPERATURE', '24', function () {
        console.log("Message is published");
      });
});

 The above code acts as a Publisher as well as a Subscriber. For e.g. the above code can be a piece running on the Internet and the Pi can Publish the temperature readings in a periodic interval and log it in a central database. We can see the readings via a webapp or whichever way we need. Also if required we can set a temperature to all the connected Raspberry Pis by publishing a message to topic ‘SET_TEMPERATURE’.

Subscriber Code

var mqtt = require('mqtt'), url = require('url');
var client = mqtt.createClient('<<Portnumber>>', 'm11.cloudmqtt.com', {
    username: '<<UserName>>',
    password: '<<Password>>'
});

client.on('connect', function () { // When connected

    // subscribe to a topic
    client.subscribe('SET_TEMPERATURE', function () {
        // when a message arrives, do something with it
        client.on('message', function (topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
           // set the temperature. 
        });
    });

});

The code is very minimal and we could achieve easy communication to all the connected devices. In the above scenario, clients are always connected. If you want to end the connection then call ‘client.end()’.

Later I implemented a Broker using Mosca, and in both scenarios the system worked really well.

The IoT Zone is brought to you in partnership with GE Digital.  Discover how IoT developers are using Predix to disrupt traditional industrial development models.

Topics:
iot ,mqtt

Published at DZone with permission of Sony Arouje, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}