I’ve a project where I’m using mqtt (HiveMQ for prototyping) for bi-directional communication. I can access the receiver via Hive’s web client but how do I implement it in browser JS?
I’ve downloaded a local copy of mqtt.min.js
from here and placed it in my JS
folder:
WEBFOLDER
+-- index.htm
|
+-- JS
|
+-- main.js
|
+-- mqtt.min.js
HTML:
<!DOCTYPE html>
<!-- Document started 22/11/2023 by BTV -->
<html>
<head>
<meta charset="UTF-8">
<title>COMMANDER</title>
<!-- JS-->
<script type="text/javascript" src="./JS/mqtt.min.js"></script>
<script type="text/javascript" src="./JS/main.js"></script>
</head>
<body>
Loaded...
</body>
</html>
main.js:
const options = {
"clientId": "random",
"keepalive": 60,
"connectTimeout": 3000,
"clean": true,
"protocolId": "MQIsdp",
"protocolVersion": 3
}
const client = mqtt.connect('https://55ab****83811.s1.eu.hivemq.cloud', options);
client.on("connect", () => {
client.subscribe("tcontrol", (err) => {
console.log("Connected...");
if (!err) {
client.publish("tcontrol", "Hello mqtt");
}
});
});
client.on("message", (topic, message) => {
// message is Buffer
console.log(message.toString());
client.end();
});
client.on('offline', () => {
console.log('Client is offline');
});
client.on('reconnect', () => {
console.log('Reconnecting to MQTT broker');
});
client.on('end', () => {
console.log('Connection to MQTT broker ended');
});
All I get from Firefox is the errors:
Firefox can’t establish a connection to the server at wss://55a***********db376d783811.s1.eu.hivemq.cloud/. mqtt.min.js:5:10448
and
The connection to wss://55ab4d************6d783811.s1.eu.hivemq.cloud/ was interrupted while the page was loading.
And from Safari:
failed: WebSocket is closed before the connection is established.
I’ve tried changing the url
protocol to ws
, wss
, http
, https
and mqtt
.
I’ve also tried importing directly from the UNPKG
link so not using a local download but with the same issues.