简体   繁体   中英

NodeJS MQTT in get/post callback not working.

The MQTT code works fine when run without the GET callback function. Initially i tried this without the events module. An expert told me to try it with events and event emitter. MQTT Broker is running perfectly. As you can see there is a res.send inside the GET callback. The app returns "Success" in the webpage. Tried the same with POST callback. I am facing the same issue.

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;

The question is still very vague, but if you just want to publish 1 every time the get('/'...) is called then the following code will work.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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