NAzT
9/5/2017 - 6:14 AM

netpie_mqtt.js

netpie_mqtt.js

var mqtt = require('mqtt'), url = require('url');
// Parse 
var mqtt_url = url.parse('mqtt://gb.netpie.io:1883');
var url = "mqtt://" + mqtt_url.host;

var mqtt_username = 'ibJzvcJjWYf87eo'
var mqtt_password = 'msLGo5E+dfSwS7U4FaM/uStvqiM='
var mqtt_client_id = 'hBCFiCRlEUVS8bvd'
var app_id = 'CMMCIO'

var options = {
  port: mqtt_url.port,
  clientId: mqtt_client_id,
  username: mqtt_username,
  password: mqtt_password,
};

// Create a client connection
var client = mqtt.connect(url, options);

client.on('connect', function() { // When connected

  // subscribe to a topic
  client.subscribe('/'+app_id+'/gearname/#', 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('/'+app_id+'/gearname/hello', 'my message', function() {
    console.log("Message is published");
  });
});


// #src https://www.cloudmqtt.com/docs-nodejs.html