From 35da8c78f492c533455c712fa9802085915c03e8 Mon Sep 17 00:00:00 2001 From: Tarun Singh Date: Mon, 22 Nov 2021 03:21:53 -0500 Subject: [PATCH] added connection timeout and refactored code --- server/model/monitor.js | 7 ++++++- server/util-server.js | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/server/model/monitor.js b/server/model/monitor.js index be0f98f7..2d4c02e4 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -321,7 +321,12 @@ class Monitor extends BeanModel { } } else if (this.type === "mqtt") { 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; } catch (error) { bean.status = DOWN; diff --git a/server/util-server.js b/server/util-server.js index 15690625..163547dc 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -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) => { + const { port, username, password, interval = 20 } = options; try { let client = mqtt.connect(hostname, { port, @@ -112,6 +113,9 @@ exports.mqttAsync = function (hostname, port = undefined, username = undefined, } } }); + setTimeout(() => { + client.end(); + }, interval * 1000); } catch (error) { reject(new Error(error)); }