-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
MqttClient.js
387 lines (319 loc) · 8.54 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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
'use strict'
// eslint-disable-next-line one-var
var reqlib = require('app-root-path').require,
mqtt = require('mqtt'),
utils = reqlib('/lib/utils.js'),
NeDBStore = require('mqtt-nedb-store'),
EventEmitter = require('events'),
storeDir = reqlib('config/app.js').storeDir,
debug = reqlib('/lib/debug')('Mqtt'),
url = require('native-url'),
inherits = require('util').inherits
debug.color = 5
const CLIENTS_PREFIX = '_CLIENTS'
const EVENTS_PREFIX = '_EVENTS'
const DEVICES_PREFIX = '$devices'
const BROADCAST_PREFIX = '_BROADCAST'
const NAME_PREFIX = 'ZWAVE_GATEWAY-'
var ACTIONS = ['broadcast', 'api']
var HASS_WILL = 'homeassistant/status'
/**
* The constructor
*/
function MqttClient (config) {
if (!(this instanceof MqttClient)) {
return new MqttClient(config)
}
EventEmitter.call(this)
init.call(this, config)
}
inherits(MqttClient, EventEmitter)
function init (config) {
this.config = config
this.toSubscribe = []
if (!config || config.disabled) {
debug('MQTT is disabled')
return
}
this.clientID = this.cleanName(NAME_PREFIX + config.name)
var parsed = url.parse(config.host || '')
var protocol = 'mqtt'
if (parsed.protocol) protocol = parsed.protocol.replace(/:$/, '')
var options = {
clientId: this.clientID,
reconnectPeriod: config.reconnectPeriod,
clean: config.clean,
rejectUnauthorized: !config.allowSelfsigned,
protocol: protocol,
host: parsed.hostname || config.host,
port: config.port,
will: {
topic: this.getClientTopic(),
payload: JSON.stringify({ value: false }),
qos: this.config.qos,
retain: this.config.retain
}
}
if (['mqtts', 'wss', 'wxs', 'alis', 'tls'].indexOf(protocol) >= 0) {
if (!config.allowSelfsigned) options.ca = config._ca
options.key = config._key
options.cert = config._cert
}
if (config.store) {
const COMPACT = { autocompactionInterval: 30000 }
var manager = NeDBStore(utils.joinPath(true, storeDir, 'mqtt'), {
incoming: COMPACT,
outgoing: COMPACT
})
options.incomingStore = manager.incoming
options.outgoingStore = manager.outgoing
}
if (config.auth) {
options.username = config.username
options.password = config.password
}
try {
var client = mqtt.connect(options)
this.client = client
client.on('connect', onConnect.bind(this))
client.on('message', onMessageReceived.bind(this))
client.on('reconnect', onReconnect.bind(this))
client.on('close', onClose.bind(this))
client.on('error', onError.bind(this))
client.on('offline', onOffline.bind(this))
} catch (e) {
debug('Error while connecting MQTT', e.message)
this.error = e.message
}
}
/**
* Function called when MQTT client connects
*/
function onConnect () {
debug('MQTT client connected')
this.emit('connect')
if (this.toSubscribe) {
for (var i = 0; i < this.toSubscribe.length; i++) {
this.subscribe(this.toSubscribe[i])
}
}
this.client.subscribe(HASS_WILL)
// subscribe to actions
// eslint-disable-next-line no-redeclare
for (var i = 0; i < ACTIONS.length; i++) {
this.client.subscribe(
[this.config.prefix, CLIENTS_PREFIX, this.clientID, ACTIONS[i], '#'].join(
'/'
)
)
}
this.emit('brokerStatus', true)
// Update client status
this.updateClientStatus(true)
this.toSubscribe = []
}
/**
* Function called when MQTT client reconnects
*/
function onReconnect () {
debug('MQTT client reconnecting')
}
/**
* Function called when MQTT client reconnects
*/
function onError (error) {
debug(error.message)
this.error = error.message
}
/**
* Function called when MQTT client go offline
*/
function onOffline () {
debug('MQTT client offline')
this.emit('brokerStatus', false)
}
/**
* Function called when MQTT client is closed
*/
function onClose () {
debug('MQTT client closed')
}
/**
* Function called when an MQTT message is received
*/
function onMessageReceived (topic, payload) {
debug('Message received on', topic)
if (topic === HASS_WILL) {
this.emit('hassStatus', payload.toString().toLowerCase() === 'online')
return
}
// remove prefix
topic = topic.substring(this.config.prefix.length + 1)
var parts = topic.split('/')
// It's not a write request
if (parts.pop() !== 'set') return
if (this.closed) return
if (isNaN(payload)) {
try {
payload = JSON.parse(payload)
} catch (e) {
payload = payload.toString()
}
} else payload = Number(payload)
// It's an action
if (parts[0] === CLIENTS_PREFIX) {
if (parts.length < 3) return
var action = ACTIONS.indexOf(parts[2])
switch (action) {
case 0: // broadcast
this.emit('broadcastRequest', parts.slice(3), payload)
// publish back to give a feedback the action is received
// same topic without /set suffix
this.publish(parts.join('/'), payload)
break
case 1: // api
this.emit('apiCall', parts.join('/'), parts[3], payload)
break
default:
debug('Unknown action received', action, topic)
}
} else {
// It's a write request on zwave network
this.emit('writeRequest', parts, payload)
}
} // end onMessageReceived
/**
* Returns the topic used to send client and devices status updateStates
* if name is null the client is the gateway itself
*/
MqttClient.prototype.getClientTopic = function (...devices) {
var subTopic = ''
for (var i = 0; i < devices.length; i++) {
var name = this.cleanName(devices[i])
subTopic += '/' + DEVICES_PREFIX + '/' + name
}
return (
this.config.prefix +
'/' +
CLIENTS_PREFIX +
'/' +
this.clientID +
subTopic +
'/status'
)
}
MqttClient.prototype.cleanName = function (name) {
if (!isNaN(name)) return name
name = name.replace(/\s/g, '_')
return name.replace(/[+*#\\.'`!?^=(),"%[\]:;{}]+/g, '')
}
/**
* Method used to close clients connection, use this before destroy
*/
MqttClient.prototype.close = function () {
return new Promise(resolve => {
this.closed = true
if (this.client) {
this.client.end(!this.client.connected, () => resolve())
} else {
resolve()
}
this.removeAllListeners()
if (this.client) {
this.client.removeAllListeners()
}
})
}
/**
* Method used to get status
*/
MqttClient.prototype.getStatus = function () {
var status = {}
status.status = this.client && this.client.connected
status.error = this.error || 'Offline'
status.config = this.config
return status
}
/**
* Method used to update client connection status
*/
MqttClient.prototype.updateClientStatus = function (connected, ...devices) {
if (this.client) {
this.client.publish(
this.getClientTopic(...devices),
JSON.stringify({ value: connected, time: Date.now() }),
{ retain: this.config.retain, qos: this.config.qos }
)
}
}
/**
* Method used to update client
*/
MqttClient.prototype.update = function (config) {
this.close()
debug('Restarting Mqtt Client after update...')
init.call(this, config)
}
/**
* Method used to subscribe tags for write requests
*/
MqttClient.prototype.subscribe = function (topic) {
if (this.client && this.client.connected) {
topic = this.config.prefix + '/' + topic + '/set'
debug('Subscribing to %s', topic)
this.client.subscribe(topic)
} else {
this.toSubscribe.push(topic)
}
}
/**
* Method used to publish an update
*/
MqttClient.prototype.publish = function (topic, data, options, prefix) {
if (this.client) {
options = options || {
qos: this.config.qos,
retain: this.config.retain
}
topic = (prefix || this.config.prefix) + '/' + topic
this.client.publish(topic, JSON.stringify(data), options, function (err) {
if (err) {
debug('Error while publishing a value', err.message)
}
})
} // end if client
}
/**
* Method used to get the topic with prefix/suffix
*/
MqttClient.prototype.getTopic = function (topic, set) {
return this.config.prefix + '/' + topic + (set ? '/set' : '')
}
/**
* Used to get client connection status
*/
Object.defineProperty(MqttClient.prototype, 'connected', {
get: function () {
return this.client && this.client.connected
},
enumerable: true
})
/**
* The prefix to add to broadcast values
*/
Object.defineProperty(MqttClient.prototype, 'broadcastPrefix', {
get: function () {
return BROADCAST_PREFIX
},
enumerable: true
})
/**
* The prefix to add to events
*/
Object.defineProperty(MqttClient.prototype, 'eventsPrefix', {
get: function () {
return EVENTS_PREFIX
},
enumerable: true
})
module.exports = MqttClient