首页 > 解决方案 > mqtt async 等待并发消息然后响应相应的 http post 请求

问题描述

我有这个家庭自动化项目的过程。

  1. 在我的服务器的 HTTP 请求中接收消息。
  2. 将上述步骤中的消息通过 MQTT 主题发布到设备。
  3. 等待 5 秒以通过 MQTT 主题接收设备的响应。
  4. 如果在 5 秒内收到响应,则发送成功响应,否则发送错误响应,到步骤 1 中的原始 HTTP 请求

下面是取自另一个问题的代码,因为它与我正在尝试做的事情完全匹配。

此代码一次只能处理一个请求。我应该怎么做来处理并发请求

var resp;
var timeOutValue = 5000; //wait 5 seconds
var timer;

const client = mqtt.connect(MQTTServer)

client.on('message', (topic, message) => {
     resp.send(message);
     client.unsubscribe('inTopic');
     resp = undefined;
     clearTimeout(timer)
}

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

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

  timer = setTimeout(function(){
    if (resp) {
        resp.send(message);
        resp = undefined;
        client.unsubscribe('inTopic');
    }
  }, timeOutValue);

}

我试过这个:

  1. 我将 HTTP 请求正文存储在数据库中,并在 MQTT 请求中向设备发送与存储记录相对应的唯一 ID。
  2. 这个唯一的 id 作为响应从设备发回。
  3. 当通过 MQTT 接收到任何消息时,我会检查数据库中是否存在唯一 ID,如果存在则检索记录并根据记录中存在的请求正文发送响应。
  4. 我等待 5 秒从设备获得响应,否则我会向 HTTP 发送错误响应。

但我不知道它是否适用于并发请求,因为我是 nodejs 的新手。所有这些都发生在 http post 路由处理程序中。

标签: javascriptnode.jshttpasync-awaitmqtt

解决方案


export async function scheduleMqtt() {
    var topic= 'office/csb_1';
    var topic1=topic;
    console.log("MQTT is started")
         var client = mqtt.connect(mqtturl, options);
         client.on('connect', mqtt_connect);
         function mqtt_connect() {
            console.log('client has connected successfully');
            client.subscribe(topic, 0, mqtt_subscribe);
            client.on('message', mqtt_messsageReceived);
            console.log(topic);
        };
        function mqtt_subscribe(err, granted) {
            console.log("Subscribed to " + topic);
            if (err) { console.log(err); }
            console.log("Granted:")
            console.log(granted)
    
            client.publish(topic);
            console.log("topic");
            client.on('message', function (topic, message) {
                console.log(message.toString()); //if toString is not given, the message comes as buffer
            });       

        };

推荐阅读