14

I am doing a project based on IOT. So I need to connect cloudmqtt and nodejs server.

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 **
    });
  });

});

Then started my server. But nothing is happening(No error message and no warning).Please help me on this?

hardillb
  • 54,545
  • 11
  • 67
  • 105
Muhsin Keloth
  • 7,855
  • 7
  • 39
  • 59

5 Answers5

12

Now the cloudmqtt and nodejs server is connected by giving extra parameters like clientId,keepalive,protocolVersion etc.

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
    });
});
Muhsin Keloth
  • 7,855
  • 7
  • 39
  • 59
  • 1
    this is not working now. Is there any problem with using this solution? I have tried but its always getting error - failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET – Tareq Aziz Mar 18 '18 at 01:44
  • @Muhsin I've came here through several google searches. May be you can give me some directions. I'm connecting to mqtt from my javascript client and set the username/password from javascript as your example. But you know it's so simple to inspect these credentials from browser. How do you prevent this? Or may be there are some different solutions to "securely" connect to mqtt from browser? – Joshgun Sep 06 '19 at 11:03
  • If anyone's still getting this issue with connecting to Cloudmqtt Websockets API with Connection reset error, change the host to `wss://soldier.cloudmqtt.com:38190/mqtt` changing the URL and port accordingly. – ManZzup Jun 01 '20 at 17:35
2

It's possible the connect goes wrong, try to add this and I think you will see something:

client.on('error', function(err) {
    console.log(err);
});
michelem
  • 14,430
  • 5
  • 50
  • 66
  • Thanks for your quick responce. I have added this line of code.But the same thing is happening again.Do you have any example? – Muhsin Keloth Apr 06 '16 at 07:05
1

I have implemented CLOUD MQTT and NodeJs interfacing.


    
    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();
        })
    })
    

0

Please check IP and port open on where you start/config your MQTT server. May these two block by antivirus firewall or server firewall And i didn't get your access port. Please check these server setting before you connect cloud 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)

Access url mqtt :http://127.0.0.1:8172/admin/

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

And please take look on IoT Core If you're building an application using Node.js there's Mosca (http://www.mosca.io)

If you're building an application using Python, you can check out hbmqtt (https://github.com/beerfactory/hbmqtt)

Developer end code share, maybe it will help:

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;
        }
    }
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
  • Thanks for your quick responce.Where i get this file? – Muhsin Keloth Apr 06 '16 at 07:11
  • 1
    please check your conf folder ..\apache-activemq-5.11.1\conf and also firewall setting open port or IP for Inbound and Outbound –  Apr 06 '16 at 07:16
  • Answers should not be all code block, reformat this so it's readable – hardillb Apr 06 '16 at 08:17
  • 1
    This not like, I'm providing the solution!! Where i'm trying help this boy as per my knowledge. Don't comment like this again. –  Apr 06 '16 at 08:34
0

Note that password is a buffer and you can pass any attribute on the option:

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

var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);
J.C. Gras
  • 4,934
  • 1
  • 37
  • 44