Skip to content

Commit

Permalink
fix: mqttClient connect/close methods (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
robertsLando authored Nov 27, 2020
1 parent dad493c commit 1ccab66
Show file tree
Hide file tree
Showing 3 changed files with 26,777 additions and 446 deletions.
40 changes: 25 additions & 15 deletions lib/MqttClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,6 @@ function init (config) {
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 }),
Expand All @@ -73,8 +70,13 @@ function init (config) {

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._key) {
options.key = config._key
}
if (config._cert) {
options.cert = config._cert
}
}

if (config.store) {
Expand All @@ -93,7 +95,12 @@ function init (config) {
}

try {
const client = mqtt.connect(options)
const serverUrl = `${protocol}://${parsed.hostname || config.host}:${
config.port
}`
debug('Connecting to ' + serverUrl)

const client = mqtt.connect(serverUrl, options)

this.client = client

Expand Down Expand Up @@ -260,19 +267,22 @@ MqttClient.prototype.cleanName = function (name) {
* Method used to close clients connection, use this before destroy
*/
MqttClient.prototype.close = function () {
const self = this
return new Promise(resolve => {
this.closed = true

if (this.client) {
this.client.end(!this.client.connected, () => resolve())
} else {
if (self.closed) {
resolve()
return
}
self.closed = true

this.removeAllListeners()

if (this.client) {
this.client.removeAllListeners()
if (self.client) {
self.client.end(true, {}, function () {
self.removeAllListeners()
resolve()
})
} else {
self.removeAllListeners()
resolve()
}
})
}
Expand Down
Loading

0 comments on commit 1ccab66

Please sign in to comment.