[英]MQTT.js multiple subscription
我正在玩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数据库。
您没有说过要如何使用这两个值,但以下是最简单的开始方法。
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.