2018/04/02

A Simple MQTT Websocket Client

The code is based on wbesockets-3.html by Steve Cope on "Using The JavaScript MQTT Client With Websockets" combines code by weldmich on "Developing MQTT Client" and web page on "How to program messaging apps in JavaScript" of IBM Knowledge Center. With the HTML file, anyone can uses any web browser supporting websockets to communicate with any MQTT IoT device without the need to download and use any mqtt client app. For example, I can use google chrome opening the HTML file to control my homebrew web switch MakerSwitch Tail WiFi.

Screen Capture

HTML File


<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<style>

#messages

{

   background-color:yellow;

   font-size:3;

   font-weight:bold; 
   line-height:140%;

}

#status

{

   background-color:red;

   font-size:4;

   font-weight:bold;

   color:white;

   line-height:140%;

}



</style>
  
<head>
    
<meta charset="utf-8">
    
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>MQTT Websocket Client</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
 
<script type = "text/javascript" 

        src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
<script type = "text/javascript">




 function onConnectionLost(){

      console.log("connection lost");

      document.getElementById("status").innerHTML = "Connection Lost";

      document.getElementById("messages").innerHTML ="Connection Lost";

      connected_flag=0;

   }

   function onFailure(message) {

      console.log("Failed");

      document.getElementById("messages").innerHTML = "Connection Failed- Retrying";

      setTimeout(MQTTconnect, reconnectTimeout);

   }

   function onMessageArrived(r_message){

      out_msg="Message received: \""+r_message.payloadString;

      out_msg=out_msg+"\" from Topic: "+r_message.destinationName;

      //console.log("Message received ",r_message.payloadString);

      console.log(out_msg);

      document.getElementById("messages").innerHTML =out_msg;

   }

   function onConnected(recon,url){

      console.log(" in onConnected " +reconn);

   }

   function onConnect() {

      // Once a connection has been made, make a subscription and send a message.

      document.getElementById("messages").innerHTML ="Connected to "+host +"on port "+port;

      connected_flag=1;
      document.getElementById("status").innerHTML = "Connected";

      console.log("on Connect "+connected_flag);

   }



  function MQTTconnect() {

      document.getElementById("messages").innerHTML ="";

      var s = document.forms["connform"]["server"].value;

      var p = document.forms["connform"]["port"].value;

      if (p!="")
{

         port=parseInt(p);

      }

      if (s!="")
{

         host=s;
      }


      console.log("connecting to "+ host +" "+ port);

      mqtt = new Paho.MQTT.Client(host,port,"clientjsaaa");

      //document.write("connecting to "+ host);

      var options = {

         timeout: 3,

         onSuccess: onConnect,

         onFailure: onFailure,

      };

      mqtt.onConnectionLost = onConnectionLost;

      mqtt.onMessageArrived = onMessageArrived;

      mqtt.onConnected = onConnected;


      mqtt.connect(options);

      return false;

  
}

   function sub_topics(){

      document.getElementById("messages").innerHTML ="";

      if (connected_flag==0){

         out_msg="<b>Not Connected so can't subscribe</b>";
         console.log(out_msg);

         document.getElementById("messages").innerHTML = out_msg;

         return false;

      }

      var stopic= document.forms["subs"]["Stopic"].value;

      var qos = parseInt($('#subQos option:selected').val());
      console.log("Subscribing to topic "+stopic+" with Qos "+qos);

      mqtt.subscribe(stopic, {qos: qos});

      return false;

   }

   function send_message(){

      document.getElementById("messages").innerHTML ="";

      if (connected_flag==0){

         out_msg="<b>Not Connected so can't send</b>";
            console.log(out_msg);

         document.getElementById("messages").innerHTML = out_msg;

         return false;

      }

      var msg = document.forms["smessage"]["message"].value;

      console.log(msg);


      var topic = document.forms["smessage"]["Ptopic"].value;

      var qos = parseInt($('#pubQos option:selected').val());
      var retain = $('#toRetain').is(':checked');
      message = new Paho.MQTT.Message(msg);

      if (topic=="")

         message.destinationName = "test-topic";
      else

         message.destinationName = topic;

      message.qos = qos;
      message.retained = retain;
      console.log("Published to topic "+topic+" with Qos "+qos);
      mqtt.send(message);

      return false;

   } 

</script>

  
</head>
  
<body>

   <h1>MQTT Websocket Client</h1>

   <script type = "text/javascript">
//ll

</script>

   <script>

      var connected_flag=0

      var mqtt;

      var reconnectTimeout = 2000;

      var host="broker.mqttdashboard.com";
      var port=8000;
   </script>


   <div id="status">Connection Status: Not Connected</div>
   <form name="connform" action="" onsubmit="return MQTTconnect()">

   <fieldset>
   <legend id="Connect">Connect</legend>
      Server:  <input type="text" id="broker" name="server" placeholder="broker.mqttdashboard.com">
      Port:    <input type="text" id="port" name="port" placeholder="8000">
      <input type="submit" value="Connect">

   </fieldset>
   </form>
   <form name="smessage" action="" onsubmit="return send_message()">


   <fieldset>
   <legend id="Publish">Publish</legend>
      Topic:   <input type="text" id="pubTopic" name="Ptopic">
      Message: <input type="text" id="payload" name="message">
      <select id="pubQos">
         <option value="Qos" disabled>Qos</option>
         <option value="0">0</option>
         <option value="1" selected>1</option>
         <option value="2">2</option> 
      </select>
      <label>Retain</label>
      <input id="toRetain" type="checkbox">
      <input type="submit" value="Publish">

   </fieldset>
   </form>
   <form name="subs" action="" onsubmit="return sub_topics()">

   <fieldset>
   <legend id="Subscribe">Subcribe</legend>
      Topic:   <input type="text" id="subTopic" name="Stopic">

      <select id="subQos">
         <option value="Qos" disabled>Qos</option>
         <option value="0">0</option>
         <option value="1" selected>1</option>
         <option value="2">2</option>         
      </select>
      <input type="submit" value="Subscribe">

   </fieldset>
   </form>
   <p id="messages"></p>

  
</body>

</html>


No comments:

Post a Comment