В настоящее время у меня возникают проблемы с выяснением, как перехватить мое событие MQTT message
обратно в мое тело REST API, написанное на NodeJS. Моя текущая настройка 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, но, похоже, он не работает. Любая помощь или предложения будут высоко оценены, спасибо!