-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathMqttClient.js
111 lines (93 loc) · 2.64 KB
/
MqttClient.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
const EventEmitter = require('node:events')
const mqtt = require('mqtt')
class MqttClient extends EventEmitter {
constructor(options) {
super()
this.options = {
...options,
reconnectPeriod: 60_000, //in milliseconds, interval between two reconnections.
connectTimeout: 30_000, //in milliseconds, time to wait before a CONNACK is received
keepalive: 90, //in seconds
rejectUnauthorized: true,
resubscribe: false,
clean: true,
protocolVersion: 5,
family: 4, //Version of IP stack. Must be 4, 6, or 0. The value 0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.
}
this.client = null
}
connect() {
this.client = mqtt.connect(`mqtts://${this.options.host}`, this.options)
this.client.on('connect', (conAck) => {
//console.log('EVENT connect', conAck)
this.emit('connect', conAck)
})
// this.client.on('disconnect', (args) => {
// console.log('EVENT disconnect (initiated by broker)', args)
// })
this.client.on('offline', () => {
//console.log('EVENT offline')
this.emit('offline')
})
this.client.on('close', () => {
//console.log('EVENT close')
this.emit('close')
})
this.client.on('error', (error) => {
//console.log('EVENT error', error)
this.emit('error', error)
})
this.client.on('message', (topic, message, _packet) => {
const parsedMsg = JSON.parse(message.toString())
//console.log('EVENT message', topic, parsedMsg)
this.emit('message', topic, parsedMsg)
})
}
async end() {
try {
return this.client.endAsync()
} catch (err) {
return false
}
}
async publish(topic, json) {
return new Promise((resolve, reject) => {
const message = JSON.stringify(json)
const options = {
qos: 1,
}
this.client.publish(topic, message, options, (err, result) => {
if (err) {
console.log(err)
reject(err)
} else {
resolve(result)
}
})
})
}
async subscribe(topics) {
const options = {
qos: 1,
}
return new Promise((resolve, reject) => {
this.client.subscribe(topics, options, (err, result) => {
if (err) {
console.log('Error during subscribe()', err)
reject(err)
} else {
//console.log('EVENT subscribed')
this.emit('subscribed', result)
resolve(result)
}
})
})
}
isConnected() {
return this.client && this.client.connected
}
isReconnecting() {
return this.client && this.client.reconnecting
}
}
module.exports = MqttClient