【发布时间】:2017-09-07 23:37:56
【问题描述】:
我在 CloudMQTT 上运行,我的 JS 代码是这样的:
var mqtt_url = URL.parse('mqtt://m10.cloudmqtt.com:15272' || 'mqtt://localhost:1883');
var auth = (mqtt_url.auth || ':').split(':');
var url = "mqtt://" + mqtt_url.host;
var options = {
port: mqtt_url.port,
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: USERNAME,
password: PASSWORD,
};
// Create a client connection
var client = mqtt.connect(url, options);
client.on('connect', function() { // When connected
// subscribe to a topic
client.subscribe('relay', function() {
// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
// console.log(packet);
console.log("Received '" + message + "' on '" + topic + "'");
});
});
// subscribe to a topic
client.subscribe('photoresistor', function() {
// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
console.log("Received '" + message + "' on '" + topic + "'");
});
});
// publish a message to a topic
client.publish('relay', value, function() {
console.log("Message of ", value, " is published");
// client.end(); // Close the connection when published
});
});
我将我的ESP8266 连接到一个光敏电阻,它每 5 秒将光敏电阻值发布到 photoresistor 主题一次。
好吧,我每隔 5 秒就会在我的 Node 服务器 (MeteorJS) 上获得四个相同的控制台日志。
I20170907-19:33:51.421(-4)? Received '156' on 'photoresistor'
I20170907-19:33:51.423(-4)? Received '156' on 'photoresistor'
I20170907-19:33:51.424(-4)? Received '156' on 'photoresistor'
I20170907-19:33:51.425(-4)? Received '156' on 'photoresistor'
I20170907-19:33:57.741(-4)? Received '39' on 'photoresistor'
I20170907-19:33:57.742(-4)? Received '39' on 'photoresistor'
I20170907-19:33:57.743(-4)? Received '39' on 'photoresistor'
I20170907-19:33:57.743(-4)? Received '39' on 'photoresistor'
I20170907-19:34:05.465(-4)? Received '37' on 'photoresistor'
I20170907-19:34:05.467(-4)? Received '37' on 'photoresistor'
I20170907-19:34:05.468(-4)? Received '37' on 'photoresistor'
I20170907-19:34:05.470(-4)? Received '37' on 'photoresistor'
I20170907-19:34:10.665(-4)? Received '161' on 'photoresistor'
I20170907-19:34:10.667(-4)? Received '161' on 'photoresistor'
I20170907-19:34:10.667(-4)? Received '161' on 'photoresistor'
I20170907-19:34:10.668(-4)? Received '161' on 'photoresistor'
知道什么可能导致client.subscribe 函数或 CloudMQTT 输出多个相同消息吗?
【问题讨论】:
-
您是否检查过其他客户端(例如 mosquitto_sub)是否有多个消息正在发布?
-
你有没有弄明白这个?我看到了完全相同的问题。有什么想法吗?
标签: javascript node.js mqtt esp8266