From 0345719e53ed0e7a5f7c4368584584f14e797827 Mon Sep 17 00:00:00 2001 From: Tarun Singh Date: Thu, 20 Jan 2022 13:20:54 -0500 Subject: [PATCH] added cleartimeout in case client is already ended --- server/util-server.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/server/util-server.js b/server/util-server.js index 98de76623..e78ee6bc9 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -99,6 +99,12 @@ exports.mqttAsync = function (hostname, topic, okMessage, options = {}) { hostname = "mqtt://" + hostname; } + const timeoutID = setTimeout(() => { + debug("MQTT timeout triggered"); + client.end(); + reject("Timeout"); + }, interval * 1000); + debug("MQTT connecting"); let client = mqtt.connect(hostname, { @@ -114,26 +120,22 @@ exports.mqttAsync = function (hostname, topic, okMessage, options = {}) { client.on("error", (error) => { client.end(); + clearTimeout(timeoutID); reject(error); }); client.on("message", (messageTopic, message) => { if (messageTopic == topic) { + client.end(); + clearTimeout(timeoutID); if (message.toString() === okMessage) { - client.end(); resolve(`Topic: ${messageTopic}; Message: ${message.toString()}`); } else { - client.end(); reject(new Error(`Error; Topic: ${messageTopic}; Message: ${message.toString()}`)); } } }); - setTimeout(() => { - client.end(); - reject("Timeout"); - }, interval * 1000); - }); };