forked from mqttjs/MQTT.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.ts
60 lines (48 loc) · 1.08 KB
/
example.ts
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
import mqtt from './src/index'
const client = mqtt.connect('mqtt://broker.hivemq.com', {
keepalive: 3,
port: 1883,
reconnectPeriod: 15000,
rejectUnauthorized: false,
})
const randomNumber = Math.floor(Math.random() * 1000)
const testTopic = `presence_${randomNumber.toString()}`
function publish() {
const msg = `Hello mqtt ${new Date().toISOString()}`
client.publish(testTopic, msg, { qos: 1 }, (err2) => {
if (!err2) {
console.log('message published')
} else {
console.error(err2)
}
})
}
client.subscribe(testTopic, (err) => {
if (!err) {
console.log('subscribed to', testTopic)
} else {
console.error(err)
}
})
client.on('message', (topic, message) => {
console.log('received message "%s" from topic "%s"', message, topic)
})
setInterval(() => {
publish()
}, 2000)
client.on('error', (err) => {
console.error(err)
})
client.on('connect', () => {
console.log('connected')
publish()
})
client.on('disconnect', () => {
console.log('disconnected')
})
client.on('offline', () => {
console.log('offline')
})
client.on('reconnect', () => {
console.log('reconnect')
})