【问题标题】:Connecting nodejs and cloud mqtt连接nodejs和云mqtt
【发布时间】:2016-07-26 09:36:18
【问题描述】:

我正在做一个基于物联网的项目。所以我需要连接cloudmqttnodejs服务器。

app.js

// Create a MQTT Client
var mqtt = require('mqtt');

// Create a client connection to CloudMQTT for live data
var client = mqtt.connect('xxxxxxxxxxx', {
  username: 'xxxxx',
  password: 'xxxxxxx' 
});

client.on('connect', function() { // When connected
    console.log("Connected to CloudMQTT");
  // Subscribe to the temperature
  client.subscribe('Motion', function() {
    // When a message arrives, do something with it
    client.on('message', function(topic, message, packet) {
      // ** Need to pass message out **
    });
  });

});

然后启动我的服务器。但是什么都没有发生(没有错误消息和警告)。请帮我解决这个问题?

【问题讨论】:

    标签: javascript node.js mqtt iot


    【解决方案1】:

    可能是连接出错了,尝试添加这个,我想你会看到一些东西:

    client.on('error', function(err) {
        console.log(err);
    });
    

    【讨论】:

    • 感谢您的快速回复。我已经添加了这行代码。但是同样的事情又发生了。你有什么例子吗?
    【解决方案2】:

    请检查在您启动/配置 MQTT 服务器的位置上打开的 IP 和端口。可能这两个被防病毒防火墙或服务器防火墙阻止而我没有得到你的访问端口。请在连接云 mqtt 前检查这些服务器设置。

    activemq.xml and jetty.xml
    
        name="openwire" uri="tcp://0.0.0.0:61616 (default)
        name="amqp" uri="amqp://0.0.0.0:5672 (default)
        name="stomp" uri="stomp://0.0.0.0:61613 (default)
        name="mqtt" uri="mqtt://0.0.0.0:1883 (default) (Android and Ios team)
        name="ws" uri="ws://0.0.0.0:61614 (default) (Php team)
    

    访问url mqtt:http://127.0.0.1:8172/admin/

        Un:admin (default)
        Ps:admin (default)
    

    请看一下 IoT Core 如果您正在使用 Node.js 构建应用程序,那么 Mosca (http://www.mosca.io)

    如果您使用 Python 构建应用程序,可以查看 hbmqtt (https://github.com/beerfactory/hbmqtt)

    开发者端代码分享,或许会有所帮助:

    if (!window.WebSocket) {
        $("#connect").html("\
    
                <p>\
                Your browser does not support WebSockets. This example will not work properly.<br>\
                Please use a Web Browser with WebSockets support (WebKit or Google Chrome).\
                </p>\
            ");
    } else {
        function subscribeClient() {
            var currentDate = new Date();
            var mqtt_clientId = CURRENT_USER_ID + "-" + currentDate.getTime();     
            var mqtt_host = '00.000.00.000';
            var mqtt_port = '00000';
            var mqtt_user = 'xxxxx';
            var mqtt_password = 'xxxxx';
            $("#connect_clientId").val("example-" + (Math.floor(Math.random() * 100000)));
            var timeout = 3000 / 2;
            var keepAliveInterval = 3000;
            var maxMqqtConnectCount = 80;
            client = new Messaging.Client(mqtt_host, Number(mqtt_port), mqtt_clientId);
            client.onConnect = onConnect;
            client.onMessageArrived = onMessageArrived;
            client.onConnectionLost = onConnectionLost;
            // the client is notified when it is connected to the server.
            var onConnect = function (frame) {
                console.log('mqqt connected.');
                $("#chat_conn").val(1);
                $(".offline-alert").css("display", "none");
                // connecting client
                client.subscribe(topicId);
                //subscribing to multiple groups
                var groups = JSON.parse($("#current_user_groups").val());
                $(groups).each(function (index, element) {
                    var group_id = element["GroupID"];
                    var group_topic_id = getGroupTopicId(group_id);
                    client.subscribe(group_topic_id);
                });
    
            };
    
            function disconnectClient() {
                client.disconnect();
                $(".offline-alert").css("display", "block");
                $("#chat_conn").val(0);
            }
    
            function onFailure(failure) {
                console.log('mqqt connectinn failed');
                $("#chat_conn").val(0);
                $(".offline-alert").css("display", "block");
                connectMqtt();
            }
    
            function onConnectionLost(responseObject) {
                console.log('mqqt connectinn lost');
                $("#chat_conn").val(0);
                $(".offline-alert").css("display", "block");
                connectMqtt();
            }
    
            function onMessageArrived(message) {
                if (!message) {
                    return false;
                }
                console.log(message.payloadString);
    
                }
    
    
            function connectMqtt()
            {
                var currentConnectionCount = getMqqtConnectionLostCount();
                if (currentConnectionCount <= maxMqqtConnectCount)
                {
                    setMqqtConnectionLostCount();
                    console.log('connecting mqqt ' + getMqqtConnectionLostCount() + ' times.');
                    client.connect({
                        timeout: timeout, //seconds
                        keepAliveInterval: keepAliveInterval,
                        userName: mqtt_user,
                        useSSL: false, // for secure connection on https #added by Virendra Yadav ver1.1 on 2015-02-03 to set MQTT SSL use setting
                        password: mqtt_password,
                        onSuccess: onConnect,
                        onFailure: onFailure,
                    });
                } else
                {
    
                    console.log('mqqt unable to connect more than ' + maxMqqtConnectCount + ' times.');
                    window.location.reload();
                }
            }
            connectMqtt();
    
            function setMqqtConnectionLostCount()
            {
                var currentConnectionLostCount = getMqqtConnectionLostCount();
                currentConnectionLostCount = parseInt(currentConnectionLostCount);
                currentConnectionLostCount = currentConnectionLostCount + 1;
                $('#mqqtReconnectConnectionCount').val(currentConnectionLostCount);
            }
            function getMqqtConnectionLostCount()
            {
                var countVal = $('#mqqtReconnectConnectionCount').val();
                return countVal;
            }
        }
    

    【讨论】:

    • 感谢您的快速回复。我从哪里得到这个文件?
    • 请检查您的 conf 文件夹 ..\apache-activemq-5.11.1\conf 以及防火墙为入站和出站设置开放端口或 IP
    • 答案不应该都是代码块,重新格式化它以便可读
    • 这不像,我提供解决方案!!据我所知,我正在尝试帮助这个男孩。不要再这样评论了。
    【解决方案3】:

    我已经实现了 CLOUD MQTT 和 NodeJs 接口。

    var mqtt = require('mqtt'),url = require('url') var client = mqtt.createClient(PORTNO,"m10.cloudmqtt.com", { username: "xxxxxxxxx", password: "xxxxxxxxx" }); client.on('connect',function() { client.publish("Hello",function() { client.end(); }) })

    【讨论】:

      【解决方案4】:

      现在 cloudmqttnodejs 服务器通过提供额外的参数(如 clientId、keepalive、protocolVersion 等)连接。

      app.js

      var mqtt = require('mqtt');
      var options = {
          port: 15255,
          host: 'mqtt://m11.cloudmqtt.com',
          clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
          username: 'xxxxxxxxxxxxxxxxxx',
          password: 'xxxxxxxxxxxxxxxxxx',
          keepalive: 60,
          reconnectPeriod: 1000,
          protocolId: 'MQIsdp',
          protocolVersion: 3,
          clean: true,
          encoding: 'utf8'
      };
      var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);
      client.on('connect', function() { // When connected
          console.log('connected');
          // subscribe to a topic
          client.subscribe('topic1/#', 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('topic1/#', 'my message', function() {
              console.log("Message is published");
              client.end(); // Close the connection when published
          });
      });
      

      【讨论】:

      • 这现在不起作用。使用这个解决方案有什么问题吗?我已经尝试过,但它总是出错 - 失败:WebSocket 握手期间出错:net::ERR_CONNECTION_RESET
      • @Muhsin 我是通过几次谷歌搜索来到这里的。也许你能给我一些方向。我正在从我的 javascript 客户端连接到 mqtt,并将 javascript 中的用户名/密码设置为您的示例。但是您知道从浏览器检查这些凭据非常简单。你如何防止这种情况发生?或者可能有一些不同的解决方案可以从浏览器“安全”连接到 mqtt?
      • 如果有人在连接到 Cloudmqtt Websockets API 时仍然遇到连接重置错误的问题,请将主机更改为 wss://soldier.cloudmqtt.com:38190/mqtt,相应地更改 URL 和端口。
      【解决方案5】:

      请注意,密码是一个缓冲区,您可以在选项上传递任何属性:

      var options = { username: 'strUserName',
                      password: new Buffer('strPassword')};
      
      var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 2021-11-18
        相关资源
        最近更新 更多