-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt_probe.js
executable file
·100 lines (79 loc) · 1.95 KB
/
mqtt_probe.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
#!/usr/bin/env node
const mqtt = require('mqtt')
const args = require('minimist')(process.argv.slice(2))
const help = `
-h | --help help
--to broker to publish to
--from broker to subscribe to
-t topic
-r rate (publishes/second)
-n total number of publishes
-w time to wait after last message to exit (seconds)
`
// Settings
const To = args.to || 'localhost'
const From = args.from || 'localhost'
const Topic = args.t
if (!Topic) {
console.error('missing topic')
process.exit(1)
}
const Rate = parseFloat(args.r) || 1/60
const Num = parseInt(args.n) || 10
const Wait = parseFloat(args.w) || 5
//console.log(To, From, Topic, Rate, Num)
// MQTT connections
const recvClient = mqtt.connect(`mqtt://${From}`)
let sendClient
if (args.to === args.from) {
// No reason to reconnect to same address
sendClient = recvClient
}
else {
sendClient = mqtt.connect(`mqtt://${To}`)
}
// Connection setup
recvClient.on('connect', () => {
recvClient.subscribe(Topic)
recvClient.subscribe(Topic + '_verified')
})
recvClient.on('message', (topic, message) => {
console.log(`${Date.now()} ${topic} '${message.toString()}'`)
})
recvClient.on('error', error => {
console.error('error:', error)
process.exit(2)
})
sendClient.on('connect', () => {
sendMessages(sendClient)
})
sendClient.on('error', error => {
console.error('error:', error)
process.exit(3)
})
let iterations = 0
function publish(client) {
const data = JSON.stringify({
Warehouse: 'Warehouse123,456 Street,Country 00001',
Temperature: 15,
Timestamp: Date.now() //ms
})
console.log(`${Date.now()} ${Topic}_sent ${data}`)
client.publish(Topic, data)
++iterations
if (iterations === Num) {
// Wait a minute before exiting
setTimeout(shutdown, 1000 * Wait)
}
else {
// More messages!
setTimeout(publish, 1000 * Rate, client)
}
}
function sendMessages(client) {
publish(client)
}
function shutdown() {
sendClient.end()
recvClient.end()
}