mqtt web application

How to make MQTT web app using HTML and Javascript

Welcome to another tutorial of How to MQTT series. In this tutorial, we will be learning how to make MQTT web application or MQTT web dashboard using HTML, CSS and Javascript. In the previous blogs, I have explained how we can publish and subscribe the data from ESP8266 or raspberry pi using MQTT. You can show that data to web app that we will learn in this tutorial.

For this, we will be working on HTML, CSS and Javascript, So you can say that this tutorial will teach you how to make a MQTT web application or web dashboard using HTML CSS and Javascript. 

We will not be focusing much on the HTML and CSS side, and will be mainly talking about the functionality or backend using java script. The frontend in this video but it’s going to be really simple and we will not be diving in the details. But obviously you can create a nice looking dashboard.

Revision

If you have been following my MQTT series or youtube channel. You will be familiar with What is MQTT protocol?

If not, here is a short introduction to the MQTT protocol.

MQTT protocol is an IoT ( Internet of things) lightweight protocol that uses publish/subscribe to communicate between devices.

MQTT works well at unreliable networks.

There are a few MQTT terminologies that you should know, which are as follows.

  • Publish / Subscribe
  • Messages
  • Topics
  • Broker

We already discussed brokers in the “Mosquitto MQTT Broker Raspberry Pi” blog. In which we made our cheap MQTT broker.

Also, we have covered how to use the MQTT protocol in MATLAB, Python and android using MIT app inventor how to make real time plotting using python and MQTT protocol.

Also, PCBWay.com are the sponsor of this video. Who are experts at providing PCB, 3D, CNC services. Make sure to check their website.

pcbway.com
pcbway.com

Why and how we can use MQTT in web browser ?

You can control your MQTT devices from Mobile apps and dashboard, So why do we need a MQTT based web app or dashboard?

A browser is available on nearly every desktop computer/laptop/tablet/smartphone around the world 
and also it would be nice if you could use one standardized protocol to get messages on all types of devices, browsers, tablets, smartphones, embedded devices, sensors, etc.

Another question before starting the main code: How MQTT works on the web.

To use MQTT we will use websockets and without it we cannot see the mqtt data on a browser.

What are websockets ?

Websockets is a computer communication protocol, and provides full- duplex communication i.e. both ways over a single TCP/IP function and since we all know our browser uses http or secure http for communication, websocket is associated with http, as it uses it for initial connection establishment.

The client and the server or both devices start their connection using http and then upgrade to websockets.

How to make MQTT web app using HTML and Javascript
what are web sockets ?

How can we use MQTT in the browser and how is it different from normal MQTT messages ?

I have explained the flow of normal MQTT messages in detail but in short it works on the publish/subscribe model and if we use MQTT on websockets then MQTT messages are placed into websockets and then it is sent to client, where client first unpacks the MQTT message from the websocket and then it is processed as a normal mqtt message. The following image will simplify the explaination.

How to make MQTT web app using HTML and Javascript
MQTT over websockets

Code

Strcuture of the MQTT web app (HTML)

Let’s start by creating a index.html file and in the headers tag, we will write.

<head>
      <meta charset="utf-8">
      <title>High Voltages - MQTT</title>
      <link rel="stylesheet" href="style.css">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.min.js" type="text/javascript"></script>
      <script src="demo.js" type="text/javascript"></script>
   </head>

The above snippet, we are linking the style.css file and importing the paho mqtt library for java script and also we are linking the javascript file that we are going to create later in this project.

   <body>
      <div class="wrapper">
         <h1 id="Main_heading"> <b>High Voltages MQTT Dashboard</b></h1><br><br>
         <form id="connection-information-form">
            <b>Hostname or IP Address and Port Number:</b> 
            <input id="host" type="text" name="host" placeholder="broker address">
            
            <input id="port" type="text" name="port" value="8080"><br>
            <b>Username and Password:</b>
            <input id="username" type="text" name="Username" placeholder="Username"><br>
           
            <input id="password" type="password" name="password" placeholder="password"><br>
            <b>Subscription topic:</b>
            <input id="topic_s" type="text" name="topic_s" value="#"><br><br>
            <input type="button" onclick="startConnect()"  value="Connect">
            <input type="button"  onclick="startDisconnect()" value="Disconnect"> <br>
            <br><b>Publish Topic and Message:</b>
            <input id="topic_p" type="text" name="topic_p" placeholder="Publish topic">
            
            <input id="Message" type="text" name="message"  placehilder="Message">
            <input type="button" onclick="publishMessage()" value="Publish">
         </form>
         <div id="messages"></div>
      </div>

The body we have first created a form, that we will be using to get the broker address, port number, username, password, topics to publish and subscribe and buttons to connect , disconnect and publish message. In the end we have added a div box, that will be used to show the logs such as if we have recieved any message or if we are connected to the broker or disconnected etc.

Also we have assigned the ids to the elements so we can use them in CSS for styling and javascript for functionalities. If you would like to make some customised dashboard, i will suggest W3 Schools for learning HTML and CSS designing. The structure orf our MQTT web app is ready.

Styling of the web app (CSS)

For styling our mqtt web dashboard we use the following code. We created a new file style.css and pasted this code.

body {
    font-family: "Open Sans", sans-serif;
}
.wrapper {
    margin-left: auto;
    margin-right: auto;
    width: 60%;
    padding-right: 10px;
    padding-left: 10px;
}

input {
    width : 150px;
    margin: 0;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
input[type=text] {
  width:100%;
    padding: 12px 12px;
        height: 10px;

    margin: 8px 0;
}
input[type=password] {
  width:100%;
    padding: 12px 12px;
        height: 10px;

    margin: 4px 2px;
}
input[type=button] {
    background-color: gray;
    border: none;
    color: black;
    
    text-decoration: none;
    font-weight: bold;
        height: 20px;

    margin: 4px 2px;
    cursor: pointer;
}
input[type=text]:focus {
    background-color: lightblue;
}
input[type=button]:hover {
    background-color: #686868;
}

#Main_heading{
     text-align: center;
}

#messages {
    margin-top: 12px;
    margin-bottom: 12px;
    padding: 12px;
    width:100%;
    display: inline-block;
    border:1px solid black;
    max-height: 250px;
    min-height: 250px;
    overflow: scroll;
}
#messages span {
    overflow-y: scroll;
    overflow: scroll;
}

Backend of the webapp (Javascript)

This is the main part of this tutorial and javascript is responsible for creating a mqtt connection, publishing and subscribing to the broker while using the elements of html. So we created a file demo.js and firstly we created a function startConnect.

function startConnect(){

    clientID = "clientID - "+parseInt(Math.random() * 100);

    host = document.getElementById("host").value;   
    port = document.getElementById("port").value;  
    userId  = document.getElementById("username").value;  
    passwordId = document.getElementById("password").value;  

    document.getElementById("messages").innerHTML += "<span> Connecting to " + host + "on port " +port+"</span><br>";
    document.getElementById("messages").innerHTML += "<span> Using the client Id " + clientID +" </span><br>";

    client = new Paho.MQTT.Client(host,Number(port),clientID);

    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;

    client.connect({
        onSuccess: onConnect,
        userName: userId,
        passwordId: passwordId
    });


}

We call above function when the connect button on the user interface is clicked. Firstly it generates a random client id and then reads the value of host, port, username and password from the HTML form. Then it sets the message to the message box that connecting to host with hostname , port and client ID.

Then we created a client object using the Paho MQTT client function and then using the client variable we set some new functions such as onConnectionLost and onMessageArrived, which we will create now.

Then in the end using the client.connect we connects to the broker. When it is successsfull, it will call the onConnect function which we will create as well.

function onConnect(){
    topic =  document.getElementById("topic_s").value;

    document.getElementById("messages").innerHTML += "<span> Subscribing to topic "+topic + "</span><br>";

    client.subscribe(topic);
}



function onConnectionLost(responseObject){
    document.getElementById("messages").innerHTML += "<span> ERROR: Connection is lost.</span><br>";
    if(responseObject !=0){
        document.getElementById("messages").innerHTML += "<span> ERROR:"+ responseObject.errorMessage +"</span><br>";
    }
}

function onMessageArrived(message){
    console.log("OnMessageArrived: "+message.payloadString);
    document.getElementById("messages").innerHTML += "<span> Topic:"+message.destinationName+"| Message : "+message.payloadString + "</span><br>";
}

In the above snippet, three functions are defined.

we call onConnect function, when we are successfully connected to the cloud. There we reads the topic to subscribe from html form and subscribe to the topic.

In the onConnectionLost function, we are printing in the message box that there is an error. Then we read the errorcode and and print it in the message box.

OnMessageArrived function is called when any message is published on the topic we have subscribed. It will just print the message in the message box.

function startDisconnect(){
    client.disconnect();
    document.getElementById("messages").innerHTML += "<span> Disconnected. </span><br>";

}

function publishMessage(){
msg = document.getElementById("Message").value;
topic = document.getElementById("topic_p").value;

Message = new Paho.MQTT.Message(msg);
Message.destinationName = topic;

client.send(Message);
document.getElementById("messages").innerHTML += "<span> Message to topic "+topic+" is sent </span><br>";

}

Then we have two more functions, which basically disconnects the connection and the later function is for publishing a message. In which we read the values of message and topic from the web app. And then we create a message object, and the topic value is assign to Message.destinationName and then we simply send the message.

Alas! our Mqtt web app and dashboard is ready.

You can find the complete code in github.

Also you can read more about pahomqtt javascript library here.

Buying guide

Development boardAmazon (US)Ali express
ESP32How to make MQTT web app using HTML and JavascriptHow to make MQTT web app using HTML and Javascript
Raspberry pi zeroHow to make MQTT web app using HTML and JavascriptHow to make MQTT web app using HTML and Javascript

Raspberry pi 4
How to make MQTT web app using HTML and JavascriptHow to make MQTT web app using HTML and Javascript
ESP8266How to make MQTT web app using HTML and JavascriptHow to make MQTT web app using HTML and Javascript
DHT11How to make MQTT web app using HTML and JavascriptHow to make MQTT web app using HTML and Javascript
Buying guide for How to MQTT series

Video

Leave a Comment

Your email address will not be published. Required fields are marked *