-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher.js
62 lines (54 loc) · 1.42 KB
/
publisher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
(function(){
var user_name = "tonsho@github";
var pass = "pass";
var wsurl = "ws://lite.mqtt.shiguredo.jp:8080/mqtt";
var client; // MQTTのクライアントです
var clientId = "clientid-test"; // ClientIDを指定します。
$(document).ready(function() {
var $log = $("#log");
$log.print = function (message) {
this.append(message + "<br/>");
};
$("#publish-form").submit(function () {
console.log("connect");
publish($("#topic").val(), $("#message").val(), $log);
});
$("#topic").val(user_name + "/a/b");
});
function publish(topic, message, log) {
if (!client) {
connect(function() {
send(topic, message);
});
return;
}
send(topic, message);
function connect(callback) {
// 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) {
log.print("connect failed");
log.print(e);
alert(e);
}
// 接続に成功したら呼び出されます
function onConnect() {
log.print("onConnect");
callback();
}
}
function send(topic, message) {
var mqttMessage = new Paho.MQTT.Message(message);
mqttMessage.destinationName = topic;
client.send(mqttMessage);
}
}
}());