How to use sango - JavaScript WebSocket editing

I will explain how to use sango from browser's JavaScript.

To use sango using JavaScript from the browser, use WebSocket.

When opening MQTT connection information on sango's dashboard, information on "WebSocket connection destination" is described.

WebSocket接続先 : ws://example.shiguredo.jp:8080/mqtt

Let's make a note of this.

1. Implement JavaScript

from Paho mqttws31.js download, to read Leave aside.

2. Client implementation

The Connect part is common to both Pub / Sub.

In other languages, if you do not specify ClientID, most of them generate random character strings, but in JavaScript it is necessary to specify them yourself. Math.random() to use, etc., I think whether it is better to have a function that generates a random string.

Connect

var client; // MQTTのクライアントです
var clientId = "clientid-test"; // ClientIDを指定します。

function connect(){
    var user_name = "example@github";
    var pass = "<password>";
    var wsurl = "ws://example.shiguredo.jp:8080/mqtt";

    // WebSocketURLとClientIDからMQTT Clientを作成します
    client = new Paho.MQTT.Client(wsurl, clientId);

    // connectします
    client.connect({userName: user_name, password: pass, onSuccess:onConnect, onFailure: failConnect});
}

// 接続が失敗したら呼び出されます
function failConnect(e) {
    console.log("connect failed");
    console.log(e);
}

// 接続に成功したら呼び出されます
function onConnect() {
    console.log("onConnect");
}

Subscribe

client of onMessageArrived to register a callback function, subscribe you.

 // メッセージが到着したら呼び出されるコールバック関数
 function onMessageArrived(message) {
     console.log("onMessageArrived:"+message.payloadString);
 }

function subscribe(){
    // コールバック関数を登録します
    client.onMessageArrived = onMessageArrived;

    var topic = "example@github/a/b";
    // Subscribeします
    client.subscribe(topic);
}

Publish

Paho.MQTT.Message to create a message in, of Client send calls the method.

function publish(){
    var topic = "example@github/a/b";
    message = new Paho.MQTT.Message("Hello");
    message.destinationName = topic;
    client.send(message);
}