Skip to content
This repository has been archived by the owner on Feb 11, 2020. It is now read-only.

Mosca basic usage

SudoPlz edited this page May 5, 2014 · 25 revisions

Mosca can be used into any Node.js app. As mentioned above you can use any broker that ascoltatore offers.

###Ok first things first.. Lets configure the server:

var mosca = require('mosca')

var pubsubsettings = {
  //using ascoltatore
  type: 'mongo',		
  url: 'mongodb://localhost:27017/mqtt',
  pubsubCollection: 'ascoltatori',
  mongo: {}
};

var settings = {
  port: 1883,			//mosca (mqtt) port
  backend: pubsubsettings
};

var server = new mosca.Server(settings);
server.on('ready', setup);

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')
}

Sending data from mosca to clients:

The publish() function allows to programatically publish a value to MQTT clients with full support of all distinctive MQTT features: offline, quality of server, and retained messages.

var message = {
  topic: '/hello/world',
  payload: 'abcde', // or a Buffer
  qos: 0, // 0, 1, or 2
  retain: false // or true
};

server.publish(message, function() {
  console.log('done!');
});

Receiving data from clients:

The on() function allows to programatically listen for messages received from the client side.

// fired when a message is published
server.on('published', function(packet, client) {
console.log('Published', packet);
console.log('Client', client);
});
// fired when a client connects
server.on('clientConnected', function(client) {
console.log('Client Connected:', client.id);
});

// fired when a client disconnects
server.on('clientDisconnected', function(client) {
console.log('Client Disconnected:', client.id);
});

###A few known events to listen for:

  • published : When a message arrives
  • clientConnected: When a mqtt client connects
  • clientDisconnected: When a mqtt client disconnects