Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting nodejs and cloud mqtt

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?

like image 678
Muhsin Keloth Avatar asked Apr 06 '16 06:04

Muhsin Keloth


People also ask

Is MQTT cloud based?

AWS IoT MQTT client allows subscribing to given topics to see necessary messages. Cloud MQTT. This cloud solution provides a hosted message broker for the Internet of Things.

How do I connect to HiveMQ broker?

Connect MQTT Clients to HiveMQ Open a terminal window and go to the tools directory of your HiveMQ 4.4 or higher installation. In the tools directory, go to the mqtt-cli/bin folder and enter mqtt sh to start the MQTT CLI in shell mode. The MQTT CLI starts and lists useful options and commands.


1 Answers

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
    });
});
like image 109
Muhsin Keloth Avatar answered Oct 02 '22 23:10

Muhsin Keloth