Added authentication logic

This commit is contained in:
Tarun Singh
2021-11-16 20:44:10 -05:00
parent 3721d11259
commit 3f5133d1ba
4 changed files with 48 additions and 12 deletions

View File

@@ -90,21 +90,33 @@ exports.pingAsync = function (hostname, ipv6 = false) {
});
};
exports.mqttAsync = function (hostname, topic, okMessage) {
exports.mqttAsync = function (hostname, port = undefined, username = undefined, password = undefined, topic, okMessage) {
return new Promise((resolve, reject) => {
try {
let client = mqtt.connect(hostname);
console.log({
hostname,
port,
username,
password
});
let client = mqtt.connect(hostname, {
port,
username,
password
});
client.on("connect", () => {
console.log(`Connected to ${hostname}:${port}, ${username}, ${password}`);
client.subscribe(topic);
});
client.on("message", (messageTopic, message) => {
console.log(messageTopic);
if (messageTopic == topic && message.toString() !== okMessage) {
client.end();
reject(new Error(`Error; Topic: ${messageTopic}; Message: ${message.toString()}`));
} else {
client.end();
resolve(`Topic: ${messageTopic}; Message: ${message.toString()}`);
if (messageTopic == topic) {
if (message.toString() === okMessage) {
client.end();
resolve(`Topic: ${messageTopic}; Message: ${message.toString()}`);
} else {
client.end();
reject(new Error(`Error; Topic: ${messageTopic}; Message: ${message.toString()}`));
}
}
});
} catch (error) {