I have an MQTT publisher and subscriber written in Node JS.
I was wondering if it is possible to have it in the form of an API, that we can connect to and publish messages to using PostMan.
Here is my code for the publisher:
Publisher.js:
const mqtt = require('mqtt');
let client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', () =>{
console.log(`MQTT Client Connected Successfully!`);
client.publish('connected', `${true}`);
});
Here is my code for the Subscriber: Subscriber.js:
const mqtt = require('mqtt');
let client = mqtt.connect('mqtt://broker.hivemq.com');
let connected = false;
client.on('connect', () =>{
console.log(`MQTT Client Connected Successfully!`);
client.subscribe('connected');
});
client.on('message', (topic, message) =>{
if(topic === "connected"){
return handleGarageConnected(message);
}
console.log("No Handler for Topic %s", topic);
});
I want to be able to communicate with the Publisher / Subscriber over the internet using an API that I create.
Thank you.
You can make a function which publishes on the desired topic in publisher.js and export it. This way you can use in any other module.
Publisher.js
const mqtt = require('mqtt');
let client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', () =>{
console.log(`MQTT Client Connected Successfully!`);
client.publish('connected', `${true}`);
});
module.exports = {
publishTopic : function(payload){
client.publish('randomTopic');
}
}
You can make another file for your APIS, where you can import the exported function like so,
const mqttWrapper = require('./Publisher.js');
module.exports = {
randomApi : function (req, res) {
mqttWrapper.publishTopic("message");
}
}