我正在研究 MQTT 和 MQTT.js。我运行了一个 MQTT 代理,现在我想订阅多个主题。一个主题没问题,但是多个。
我有这两个主题:
'sensor/esp8266-1/humidity'
'sensor/esp8266-1/temperature'
我用这段代码订阅了这两个主题
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://10.0.0.18');
client.subscribe('sensor/esp8266-1/humidity');
client.subscribe('sensor/esp8266-1/temperature');
client.on('message', function(topic, message, packet) {
console.log(packet)
});
使用此代码 console.log 返回以下内容
Packet {
cmd: 'publish',
retain: false,
qos: 0,
dup: false,
length: 35,
topic: 'sensor/esp8266-1/temperature',
payload: <Buffer 32 31 2e 32 30> }
Packet {
cmd: 'publish',
retain: false,
qos: 0,
dup: false,
length: 32,
topic: 'sensor/esp8266-1/humidity',
payload: <Buffer 34 31 2e 30 30> }
这看起来很好,但我如何从中获取温度/湿度数据?
我试过了
console.log(packet.payload.toString())
但现在我每次都得到温度和湿度,没有它们我就知道数字的含义了。
最后,我想让两个变量(温度/湿度)填充正确的数据。稍后我想连接这两个变量并将它们存储到 SQL 数据库中。
最佳答案
您还没有说您想如何使用这 2 个值,但以下是最简单的开始方式。
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://10.0.0.18');
var temperature;
var humidity;
client.subscribe('sensor/esp8266-1/humidity');
client.subscribe('sensor/esp8266-1/temperature');
client.on('message', function(topic, message, packet) {
if (topic === 'sensor/esp8266-1/temperature') {
temperature = message;
}
if (topic === 'sensor/esp8266-1/humidity') {
humidity = message;
}
});
您可以通过使用单个通配符订阅使其变得更简单:
client.subscribe('sensor/esp8266-1/+');
它将订阅所有以 sensor/esp8266-1/
开头的主题
编辑: 现在我们终于解决了你想问的问题(问题中不清楚)
client.on('message', function(topic, message, packet) {
if (topic === 'sensor/esp8266-1/temperature') {
temperature = message;
}
if (topic === 'sensor/esp8266-1/humidity') {
humidity = message;
}
if (temperature && humidity) {
//do database update or print
console.log("----");
console.log("temp: %s", temperature);
console.log("----");
console.log("humidity: %s", humidity);
//reset to undefined for next time
temperature = undefined;
humidity = undefined;
}
});
关于javascript - MQTT.js 多重订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185787/