Basic javascript example using Mosquitto MQTT


#1

I am trying to get a basic example to work and it is not connecting to the MQTT broker. I double checked the host and port variables and they are correct, then I tested the broker and it is functioning correctly. Is there an error in the javascript?

<?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>
    <title>Websockets Using JavaScript MQTT Client</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<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+"<br>";
		out_msg=out_msg+"Message received 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);
	//mqtt.subscribe("sensor1");
	//message = new Paho.MQTT.Message("Hello World");
	//message.destinationName = "sensor1";
	//mqtt.send(message);
	  }

    function MQTTconnect() {
	document.getElementById("messages").innerHTML ="";
	var s = document.forms["connform"]["server"].value;
	var p = document.forms["connform"]["port"].value;
	if (p!="")
	{
	console.log("ports");
		port=parseInt(p);
		console.log("port" +port);
		}
	if (s!="")
	{
		//host=s;
		console.log("host");
		}


	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;
	console.log("Subscribing to topic ="+stopic);
	mqtt.subscribe(stopic);
	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;
		message = new Paho.MQTT.Message(msg);
		if (topic=="")
			message.destinationName = "test-topic"
		else
			message.destinationName = topic;
		mqtt.send(message);
		return false;
	}


    </script>

  </head>
  <body>
    <h1>Websockets Using JavaScript MQTT Client</h1>

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

</script>
	<script>
	var connected_flag=0
	var mqtt;
    var reconnectTimeout = 2000;
	var host="192.168.1.161";
	var port=1883;

	</script>

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

Server:  <input type="text" name="server"><br><br>
Port:    <input type="text" name="port"><br><br>
<input type="submit" value="Connect">
</form>
<hr>
<form name="subs" action="" onsubmit="return sub_topics()">
Subscribe Topic:   <input type="text" name="Stopic"><br><br>

<input type="submit" value="Subscribe">
</form>
<hr>
<form name="smessage" action="" onsubmit="return send_message()">

Message: <input type="text" name="message"><br><br>
Publish Topic:   <input type="text" name="Ptopic"><br><br>
<input type="submit" value="Submit">
</form>
Messages:<p id="messages"></p>

  </body>
</html>


#2

What errors (if any) are displayed in Chrome’s Developer’s Tools > Console for this page?


#3

I don’t know if it has anything to do with the problem, but the DOCTYPE is XHTML Transitional, yet the markup looks more like HTML5. At least the markup is not valid XHTML (my bet is it isn’t served as XHTML either. Nothing personal, I think most XHTML pages were not served as XHTML)


#4
connecting to 192.168.1.161 1883 
[websockets-3.htm:82:2](file:///var/www/html/javascript-websockets/websockets-3.htm)

Firefox can’t establish a connection to the server at ws://192.168.1.161:1883/mqtt. 
[mqttws31.js:979:17](https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js)

Firefox can’t establish a connection to the server at ws://192.168.1.161:1883/mqtt. 
[mqttws31.js:977:17](https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js)

Failed 
[websockets-3.htm:39:3](file:///var/www/html/javascript-websockets/websockets-3.htm)

Firefox can’t establish a connection to the server at ws://192.168.1.161:1883/mqtt. 
[mqttws31.js:979:17](https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js)

ports 
[websockets-3.htm:71:2](file:///var/www/html/javascript-websockets/websockets-3.htm)

port1883 
[websockets-3.htm:73:3](file:///var/www/html/javascript-websockets/websockets-3.htm)

host 
[websockets-3.htm:78:3](file:///var/www/html/javascript-websockets/websockets-3.htm) 

#5

Are you running this from the filesystem instead of a localhost server? Seeing "file://"s suggests you are opening it by some kind of “right click, open with the default OS browser” instead of putting the pages URL into a browsers address bar and opening it that way.


#6

It wont let me post the whole error because it contains more than 2 links, so ill post it in pieces:

connecting to 192.168.1.161 1883 websockets-3.htm:82:2

Firefox can’t establish a connection to the server at ws://192.168.1.161:1883/mqtt. mqttws31.js:979:17


#7

Firefox can’t establish a connection to the server at ws://192.168.1.161:1883/mqtt. mqttws31.js:977:17

Failed websockets-3.htm:39:3


#8

Failed websockets-3.htm:39:3
ports websockets-3.htm:71:2
port1883 websockets-3.htm:73:3
host websockets-3.htm:78:3


#9

so I did some research on how websockets work, it looks like I should be using the http port not the mqtt port. So I tried port 80 with no luck. I am running apache 2.4.29, mosquitto and paho on ubuntu 18.04.1.
This is the console log I received using port 80:
connecting to 192.168.1.161 80 websockets-3.htm:82:2 Firefox can’t establish a connection to the server at ws://192.168.1.161/mqtt. mqttws31.js:979:17 Failed websockets-3.htm:39:3 ports websockets-3.htm:71:2 port80 websockets-3.htm:73:3 host websockets-3.htm:78:3


#10

Perhaps a stupid question but…
Are you sure your MQTT server is running?


#11

I don’t count any question as stupid, statistically people always forget the easy solutions to problems. I did test the mqtt server from multiple machineson my network. I ended up adding some listeners to the mosquitto .conf file and was able to get this working.

listener 1883
protocol mqtt

listener 9001 
protocol websockets