-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (70 loc) · 1.87 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
75
76
77
78
79
80
// mqtt test
const mqtt = require('mqtt');
// test mqtt using broker from this site
// http://www.hivemq.com/demos/websocket-client/?
// const host = 'tcp://10.0.0.2:1884';
// mqtt server
// const host = 'mqtt://iot.eclipse.org:1883';
// mqtt through ws
// const host = 'ws://iot.eclipse.org:80/ws';
// a unique random string
// const clientId = 'eaca4d1b-34fc-487f-9fd0-ebdcb55322ff';
const host = 'mqtt://10.0.1.40:1883';
const clientId = 'client1';
const options = {
keepalive: 10,
clientId: clientId,
// protocol but not protocolId?
// protocolId: 'mqtt',
protocol: 'mqtt',
// protocol: 'ws',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
will: {
topic: 'Will',
payload: 'Connection Closed unexpectedly :(',
qos: 0,
retain: false
},
rejectUnauthorized: false
};
const mqttClient = mqtt.connect(host, options);
mqttClient.on('connect', function() {
console.log('connect');
mqttClient.subscribe(
'Popsense/People',
{ qos: 0 },
function(err) {
if (err) {
console.log('subscribe "Popsense/People" failed');
}
}
);
mqttClient.subscribe(
'Popsense/Product',
{ qos: 0 },
function(err) {
if (err) {
console.log('subscribe "Popsense/Product" failed');
console.log(err);
}
}
);
// mqttClient.publish("Popsense/People", '{"sss": "hello world!"}');
})
mqttClient.on('close', function() {
console.log(clientId + 'disconnected');
});
mqttClient.on('message', function(topic, message) {
const messageStr = message.toString();
// const messageJSON = JSON.parse(messageStr);
// console.log('typeof' + " :\n" + typeof(messageStr));
// console.log(topic + " :\n" + JSON.stringify(messageJSON, null, ' '));
console.log(topic + " :\n" + messageStr);
})
mqttClient.on('error', function(err) {
console.log(err);
mqttClient.end();
});