-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (73 loc) · 1.77 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
var num = 0;
var app = new Vue({
el: "#app",
data() {
return {
messages: [],
url: this.getConfig("mqtt.url", "ws://localhost:1884"),
topic: this.getConfig("mqtt.topic", "my/test/topic"),
client: null,
error: null,
content: ''
};
},
methods: {
connect() {
if (this.client) {
this.client.end();
}
try {
this.client = mqtt.connect(this.url);
} catch (err) {
this.error = err;
}
this.client.stream.on("error", err => {
this.error = err;
});
this.client.on("error", err => {
this.error = err;
});
this.client.on("offline", err => {
console.log("offline");
});
this.client.on("connect", () => {
console.log("connected");
this.setConfig("mqtt.url", this.url);
this.setConfig("mqtt.topic", this.topic);
this.client.subscribe(this.topic, function(err) {
if (err) {
this.error = err;
}
});
});
this.client.on("message", (topic, message) => {
// message is Buffer
console.log({ topic, message: message.toString(), num: num++ });
app.$data.messages.push({ topic, content: message.toString() });
});
},
getConfig(key, fallback) {
if (!localStorage) {
return fallback;
}
const val = localStorage.getItem(key) || fallback;
localStorage.setItem(key, val);
return val;
},
setConfig(key, val) {
if (!localStorage) {
return;
}
localStorage.setItem(key, val);
return val;
},
publish() {
this.client.publish(this.topic, this.content)
}
},
computed: {
connected() {
return !!this.client && this.client.connected;
}
}
});