获取/发布回调中的NodeJS MQTT不起作用。

问题描述 投票:-1回答:1

在没有GET回调函数的情况下运行时,MQTT代码可以正常工作。最初我试过这个没有事件模块。一位专家告诉我用事件和事件发射器来尝试它。 MQTT Broker运行良好。正如您所看到的,GET回调中有一个res.send。该应用程序在网页中返回“成功”。尝试使用POST回调。我面临同样的问题。

var mqtt = require('mqtt');
var express = require('express');
var router = express.Router();
var events = require('events');

var eventEmitter = new events.EventEmitter();

var client  = mqtt.connect(MQTT_ADDR,{protocolId: 'MQIsdp', protocolVersion: 3, connectTimeout:1000, debug:true});

var MQTT_TOPIC          = "faultress/filter1/machine";
var MQTT_ADDR           = "mqtt://192.168.1.5:1883";
var MQTT_PORT           = 1883;

var myEventHandler = function ()
     {
            client.on('connect', function () {
              client.subscribe(MQTT_TOPIC);
              client.publish(MQTT_TOPIC, '1');
          });

          client.on('message', function (topic, message) {
              // message is Buffer
              console.log(message.toString());
              client.end();
          });

          client.on('error', function(){
              console.log("ERROR")
              client.end()
          });
        console.log("success");
    }
    eventEmitter.on('mqttcall', myEventHandler);

router.get('/', (req, res) => {

eventEmitter.emit('mqttcall');
res.send("success");

});


module.exports = router;
javascript node.js post get mqtt
1个回答
1
投票

问题仍然很模糊,但如果你只想在每次调用1时发布get('/'...),那么以下代码将起作用。

var mqtt = require('mqtt');
var express = require('express');
var router = express.Router();

var MQTT_TOPIC          = "faultress/filter1/machine";
var MQTT_ADDR           = "mqtt://192.168.1.5:1883";

var client  = mqtt.connect(MQTT_ADDR,{protocolId: 'MQIsdp',
      protocolVersion: 3, connectTimeout:1000, debug:true});

client.on('connect', function () {
  client.publish(MQTT_TOPIC, '1');
});


client.on('error', function(){
  console.log("ERROR");
});

router.get('/', (req, res) => {

  client.publish(MQTT_TOPIC,"1");
  res.send("success");

});


module.exports = router;
© www.soinside.com 2019 - 2024. All rights reserved.