-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
59 lines (49 loc) · 1.16 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
'use strict'
const BaseFacility = require('bfx-facs-base')
const mqtt = require('mqtt')
const aedes = require('aedes')()
const async = require('async')
class MQTTFacility extends BaseFacility {
constructor (caller, opts, ctx) {
super(caller, opts, ctx)
this.name = 'mqtt'
if (!opts.port) {
throw new Error('ERR_FACS_SERVER_MQTT_PORT_REQ')
}
this._hasConf = false
this.clients = []
this.init()
}
getClient (opts) {
const client = mqtt.connect(opts.url, opts.libOpts)
this.clients.push(client)
return client
}
async startServer () {
if (this.server) {
throw new Error('ERR_FACS_SERVER_MQTT_CREATE_DUP')
}
const srv = require('net').createServer(aedes.handle)
this.server = srv
this.aedes = aedes
return this.server.listen({
host: '0.0.0.0',
port: this.opts.port
})
}
_stop (cb) {
async.series([
next => { super._stop(next) },
() => {
if (this.server) {
this.server.close()
}
aedes.close()
for (const client of this.clients) {
client.end()
}
}
], cb)
}
}
module.exports = MQTTFacility