27/06/2019

Publish MQTT using Javascript

By snorlaxprime

Continuation to the previous post about the Automatic IoT Gate control, once we have connected the ESP8266 gate Opener to listen to the message broker, we will need a mechanism to be able to publish the message to the node it was listening to.

In the previous post, the ESP8266 was listening to the “/homeautomation/gate” topic. So in this post we are trying to create a simple website to publish “ON” and “OFF”message to this topic. This can be achieved with the following Javascript code:

<script src="https://assets.shiftr.io/js/mqtt-2.9.0.js"></script>
<script>
// Note: This line is only required when running in node.js 
var client = mqtt.connect('mqtt://try:try@broker.shiftr.io', {
    clientId: 'ESP8266' 
}); 
client.on('connect', function(){
       console.log('client has connected!');   
});
</script>
<script language="javascript">
function colorchange(id){
     var xmlhttp;
     xmlhttp=new XMLHttpRequest();
     if(document.getElementById(id).name == 'OFF' ){
         client.publish('/homeautomation/gate', 'ON');
         document.getElementById(id).name = 'ON';
         xmlhttp.open("GET","a.htm?ON",true);
         xmlhttp.send();
 } else { 
    client.publish('/homeautomation/gate', 'OFF'); 
    document.getElementById(id).name= 'OFF'; 
    xmlhttp.open("GET","a.htm?OFF",true);
    xmlhttp.send(); 
}
}
</script>

In the code above, we are using the broker.shiftr.io as the MQTT broker, and I am using their public try:try account, so please change this to your own account and password to ensure security.

The html code is crafted in such a way using the css to make it looks like an ON/OFF button, this is shown below, full credit to the author that made such and outstanding button.

The code that publish the “ON” message is executed from the “colorchange” function as below:

client.publish('/homeautomation/gate', 'ON');

and the code that publish the “OFF” message is executed from the same function as below:

client.publish('/homeautomation/gate', 'OFF');

If all is well you should see the “ON” and “OFF:” message being published to /homeautomation/gate topic, as shown in the below screen shot.

The full source code for the html page can be found in the following link. Please let me know if you like this post and subscribe for more projects related to IoT. Feel free to share this also.