This repository has been archived by the owner on Feb 11, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 506
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')
}
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!');
});
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:
- clientConnected : when a client is connected; the client is passed as a parameter.
- clientDisconnecting : when a client is being disconnected; the client is passed as a parameter.
- clientDisconnected : when a client is disconnected; the client is passed as a parameter.
- published : when a new message is published; the packet and the client are passed as parameters.
- subscribed : when a client is subscribed to a topic; the topic and the client are passed as parameters.
- unsubscribed : when a client is unsubscribed to a topic; the topic and the client are passed as parameters.