Thursday , July 18 2019

MOSCA MQTT Server Using Node JS

Share on WhatsApp
Share via email Share

Before we going to start something. We should know about what is the MQTT server and how it works. MQTT (Message Queuing Telemetry Transport) Protocol. This protocol allows the machine to communicate with each other regardless of the power consumption for the lightweight and small sensor and actuators. Moreover, in this Protocol, we have lots of QoS. Means that according to the environment you set the QoS.

There are three basic levels of QoS 0,1,2.

There are too many things which are related to this but for now, you just check out the actual document here http://mqtt.org/documentation

Now, let’s talk about the MQTT main components without these it will not be working as declared. The things are:

  1. Broker
  2. Publisher
  3. Subscriber

The Broker act like we saw in over daily routine life Broker. It means that every party should now the Broker. But, no seller or buyer will know it.

Here the Broker code which was running in Node.JS

var mosca = require('mosca');
var settings = {
		port:1883
}

var server = new mosca.Server(settings);

server.on('ready', function(){
console.log("ready");
});

After this Publisher comes in the live stream. As the Word describes its nature Publisher behave like the seller in this scope.

Here the Publisher code which was running in Node.JS

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://<mqtt-server-ip>');
client.on('connect', function () {
setInterval(function() {
client.publish('onoff', 'Turn on the light');
console.log('Message Sent');
}, 5000);
});

Finally, the thing which ends the story is the Subscriber. I think now you know the work of this thing. It actually works like the buyer.

Here the Subscriber code which was running in Node.JS

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://<mqtt server ip>')
client.on('connect', function () {
    client.subscribe('#');
})
client.on('message', function (topic, message) {
context = message.toString();
console.log(context)
})

 

Share on WhatsApp
Share via email Share

About Faheem

Faheem
An adaptable and responsible Software Engineer, who enjoys working with computers and the opportunity to learn new skills and work with new technologies is particularly attractive to me.

Leave a Reply

Your email address will not be published.