I have a mosquitto broker running on one of my machines (say: mqtt://10.0.0.50:1883). I am trying to use MQTT with Node in an IoT gateway to receive messages from a mobile app and based on the topic for which message was sent perform some function. Once the action is complete publish another message on the same topic from gateway for mobile apps.
Gateway side:
client.on('connect', function () {
if (client.connected) {
client.subscribe(topics, {qos: 1}, function (err, granted) {
console.log('Subscribed to topics: ' + JSON.stringify(granted));
});
}
});
client.on('message', function (topic, message) {
switch (topic.toUpperCase()) {
case 'TEST':
console.log('test topic Called');
client.publish(topic, "test topic response msg", {qos: 1},
function () {
console.log("message response sent");
});
}
});
I tried this piece of code with another sample node.js code.
Client side:
client.on('connect', function () {
if (client.connected) {
client.subscribe("test", {qos: 1}, function (err, granted) {
console.log('Subscribed to topics: ' + JSON.stringify(granted));
});
client.publish("test", "send_me_test", {qos: 1}, function () {
console.log("request message published");
});
}
});
client.on('message', function (topic, message) {
console.log("Topic: " + topic + " request: " + message);
});
Response that I get after running client.js:
Connected to the broker at: mqtt://10.0.0.50:1883
Subscribed to topics: [{"topic":"test","qos":1}]
message published
Topic: test request: send_me_test
Topic: test request: test topics response msg
Topic: test request: test topics response msg
Topic: test request: test topics response msg
which goes on endlessly.
On the gateway side:
Jun 21 08:53:56 intel-quark api-server[16975]: test topic Called
Jun 21 08:53:56 intel-quark api-server[16975]: publishing response for topic: test with data: "test topics response msg"
Jun 21 08:53:56 intel-quark api-server[16975]: message published
keeps on repeating endlessly.
I am not able to figure out why it's happening likewise. My desired output was one response publish for one request publish.