How to setup a Mosca Node.js MQTT broker service on Ubuntu 14.04

May 4, 2015

This article will cover installing Mosca Node.js MQTT standalone broker service along side Redis on Ubuntu 14.04. MQTT is a light weight publish-subscription messaging protocol for use on top of the TCP/IP.

MQTT is designed for connections with remote locations where network bandwidth is limited. The Pub/Sub messaging pattern requires a message broker which is what is covered in this article. The broker distributes messages to clients subscribers based on the topic of a message.

Step 0
Time Matters!

sudo apt-get update
 
sudo ntpdate pool.ntp.org
 
sudo apt-get install ntp


Step 1
Install Redis

sudo apt-get install build-essential

sudo apt-get install tcl8.5

wget http://download.redis.io/releases/redis-3.0.0.tar.gz

gunzip -c redis-3.0.0.tar.gz | tar -xvf -

cd redis-3.0.0/

sudo make

sudo make install


Step 2
Start the Redis Server

cd utils/

sudo ./install_server.sh


Step 3
Install Mosca, and some helpful node packages

sudo apt-get update

sudo apt-get install nodejs

sudo ln -s /usr/bin/nodejs /usr/bin/node

sudo apt-get install npm

sudo npm install debug

sudo npm install mosca bunyan -g

sudo npm install daemon


Step 4
Create your Mosca Node.js MQTT Broker Service mosca-app.js

console.log(process.pid);
require('daemon')();
var mosca = require('mosca')

var backjack = {
  type: 'redis',
  db: 12,
  port: 6379,
  return_buffers: true,
  host: "localhost"
};

var moscaSettings = {
  port: 1883,
  backend: backjack,
  persistence: {
    factory: mosca.persistence.Redis
  }
};

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

server.on('clientConnected', function(client) {
    console.log('client connected', client.id);     
});

server.on('published', function(packet, client) {
  console.log('Published', packet.payload);
});

function setup() {
  console.log('Mosca server is up and running')
}
console.log(process.pid);


Step 5
Start the Mosca Node.js MQTT Broker Service

Step 6
Install MQTT Client For Testing

Step 7
Write a MQTT Publishing Client client-pub.js

var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://localhost');

client.on('connect', function () {
  client.publish('presence', 'Hello!', {retain: false, qa: 1});
client.end();
});


Step 8
Write a MQTT Subscription Client client-sub.js

var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://localhost');
 
client.on('connect', function () {
  client.subscribe('presence');

client.on('message', function (topic, message) {
  console.log(message.toString());
client.end();
  });
});


Step 9
Open a New Terminal and Execute your MQTT Subscription Client client-sub.js

Step 10
Open a New Terminal and Execute your MQTT Publish Client client-pub.js

Successful Output From client-sub.js terminal

I will write a followup article on scaling Mosca soon for production.

Comments are closed.