Skip to content

Instantly share code, notes, and snippets.

@bphermansson
Last active August 15, 2019 11:05
Show Gist options
  • Save bphermansson/8267cc9c634dd5b64b5a98e61ce654ec to your computer and use it in GitHub Desktop.
Save bphermansson/8267cc9c634dd5b64b5a98e61ce654ec to your computer and use it in GitHub Desktop.
Code for the blog post at http://paheco.nu/?p=323
<!DOCTYPE html>
<head>
<title>Javascript MQTT test</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>
</head>
<body>
<script>
// Connection settings
var broker = new Object();
broker.hostname = '192.168.1.190';
broker.port = 9001;
// Create a random client name
var random = Math.floor(Math.random() * (+65536 - +1)) + +1;
var url = window.location.pathname;
var clientname = url.substring(url.lastIndexOf('/')+1) + random;
// Write the name
console.log(clientname);
// Create a new client
client = new Paho.MQTT.Client(broker.hostname, Number(broker.port), clientname);
// If the broker demands a username and password, set it here.
var conOpts = new Object();
conOpts.userName='emonpi';
conOpts.password='emonpimqtt2016';
// We also define functions for a successful connection and when a message arrives.
conOpts.onSuccess = onConnect;
client.onMessageArrived = onMessageArrived;
// All set, connect!
client.connect(conOpts);
// On a successful connection, tell the log and subscribe to a topic.
// We can also send a message directly.
function onConnect() {
console.log("onConnect");
client.subscribe("mqttjs");
/*
message = new Paho.MQTT.Message("Hello from " + clientname);
message.destinationName = "mqttjs"; // = topic to send to
client.send(message);
*/
}
// This is the function that runs when a message with the correct topic arrives.
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment