Skip to content Skip to sidebar Skip to footer

Mqtt Async Wait For Messagse Then Respond To Http Post Request

I am new to node.js am trying to make a webhook, where I get an HTTP post request and want to send a request over mqtt and wait for mqtt messages in reference to the MQTT message a

Solution 1:

You don't need to call response.send(array) from within the route handler, you can do it externally.

var array = [];
var resp;
var n = 10; //number of messages to wait for
var timeOutValue = 5000; //wait 5 seconds
var timer;

const client = mqtt.connect(MQTTServer)
var count =0;
client.on('message', (topic, message) => {
  array.push(message); 
  count ++ 
  if (count == n) {
     resp.send(array);
     client.unsubscribe('inTopic');
     resp = undefined;
     counter = 0;
     array = [];
     clearTimeout(timer)
  }
}

app.post('/test', function (request, response) {

resp = response;
client.publish ('outTopic' , 'request ');
client.subscribe('inTopic');

  timer = setTimeout(function(){
    if (resp) {
        resp.send(array);
        resp = undefined;
        client.unsubscribe('inTopic');
        counter = 0;
        array = []
    }
  }, timeOutValue);

}

It's not pretty (and it's single call at a time...) but it should work.


Solution 2:

You can define a global variable (such as global.results={} and in your client.on('message', callback) update the value with upcoming messages.

  client.on('message', (topic, mqttMessage) => {
    // mqttMessage is Buffer
    global.results.receiveResult = mqttMessage.toString();
    client.end();
  });

Now, in your API you can use a settimeout to return an appropriate response based on the value of global.results:

  setTimeout(() => {
    console.log('printing results', global.results);
    if (global.results.publishResult !== 'Published Successfully') {
      return res
        .status(500)
        .send({ data: global.results, message: 'Publish Failed' });
    }
    if (!global.results.receiveResult) {
      return res
        .status(500)
        .send({ data: global.results, message: 'Published but Confirmation Not received' });
    }
    return res
      .status(200)
      .send({ data: global.results, message: 'Response from mqtt' });
  }, timeout);

Post a Comment for "Mqtt Async Wait For Messagse Then Respond To Http Post Request"