Your own server

People are asking me about how to run their own server. I will try to give some examples on the server side software here. For this example I will use c9.io which is a great place to test your server side code. I usually first develop my code in c9.io if it ends with success I port it to a server on Digital Ocean. Lets try to develop a Nodejs app with MQTT messaging protocol and MandoDB to store our RFID key numbers and the time stamp indicating the moment your key has been read.

First register and login to c9.io. It is better to use your GitHub credentials if you have any. Create a new project and select nodejs.

c9 wifi rfid reader

and click "create workspace". Now you have a Linux environment nodejs installed. Now install mangodb with the command

sudo apt-get install -y mongodb-org

To run MongoDB, run the following shell commands below to pass the correct parameters to MangoDB. Mongodb data will be stored in the data folder.

mkdir data
echo 'mongod --bind_ip=$IP --dbpath=data --nojournal --rest "$@"' > mongod
chmod a+x mongod

in order to use the mangobd inside nodejs app, install this package with the command:

sudo npm install mongodb

Now lets install the MQTT libraries for our nodejs app.

npm install mqtt --save

Our MQTT broker will be again mqtt://test.mosquitto.org The protocol is non secure. Waiting from you suggestions on how to make the MQTT communication in a secure way.

So the next thing is the code

var mqtt = require('mqtt'); 
var mongodb = require('mongodb'); 
var mongodbClient = mongodb.MongoClient;  
var mongodbURI = 'mongodb://localhost:27017/Test_DB'; 
var deviceRoot = "demo/device/";
var collection,client; 

mongodbClient.connect(mongodbURI,setupCollection); 

function setupCollection(err, db) {
 if(err) throw err;
 collection=db.collection("test_mqtt"); 

 client  = mqtt.connect({ host:'test.mosquitto.org', port: 1883 })
 client.subscribe(deviceRoot); 
 client.on('message', insertEvent); 
}


function insertEvent(topic,message) {
  var key=topic;

  collection.update(
   { _id:key }, 
   { $push: { events: { event: {  value:message, when:new Date() } } } }, 
   { upsert:true },

   function(err,docs) {  
    if(err) {
     console.log("Insert fail")
   }
   }

  );

}

Copy and paste this code inside server.js file and save.

You can now start mongodb server by running the mongod command on your project root:

./mongod

Start a new Terminal by pressing the + sign and select start new Terminal. In this Terminal run our nodejs server on c9.io with the command:

node server.js

This will run the server and it will subscribe and wait for the key info. When it receive a MQTT message with a payload of the key and the time-stamp It will record the data into our mongodb collection.

I tried to keep this as simple as possible. Please share your ideas and any problem you faced during implementation.

Please support us by purchasing our open hardware products from http://www.makerstorage.com