我目前在解决如何将MQTT message
事件捕获回用NodeJS编写的REST API主体方面遇到问题。我当前的设置是App
-> NodeJS REST API
-> MQTT broker inside RPi 3
。
这是我的MQTTHandler.js
类,在其中放置了所有可重复使用的MQTT函数
const mqtt = require('mqtt')
class MQTTHandler {
constructor (host) {
this.client = null
this.host = host
}
connect () {
this.client = mqtt.connect(this.host)
this.client.on('error',function (err) {
console.log(err)
this.client.end()
})
this.client.on('connect',function () {
console.log('MQTT client connected...')
})
// I need this to send message back to app.js
this.client.on('message',function (topic,message) {
if (!message.toString()) message = 'null'
console.log(JSON.parse(message.toString()))
})
this.client.on('close',function () {
console.log('MQTT client disconnected...')
})
}
subscribeTopic (topic) {
this.client.subscribe(topic)
}
unsubscribeTopic (topic) {
this.client.unsubscribe(topic)
}
sendMessage (topic,message) {
this.client.publish(topic,message)
}
}
module.exports = MQTTHandler
下面是我的app.js
const MQTTHandler = require('./mqtt.handler')
...
var mqttClient = new MQTTHandler('mqtt://127.0.0.1')
mqttClient.connect()
app.get('/hello',function (req,res) {
mqttClient.subscribeTopic('topic')
mqttClient.sendMessage('topic','hello world')
// I need to return the MQTT message event here
// res.json(<mqtt message here>)
res.end()
})
我已经尝试使用NodeJS的事件发射器,但是它似乎不起作用。任何帮助或建议,将不胜感激,谢谢!