JSFiddle - React, Tailwind, and code Playground

by Jason Kridner

HTML

<script src="http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.javascript.git/plain/src/mqttws31.js"></script>
<button onclick="client.connect({timeout: 3, onSuccess: onSuccess, onFailure: onFailure});">1. Connect and Subscribe</button>
<button onclick="publish('{rate:10}','iot-2/type/iotsample-ti-bbst/id/9059af69c042/cmd/blink/fmt/json',0);">2. Publish</button>
<button onclick="client.disconnect();">3. Disconnect</button>
<div id="messages"></div>

JavaScript

try {
    var client = new Paho.MQTT.Client("184.172.124.189", 1883, "a:quickstart:0123456789ab");
} catch (ex) {
    console.log('error making client: ' + ex);
}
console.log('ClientId = ' + client._getClientId());
console.log('Host = ' + client._getHost());
client.startTrace();

function onSuccess() {
    console.log("Connected");
    client.subscribe('iot-2/type/+/id/9059af69c042/evt/+/fmt/json');
}

function onFailure(message) {
    console.log("Connection failed: " + message.errorMessage);
}

//Gets called if the websocket/mqtt connection gets disconnected for any reason
client.onConnectionLost = function (responseObject) {
    //Depending on your scenario you could implement a reconnect logic here
    console.log("connection lost: " + responseObject.errorMessage);
};

//Gets called whenever you receive a message for your subscriptions
client.onMessageArrived = function (message) {
    //Do something with the push message you received
    $('#messages').append('<span>Topic: ' + message.destinationName + '  | ' + message.payloadString + '</span><br/>');
};

//Creates a new Messaging.Message Object and sends it to the HiveMQ MQTT Broker
var publish = function (payload, topic, qos) {
    //Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
    console.log('Sending: ' + JSON.stringify(payload));
    var message = new Paho.MQTT.Message(payload);
    message.destinationName = topic;
    message.qos = qos;
    client.send(message);
}