[MQTT] Try to improve error handling

This commit is contained in:
Louis Lam 2022-01-13 12:42:34 +08:00
parent 6272514820
commit 227bbdea2f
2 changed files with 40 additions and 31 deletions

View file

@ -351,7 +351,7 @@ class Monitor extends BeanModel {
} }
} else if (this.type === "mqtt") { } else if (this.type === "mqtt") {
try { try {
bean.msg = await mqttAsync(this.url, this.mqttTopic, this.mqttSuccessMessage, { bean.msg = await mqttAsync(this.hostname, this.mqttTopic, this.mqttSuccessMessage, {
mqttPort: this.port, mqttPort: this.port,
mqttUsername: this.mqttUsername, mqttUsername: this.mqttUsername,
mqttPassword: this.mqttPassword, mqttPassword: this.mqttPassword,

View file

@ -12,7 +12,6 @@ const fs = require("fs");
const nodeJsUtil = require("util"); const nodeJsUtil = require("util");
const mqtt = require("mqtt"); const mqtt = require("mqtt");
// From ping-lite // From ping-lite
exports.WIN = /^win/.test(process.platform); exports.WIN = /^win/.test(process.platform);
exports.LIN = /^linux/.test(process.platform); exports.LIN = /^linux/.test(process.platform);
@ -94,19 +93,30 @@ exports.pingAsync = function (hostname, ipv6 = false) {
exports.mqttAsync = function (hostname, topic, okMessage, options = {}) { exports.mqttAsync = function (hostname, topic, okMessage, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const { port, username, password, interval = 20 } = options; const { port, username, password, interval = 20 } = options;
try {
// Adds MQTT protocol to the hostname if not already present // Adds MQTT protocol to the hostname if not already present
if (!/^(?:http|mqtt)s?:\/\//.test(hostname)) { if (!/^(?:http|mqtt)s?:\/\//.test(hostname)) {
hostname = "mqtt://" + hostname; hostname = "mqtt://" + hostname;
} }
debug("MQTT connecting");
let client = mqtt.connect(hostname, { let client = mqtt.connect(hostname, {
port, port,
username, username,
password password
}); });
client.on("connect", () => { client.on("connect", () => {
debug("MQTT subscribe topic");
client.subscribe(topic); client.subscribe(topic);
}); });
client.on("error", (error) => {
client.end();
reject(error);
});
client.on("message", (messageTopic, message) => { client.on("message", (messageTopic, message) => {
if (messageTopic == topic) { if (messageTopic == topic) {
if (message.toString() === okMessage) { if (message.toString() === okMessage) {
@ -118,12 +128,11 @@ exports.mqttAsync = function (hostname, topic, okMessage, options = {}) {
} }
} }
}); });
setTimeout(() => { setTimeout(() => {
client.end(); client.end();
}, interval * 1000); }, interval * 1000);
} catch (error) {
reject(new Error(error));
}
}); });
}; };