MQTT.js订阅从代理接收多个相同的消息

时间:2017-09-07 23:37:57

标签: javascript node.js mqtt esp8266

我在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秒我就会在我的节点服务器(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输出同一消息的倍数的原因吗?

1 个答案:

答案 0 :(得分:0)

似乎在某些情况下,在连接事件处理程序内进行订阅可能会导致重复订阅。如mqtt.js release 2.9.0所述,here解决了这种性质的问题。 因此,升级到最新的mqtt.js版本(目前为2.13.1)可能会解决您的问题。

但是,请注意mqtt.js usage notes状态“从v2.0.0开始,如果clean:true则重新连接时会恢复订阅”。另见here。如果是这样,看起来你根本不需要在你的连接事件处理程序中订阅,这应该有希望防止重复订阅首先发生。

您应该可以测试上述假设,只需在连接node.js客户端时重新启动CloudMQTT代理。这会导致您开始看到重复的邮件吗?如果是这样,我相信补救措施确实只是简单地将您的订阅移到connect事件处理程序之外。