forked from hezhii/mqttjs-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
executable file
·215 lines (191 loc) · 5.83 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
let connectionForm, subscriptionForm, publishForm, state, messageList, colorPicker;
let client, protol;
const TOPIC_COLOR_MAP = {};
const SUBSCRIBED_TOPICS = [];
$(function () {
colorPicker = $('#color');
colorPicker.colorpicker();
$('#connectButton').click(toggleConnect);
$('#subscribeButton').click(handleSubscribe);
$('#publishButton').click(handlePublish);
$('#topicList').click(handleUnsubscribe);
$('#clearMessage').click(clearMessage);
if (window.location.protocol === 'https:') {
protol = 'wss';
$('#port').val(443);
} else {
protol = 'ws';
$('#port').val(80);
}
});
function toggleConnect(event) {
if (client) {
client.end(true, function () {
state.attr('class', 'color-red');
state.children('span').text('disconnected');
$(event.target).text('Connect');
$('#topicList').empty();
SUBSCRIBED_TOPICS.length = 0;
client = null;
});
} else {
connectionForm = connectionForm || $('#connectionForm');
const formData = convertFormData(connectionForm.serializeArray());
client = mqtt.connect(`${protol}://${formData.host}:${formData.port}${formData.path || ''}`, {
username: formData.username,
password: formData.password,
clientId: formData.clientId,
keepalive: formData.keepalive && parseInt(formData.keepalive),
});
client.on('connect', function () {
state = state || $('#state');
state.attr('class', 'color-green');
state.children('span').text('connected');
$(event.target).text('Disconnect');
});
client.on('error', function (err) {
alert('There has some problems when create connection!\n Error is:' + err.message);
});
client.on('message', handleMessage);
}
return false;
}
function handleSubscribe(event) {
subscriptionForm = subscriptionForm || $('#subscriptionForm');
const formData = convertFormData(subscriptionForm.serializeArray());
const {
subscribeTopic: topic,
subscribeQoS: qos,
color
} = formData;
if (client) {
if (SUBSCRIBED_TOPICS.includes(topic)) {
alert('You are already subscribed to this topic!');
return false;
}
SUBSCRIBED_TOPICS.push(topic);
client.subscribe(topic, { 'qos': parseInt(qos) }, function (err) {
if (err) {
alert(`There has some problems when subscribe topic "${formData.topic}"!\nError:${err.message}`);
} else {
TOPIC_COLOR_MAP[topic] = color;
$('#topicList').append(
`<li class='topic-item' style='border-left-color: ${color}'>
<div class='content'>
<a class='close' data-topic='${topic}'>x</a>
<div class='qos'>Qos:${qos}</div>
<div class='topic'>${topic}</div>
</div>
</li>`
);
colorPicker.colorpicker('setValue', getRandomColor());
}
});
} else {
alert('You have to create connection first!');
}
event.preventDefault();
}
function handleUnsubscribe(event) {
const target = event.target;
if (target.tagName === 'A') {
const $target = $(target);
const topic = $target.data('topic');
client.unsubscribe(topic, function (err) {
if (err) {
alert(`Unsubscribe topic: ${topic} fail!`);
} else {
SUBSCRIBED_TOPICS.splice(SUBSCRIBED_TOPICS.indexOf(topic), 1);
$target.parents('li').remove();
}
});
return false;
}
}
function handlePublish() {
publishForm = publishForm || $('#publishForm');
const formData = convertFormData(publishForm.serializeArray());
const {
publishTopic: topic,
publishQoS: qos,
publishRetain: retain,
publishMessage: msg
} = formData;
if (client) {
client.publish(topic, msg, {
'qos': parseInt(qos),
'retain': retain === 'on'
});
} else {
alert('You have to create connection first!');
}
event.preventDefault();
}
function handleMessage(topic, msg, packet) {
messageList = messageList || $('#messageList');
messageList.append(`<li style="border-left: solid 10px ${getColorForSubscription(topic)};">
<div class="container-fluid message">
<div class="row small-text">
<div class="col-md-3">${new Date().toLocaleDateString()}</div>
<div class="col-md-5">Topic: ${topic}</div>
<div class="col-md-2">Qos: ${packet.qos}</div>
<div class="col-md-2">Retain: ${packet.retain}</div>
</div>
<div class="row">
<div class="col-md-12 message-content">
${msg}
</div>
</div>
</div>
</li>`);
}
function clearMessage() {
$('#messageList').empty();
}
/**
* 将 jQuery 序列化后的表单数据数组转换为对象
*
* @param {Array} arr
* @return {Object}
*/
function convertFormData(arr) {
let obj = {};
if (!arr || !arr.length) {
return obj;
}
arr.forEach(function (item) {
if (item.value) {
obj[item.name] = item.value;
}
});
return obj;
}
/**
* 获取订阅主题相应的颜色
*
* @param {String} topic - 主题
*/
function getColorForSubscription(topic) {
for (let _topic in TOPIC_COLOR_MAP) {
if (this.containTopic(_topic, topic)) {
return TOPIC_COLOR_MAP[_topic];
}
}
}
/**
* 判断一个主题是否包含另外一个主题
*
* @param {String} topic -父主题
* @param {String} subTopic - 子主题
*/
function containTopic(topic, subTopic) {
let pattern = topic.replace('+', '(.+?)').replace('#', '(.*)');
let regex = new RegExp('^' + pattern + '$');
return regex.test(subTopic);
}
function getRandomColor() {
let r = (Math.round(Math.random() * 255)).toString(16);
let g = (Math.round(Math.random() * 255)).toString(16);
let b = (Math.round(Math.random() * 255)).toString(16);
return r + g + b;
}