Hi All
Sorry to say I have been struggling to make a webpage connect to my HiveMQ server using Paho JS. The examples all don’t work for various reasons that I just don’t understand.
I’m trying to make the webpage “device agnostic”, so use the web version of Paho.
My HTML is:
<!-- import jquery library -->
<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<!-- import paho MQTT library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
My (limited) understanding of this is that it downloads the javascript engine from the web address. This seems to work as the javascript runs.
My javascript for connection is:
// Generate a new random MQTT client id on each page load
var MQTT_CLIENT_ID = "iot_web_"+Math.floor((1 + Math.random()) * 0x10000000000).toString(16);
// Create a MQTT client instance
//var MQTT_CLIENT = new Paho.MQTT.Client("iot.eclipse.com", 80, "/ws", MQTT_CLIENT_ID);
//var MQTT_CLIENT = new Paho.MQTT.Client("mqtt-dashboard.com", 8884, "/ws", MQTT_CLIENT_ID);
var MQTT_CLIENT = new Paho.MQTT.Client("<my alpha code>.s1.eu.hivemq.cloud", 8884, MQTT_CLIENT_ID);
// Tell the client instance to connect to the MQTT broker
MQTT_CLIENT.connect({
userName : "<my username for HiveMQ>",
password : "<my password for HiveMQ>",
useSSL : true,
onSuccess: function(){
console.log('Connected');
client.subscribe("SquashScore"); // the topic I want to publish to
message = new Paho.Message("Hello");
client.send(message);
}
});
console.log("attempting to connect");
// This is the function which handles button clicks
function myButtonWasClicked() {
var mqttMessage = new Paho.MQTT.Message("Score:12-13");
MQTT_CLIENT.send(mqttMessage);
}
The browser log shows “Attempting to connect” and then “Connected” which seems good. However, an error happens in the browser window when I try to publish by clicking the button.
The browser has a message of
Uncaught Error: AMQJS0011E Invalid state not connected.
at k.send (mqttws31.min.js:34:175)
at I.send (mqttws31.min.js:67:296)
at myButtonWasClicked (app.js:35:15)
at HTMLButtonElement.onclick (index.html:14:46)
which seems to mean that the page was never connected in the first place.
This should be easy - to me it looks like all the documentation is either out of date or just wrong.
Anybody got any help for what’s going wrong? Happy to provide other details if needed.
Thanks in advance.
Max