added connection timeout and refactored code

pull/875/head
Tarun Singh 3 years ago
parent 3306f4a8e0
commit 35da8c78f4

@ -321,7 +321,12 @@ class Monitor extends BeanModel {
} }
} else if (this.type === "mqtt") { } else if (this.type === "mqtt") {
try { try {
bean.msg = await mqttAsync(this.url, this.mqttPort, this.mqttUsername, this.mqttPassword, this.mqttTopic, this.mqttSuccessMessage); bean.msg = await mqttAsync(this.url, this.mqttTopic, this.mqttSuccessMessage, {
mqttPort: this.mqttPort,
mqttUsername: this.mqttUsername,
mqttPassword: this.mqttPassword,
interval: this.interval,
});
bean.status = UP; bean.status = UP;
} catch (error) { } catch (error) {
bean.status = DOWN; bean.status = DOWN;

@ -90,8 +90,9 @@ exports.pingAsync = function (hostname, ipv6 = false) {
}); });
}; };
exports.mqttAsync = function (hostname, port = undefined, username = undefined, password = undefined, topic, okMessage) { exports.mqttAsync = function (hostname, topic, okMessage, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const { port, username, password, interval = 20 } = options;
try { try {
let client = mqtt.connect(hostname, { let client = mqtt.connect(hostname, {
port, port,
@ -112,6 +113,9 @@ exports.mqttAsync = function (hostname, port = undefined, username = undefined,
} }
} }
}); });
setTimeout(() => {
client.end();
}, interval * 1000);
} catch (error) { } catch (error) {
reject(new Error(error)); reject(new Error(error));
} }

Loading…
Cancel
Save