繁体   English   中英

mqtt async 等待并发消息,然后响应相应的 http post 请求

[英]mqtt async wait for concurrent messages then respond to respective http post requests

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

  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 路由处理程序中。

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
            });       

        };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM