连接nodejs和云mqtt

Connecting nodejs and cloud mqtt

我正在做一个基于物联网的项目。所以我需要连接 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 **
    });
  });

});

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

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

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

请检查您 start/config 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)

访问urlmqtt: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;
        }
    }

我已经实现了 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();
        })
    })
    

现在 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
    });
});

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

var options = { username: 'strUserName',
                password: new Buffer('strPassword')};

var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);