Skip to main content

MQTT using Node JS | Node JS Tutorial

This post shows you Simple MQTT Application using Node JS. There are three parts of the application.
For running any MQTT application, we need a 

1. Broker (The broker can be anywhere in the Internet or cloud or a local machine) 
2. Publisher (pub.js is the name of the file)
3. Subscriber (sub.js is the name of the file)

Check the following video for complete instructions.




In this example, we will be using a broker called https://www.hivemq.com

To use the cloud broker (mqtt://broker.hivemq.com) and connect the publisher and subscriber with a topic and a message. To install the Hive MQ software in your local machine (127.0.0.1) and run the same above code locally and make the connectivity between the pub-sub.

  • We open two new .js files called pub.js (publisher) and sub.js (subscriber) in Visual Studio Code. To install the mqtt module in NodeJS, we use the command “npm install mqtt” in C:/ terminal. 
  • We define our client as connecting to “mqtt://broker.hivemq.com”. We connect to the cloud broker in both publisher and subscriber js modules. We have taken temperature and temperature value as our message. The source code is given below. 
  • To execute our code, we open two terminals and use the command “node pub.js” and then in the other one, “node sub.js”. In the left command prompt, we have published, and in the one on the right, we have subscribed. We can see the outputs match each other. 
MQTT using Node JS
MQTT using Node JS

Using cloud broker:

Pub.js:

const mqtt = require("mqtt");

var client = mqtt.connect("mqtt://broker.hivemq.com");


client.on("connect",function()

{

    setInterval(function(){

        var random = Math.random()*50;

        console.log(random);

        if(random<30)

        {

            client.publish("Pradeep","temperature value: "+random.toString());

        }

    }),30000;

});


Sub.js:


const mqtt = require("mqtt");

var client = mqtt.connect("mqtt://broker.hivemq.com");


client.on("connect",function()

{

    client.subscribe("Shirish");

    console.log("Client subscribed ");

});


client.on("message",function(topic, message){

    console.log(message.toString());

});



Using local broker:

  • To run the broker locally, we first install HiveMQ on our system.
HiveMQ for MQTT
HiveMQ for MQTT

Pub.js:


const mqtt = require("mqtt");

var client = mqtt.connect("mqtt://127.0.0.1:1883");


client.on("connect",function()

{

    setInterval(function(){

        var random = Math.random()*50;

        console.log(random);

        if(random<30)

        {

            client.publish("Shirish","temperature value: "+random.toString());

        }

    }),30000;

});



Sub.js:


const mqtt = require("mqtt");

var client = mqtt.connect("mqtt://127.0.0.1:1883");


client.on("connect",function()

{

    setInterval(function(){

        var random = Math.random()*50;

        console.log(random);

        if(random<30)

        {

            client.publish("Shirish","temperature value: "+random.toString());

        }

    }),30000;

});



Comments

  1. Please how do I create an API for the mqtt publish in node.js

    ReplyDelete
  2. Thoda dekh ke dala karo sir niche wale mai pub or sub mai same data hai

    ReplyDelete

Post a Comment

Popular posts from this blog

Installing ns3 in Ubuntu 22.04 | Complete Instructions

In this post, we are going to see how to install ns-3.36.1 in Ubuntu 22.04. You can follow the video for complete details Tools used in this simulation: NS3 version ns-3.36.1  OS Used: Ubuntu 22.04 LTS Installation of NS3 (ns-3.36.1) There are some changes in the ns3 installation procedure and the dependencies. So open a terminal and issue the following commands Step 1:  Prerequisites $ sudo apt update In the following packages, all the required dependencies are taken care and you can install all these packages for the complete use of ns3. $ sudo apt install g++ python3 python3-dev pkg-config sqlite3 cmake python3-setuptools git qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools gir1.2-goocanvas-2.0 python3-gi python3-gi-cairo python3-pygraphviz gir1.2-gtk-3.0 ipython3 openmpi-bin openmpi-common openmpi-doc libopenmpi-dev autoconf cvs bzr unrar gsl-bin libgsl-dev libgslcblas0 wireshark tcpdump sqlite sqlite3 libsqlite3-dev  libxml2 libxml2-dev libc6-dev libc6-dev-i386 libc...

Installation of NS2 (ns-2.35) in Ubuntu 20.04

Installation of NS2 (ns-2.35) in Ubuntu 20.04 LTS Step 1: Install the basic libraries like      $] sudo apt install build-essential autoconf automake libxmu-dev Step 2: install gcc-4.8 and g++-4.8 open the file using sudo mode $] sudo nano /etc/apt/sources.list Include the following line deb http://in.archive.ubuntu.com/ubuntu bionic main universe $] sudo apt update $] sudo apt install gcc-4.8 g++-4.8 Step 3:  Unzip the ns2 packages to home folder $] tar zxvf ns-allinone-2.35.tar.gz $] cd ns-allinone-2.35/ns-2.35 Modify the following make files. ~ns-2.35/Makefile.in Change @CC@ to gcc-4.8 change @CXX@ to g++-4.8 ~nam-1.15/Makefile.in ~xgraph-12.2/Makefile.in ~otcl-1.14/Makefile.in Change in all places  @CC@ to gcc-4.8 @CPP@ or @CXX@ to g++-4.8 open the file: ~ns-2.35/linkstate/ls.h Change at the Line no 137  void eraseAll() { erase(baseMap::begin(), baseMap::end()); } to This void eraseAll() { this->erase(baseMap::begin(), baseMap::end()); } All changes ...

Installation of NS2 in Ubuntu 22.04 | NS2 Tutorial 2

NS-2.35 installation in Ubuntu 22.04 This post shows how to install ns-2.35 in Ubuntu 22.04 Operating System Since ns-2.35 is too old, it needs the following packages gcc-4.8 g++-4.8 gawk and some more libraries Follow the video for more instructions So, here are the steps to install this software: To download and extract the ns2 software Download the software from the following link http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.35/ns-allinone-2.35.tar.gz/download Extract it to home folder and in my case its /home/pradeepkumar (I recommend to install it under your home folder) $ tar zxvf ns-allinone-2.35.tar.gz or Right click over the file and click extract here and select the home folder. $ sudo apt update $ sudo apt install build-essential autoconf automake libxmu-dev gawk To install gcc-4.8 and g++-4.8 $ sudo gedit /etc/apt/sources.list make an entry in the above file deb http://in.archive.ubuntu.com/ubuntu/ bionic main universe $ sudo apt update Since, it...