Showing posts with label Browser. Show all posts
Showing posts with label Browser. Show all posts

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>


2012/11/16

Freeduino/Arduino Web Controlled (Configured) Automatic Switches

Inspired by Freeduino/Arduino Web Sensors And Switches on cheaphousetek blog on Oct. 20, 2012, go a step forward, automatically controll the switches by setting the sensors criteria. It comes out the sketch at the bottom of this post.
By setting the lower limits, upper limits and switch on/off using a browser, one can monitor the conditions of all switches  remotely.
To control the web server outside the local area network, the NAT function of IP router should be enabled. To secure your web server, the SSH or VNC connection should be established.

Pins Used

Sensors: A2, A3
Switches: D2, D3, D4, D5, D6, D7, D8, D9

Output


Sketch


// Freeduino/Arduino Web Controlled Automatic Switches version 1.0
// By Befun Hung on Nov. 16 2012
// Modified From Freeduino/Arduino Web Sensors And Switches At cheaphousetek Blog 
// The Sketch Works On Arduino IDE 1.02

#include <Ethernet.h>
#include <SPI.h>
//network NB: Pins 10, 11, 12 and 13 are reserved for Ethernet module. 
#define sensorPinStart 2
#define noOfSensors 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[] = { 255, 255, 255, 0 };
String inString = String(100);
String minValue, maxValue;
int defaultMinValue[] = {55, 56, 57, 58, 59, 60, 61, 62, 63};
int defaultMaxValue[] = {60, 61, 62, 63, 64, 65, 66, 67, 68};
String defaultOnValue[] = {"Low", "Low", "Low", "Low", "Low", "Low", "Low", "Low", "Low"};
String Led;
int led[] = {00, 2, 3, 4 ,5 ,6 ,7 ,8 ,9  }; //pin num 0 in arry is not used
int numofleds = 8; //number of switches
String value[] = {"off","off","off","off","off","off","off","off","off"}; //startup all led are off
EthernetServer server(80);

void setup()
{
  delay(250); 
  Serial.begin(9600);
  Ethernet.begin(mac, ip,gateway,subnet); 
  server.begin();
  //set pin mode
  for (int j = 1; j < (numofleds + 1); j++)
  {
    pinMode(led[j], OUTPUT);
  }
  Serial.println("Serial READY");
  Serial.println("Ethernet READY");
  Serial.println("Server READY");
}

void loop()
{
  EthernetClient client = server.available();  
  if (client)
  {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    while (client.connected()) 
    {     
      if (client.available()) 
      {      
        char c = client.read();
        // if we've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so we can send a reply
        if (inString.length() < 35) 
        {
          inString.concat(c);
        } 
        if (c == '\n' && current_line_is_blank) 
        {                    
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<html>");
          client.println("<meta http-equiv=\"refresh\" content=\"5\">");
          client.println("<body><form method=get>");
          client.println("<center><p><h1>Freeduino/Arduino Web Controlled Automatic Switches</h1></p><hr></center>"); 
          client.println("<h2>");
          // Sensor Reading and Setting -----------------------------------------------------------------------------
          client.println("Sensor Reading And Setting:<br>");
          for (int analogChannel = sensorPinStart ; analogChannel < sensorPinStart+noOfSensors ; analogChannel++)
          {
            minValue = String("Low") + analogChannel;
            // fixValue = String("Fix") + analogChannel;
            maxValue = String("High") + analogChannel;
            Led = String("RelayOn") + analogChannel;
            int sensorReading = analogRead(analogChannel);
            
            if (inString.indexOf(minValue+"=Dn") > 0) defaultMinValue[analogChannel] -= 1;
            if (inString.indexOf(minValue+"=Up") > 0) defaultMinValue[analogChannel] += 1;
            if (inString.indexOf(maxValue+"=Dn") > 0) defaultMaxValue[analogChannel] -= 1;
            if (inString.indexOf(maxValue+"=Up") > 0) defaultMaxValue[analogChannel] += 1; 
            if (inString.indexOf(Led+"=High") > 0)    defaultOnValue[analogChannel] = "Low";
            if (inString.indexOf(Led+"=Low") > 0)     defaultOnValue[analogChannel] = "High";
            client.print("Input A");
            client.print(analogChannel);
            client.print(":");
            client.print(sensorReading);
            client.print("  Low");
            // client.print(analogChannel);
            client.print(":");
            client.print(defaultMinValue[analogChannel]);
            client.print("<input type=submit name="+minValue+" value=Dn><input type=submit name="+minValue+" value=Fix><input type=submit name="+minValue+" value=Up>");
            client.print("  High");
            // client.print(analogChannel);
            client.print(":");
            client.print(defaultMaxValue[analogChannel]);
            client.print("<input type=submit name="+maxValue+" value=Dn><input type=submit name="+maxValue+" value=Fix><input type=submit name="+maxValue+" value=Up>");
            client.print("  On");
            // client.print(analogChannel);
            client.print(":");
            client.print("<input type=submit name="+Led+" value="+defaultOnValue[analogChannel]+">");
            client.println("<br>");
          }
          // Switch Monitoring -------------------------------------------------------------------------------------------
          client.println("<p></p>Switches Status:<br>"); 
          for (int i=1; i < (noOfSensors+1) ; i++)
          { 
            Led = String("Switch") + i;
            int sensorReading = analogRead(sensorPinStart+i-1);
            if ((sensorReading > defaultMaxValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "High")) {
              digitalWrite(led[i], HIGH);
              value[i] = "on";
            }
            if ((sensorReading < defaultMinValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "High")) {
              digitalWrite(led[i], LOW);
              value[i] = "off";
            }
            if ((sensorReading < defaultMinValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "Low")) {
              digitalWrite(led[i], HIGH);
              value[i] = "on";
            }
            if ((sensorReading > defaultMaxValue[sensorPinStart+i-1]) && (defaultOnValue[sensorPinStart+i-1] == "Low")) {
              digitalWrite(led[i], LOW);
              value[i] = "off";
            }
            client.println(Led+"  <input type=submit name="+Led+" value="+value[i]+">"+"<br>");
          }
          client.println("</form><hr></h2>");
          client.println("<center>The web page will automatically refresh every 5 seconds.</center>");
          client.println("</html></body>");
          break;
        }
        if (c == '\n') 
        {
          // we're starting a new line
          current_line_is_blank = true;
        } 
        else if (c != '\r') 
        {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
      }  // End of if (client.available)
    }  // End of while (client.connected())
    // give the web browser time to receive the data
    delay(1);
    inString = "";
    client.stop();
  } //End of if (client)
}

2012/10/20

Freeduino/Arduino Web Sensors And Switches

Arduino Uno/Duemilanove is an useful gadget, combined with an W5100 Ethernet Shield , linked with some analog sensors and relays by wires, one can easily implements an simple remote web sensor monitoring and switch controlling system using an browser.

Pins Used

W5100 Ethernet Shield -- D10, D11, D12, D13
Analog Sensors -- A0, A1, A2, A3, A4, A5
Switches -- D2, D3, D4, D5, D6, D7, D8, D9

Output On Chrome Browser


Sketch


// modified from Instructables Arduino Led Server and Arduino Example WebServer 
// by Befun Hung on Oct. 20, 2012
// the sketch works on Arduino IDE 1.01

#include <Ethernet.h>
#include <SPI.h>
//network NB: Pins 10, 11, 12 and 13 are reserved for Ethernet module. 
#define sensorPinStart 0 //change to 2 if using Arduino Ethernet Shield 05 or 06
#define noOfSensors 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[] = { 255, 255, 255, 0 };
String inString = String(35);
String Led;
int led[] = {00, 2, 3, 4 ,5 ,6 ,7 ,8,9  }; //Led pins num 0 in arry is not used
int numofleds = 8; //numofleds
String value[] = {"off","off","off","off","off","off","off","off","off"}; //startup all led are off
EthernetServer server(80);
String data;

void setup()
{
  Serial.begin(9600);
  Ethernet.begin(mac, ip,gateway,subnet); 
  server.begin();
  //set pin mode
  for (int j = 1; j < (numofleds + 1); j++)
  {
    pinMode(led[j], OUTPUT);
  }
  Serial.println("Serial READY");
  Serial.println("Ethernet READY");
  Serial.println("Server READY");
}

void loop()
{
  EthernetClient client = server.available();  
  if (client)
  {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    while (client.connected()) 
    {     
      if (client.available()) 
      {      
        char c = client.read();
        // if we've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so we can send a reply
        if (inString.length() < 35) 
        {
          inString.concat(c);
        } 
        if (c == '\n' && current_line_is_blank) 
        {                    
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<html>");
          client.println("<meta http-equiv=\"refresh\" content=\"5\">");
          client.println("<body><form method=get>");
          client.println("<center><p><h1>Freeduino/Arduino Web Sensor And Switch</h1></p><hr></center>"); 
          client.println("<h2>");
          client.println("Sensor Reading:<br>");
          for (int analogChannel = sensorPinStart ; analogChannel < sensorPinStart+noOfSensors ; analogChannel++)
          {
            int sensorReading = analogRead(analogChannel);
            client.print("Analog Input ");
            client.print(analogChannel);
            client.print(" : ");
            client.print(sensorReading);
            client.println("<br>");
          }
          client.println("<p></p>Switches Status:<br>");
          for(int i=1;i < (numofleds + 1) ;i++) 
          { 
            Led = String("Switch") + i;
            if(inString.indexOf(Led+"=off")>0 || inString.indexOf("all=on")>0)
            {
              Serial.println(Led+"on");
              digitalWrite(led[i], HIGH);
              value[i] = "on"; 
            }
            else if(inString.indexOf(Led+"=on")>0 || inString.indexOf("all=off")>0 )
            {          
              Serial.println(Led+"off");
              digitalWrite(led[i], LOW);
              value[i] = "off";
            }
            client.println(Led+"  <input type=submit name="+Led+" value="+value[i]+">"+"<br>");
          }
          client.println("<p></p>Switches Action:<br>");
          client.println("All <input type=submit name=all value=on><input type=submit name=all value=off>");
          client.println("</form><hr></h2>");
          client.println("<center>The web page will automatically refresh every 5 seconds.</center>");
          client.println("</html></body>");
          break;
        }
        if (c == '\n') 
        {
          // we're starting a new line
          current_line_is_blank = true;
        } 
        else if (c != '\r') 
        {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
      }  // End of if (client.available)
    }  // End of while (client.connected())
    // give the web browser time to receive the data
    delay(1);
    inString = "";
    client.stop();
  } //End of if (client)
}