-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMqtt.js
More file actions
168 lines (142 loc) · 5.06 KB
/
Mqtt.js
File metadata and controls
168 lines (142 loc) · 5.06 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
'use strict'
const mqtt = require('mqtt')
const mqttWildcard = require('mqtt-wildcard')
const fs = require('fs')
const path = require('path')
const debug = require('debug')('adonis:mqtt')
const {ioc} = require('@adonisjs/fold')
class Mqtt {
/**
* @return {Array}
*/
static get inject () {
return ['Adonis/Src/Event', 'Adonis/Src/Config', 'Adonis/Src/Helpers']
}
constructor (Event, Config, Helpers) {
if(Helpers.isAceCommand()) {
debug('MQTT not booting since execution is an ACE command')
return
}
this.Event = Event
this.Helpers = Helpers
this.Config = Config
this.listeners = []
this.Event.fire('MQTT:Initializing')
this._createClient()
this._configureListenersPath()
this._registerListeners()
this.Event.fire('MQTT:Initialized')
}
/**
* publish - publish <message> to <topic>
*
* @param {String} topic - topic to publish to
* @param {(String|Buffer)} message - message to publish
*
* @param {Object} [opts] - publish options, includes:
* @param {Number} [opts.qos] - qos level to publish on
* @param {Boolean} [opts.retain] - whether or not to retain the message
*
* @returns {Promise} Result of publish
*
* @example await Mqtt.sendMessage('test/topic', 'This is a message')
* @example await Mqtt.sendMessage('test/topic', 'This is a message', {qos: 2})
*/
async sendMessage(topic, message, opts) {
return new Promise((resolve) => {
this.client.publish(topic, message, opts, resolve);
})
}
_handleConnect () {
debug('Mqtt client connected')
this.Event.fire('MQTT:Connected')
}
_handleDisconnect () {
debug('Mqtt client disconnected')
this.Event.fire('MQTT:Disconnected')
}
_handleMessage (topic, message) {
debug('Mqtt message received on topic %s: %s', topic, message.toString())
for (const listener of this.listeners) {
const matchedWildcards = mqttWildcard(topic, listener.subscription)
if (matchedWildcards) {
debug('Found matching listener with subscription %s', listener.subscription)
listener.handleMessage(message.toString(), matchedWildcards)
}
}
}
/**
* Configure tasks absolute path for app
* /<project-dir>/app/MqttListeners
*
* @private
*/
_configureListenersPath () {
this.listenersPath = path.join(this.Helpers.appRoot(), 'app',
'MqttListeners')
this.listenersPath = path.normalize(this.listenersPath)
}
async _registerListeners () {
debug('Scan tasks path %s', this.listenersPath)
let taskFiles
try {
taskFiles = fs.readdirSync(this.listenersPath)
} catch (e) {
// If the directory isn't found, log a message and exit gracefully
if (e.code === 'ENOENT') {
throw new Error('MqttListeners folder not found!')
}
throw e
}
taskFiles = taskFiles.filter(file => path.extname(file) === '.js')
for (let taskFile of taskFiles) {
await this._registerListener(taskFile)
}
}
async _registerListener (file) {
const filePath = path.join(this.listenersPath, file)
let task
try {
task = require(filePath)
} catch (e) {
if (e instanceof ReferenceError) {
debug(
'Unable to import task class <%s>. Is it a valid javascript class?',
file)
return
} else {
throw e
}
}
// Get instance of task class
const taskInstance = ioc.make(task)
if (!taskInstance.subscription || taskInstance.subscription === '') {
console.error(`MqttListener ${file} does not have a subscription string!`)
} else {
this.client.subscribe(taskInstance.subscription)
debug('Subscribed to topic %s', taskInstance.subscription)
this.listeners.push(taskInstance)
}
}
_createClient () {
const options = {
username: (this.Config.get('mqtt.username') != '') ? this.Config.get('mqtt.username') : null,
password: (this.Config.get('mqtt.password') != '') ? this.Config.get('mqtt.password') : null,
// Necessary only if the server requires client certificate authentication
key: (fs.existsSync(this.Config.get('mqtt.key'))) ? fs.readFileSync(this.Config.get('mqtt.key')) : null,
cert: (fs.existsSync(this.Config.get('mqtt.cert'))) ? fs.readFileSync(this.Config.get('mqtt.cert')) : null,
// Necessary only if the server uses a self-signed certificate.
ca: [ (fs.existsSync(this.Config.get('mqtt.ca'))) ? fs.readFileSync(this.Config.get('mqtt.ca')) : null ],
// Necessary only if the server's cert isn't for "localhost".
checkServerIdentity: () => { return null; },
rejectUnauthorized: false,
}
this.client = mqtt.connect(`mqtt://${this.Config.get('mqtt.host')}:${this.Config.get('mqtt.port')}`, options)
this.client.on('connect', this._handleConnect.bind(this))
this.client.on('offline', this._handleDisconnect.bind(this))
this.client.on('close', this._handleDisconnect.bind(this))
this.client.on('end', this._handleDisconnect.bind(this))
this.client.on('message', this._handleMessage.bind(this))
}
}
module.exports = Mqtt