mqtt async wait for messagse then respond to http

2019-07-20 06:38发布

问题:

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 and then send these messages a response over HTTP

  var array = [];
  const client = mqtt.connect(MQTTServer)
  var count =0;
  client.on('message', (topic, message) => {

  array[count] = message 
  count ++ 

  }

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

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


    //wait for multiple mqtt message in  MQTT callback 


    //after all messages received or timeout  return  here
     client.unsubscribe('inTopic')
    count = 0
    response.status(200).json(array);

  }

so have tried while() and seInterval() but haven't found any sollution

回答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.