在没有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;
答案 0 :(得分: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;