Thursday, August 27, 2015

Simple node js code to receive commands from a Device over mqtt. ( App side )

A traditional publish / subscribe model for an IOT would mean that the Device ( in this case let's say a RPI ) is publishing some sensor data ( say a temperature from a furnace )
and sending it to IoT platform.  This is called the "Client"

At the other side - there is an app" end - where we have a C program, or Java or Python application which is sitting and listening to the PublishEvents from the device(s).


Below is a App end code in node.js - which connects to IoTF ( Internet of Things Foundation )  and prints whatever it received from the devices.




A sample  node.js code to receive events data published from the device (e.g : Raspberry Pi )


References :
http://iotf.readthedocs.org/en/latest/libraries/python_cli_for_apps.html#handling-events-from-devices


Run this on your laptop  ( or on the app end )
( npm install iotf _ if this complains that Iotf libraries are not installed ) 
 
==
var Client = require("ibmiotf").IotfApplication;

//read the config from the application.cfg
var config = Client.parseConfigFile('./iotf.cfg');

var application = new Client(config);

var deviceType = "iotdevice";
var deviceId = "b827eb984666"

application.connect();

application.on("connect", function () {


        setInterval(function function_name (argument) {
                payload = '{ "numOfTimes" : 23 }';

                application.publishDeviceCommand(deviceType, deviceId, "blink", "json",payload);

        }, 2000);

});
 



==
This will connect to IoTF and print data being published from the device(s) which are at remote places.

A sample :

[user@oc0650888602 nodetest]$ node app.js
[2015-08-27 18:24:10.268] [INFO] [default] - Connected to IoTF successfully
Device Event from :: iotdevice : b827eb984666 of event status with payload : {"d" : {"temp" : 16 }}
Device Event from :: iotdevice : b827eb984666 of event status with payload : {"d" : {"temp" : 5 }}


==
A sample  iotf.cfg  that is used is as shown:
org = 8ubmht
id = b827eb984666
auth-method = apikey
auth-key = a-8ubmht-httz8bouy6
auth-token = NNZrVxhQpZa90Jc*5J    







1 comment:

  1. Thanks Admin, I just begin my career in sever side web application development for that I complete the Node JS training but I wish to explore more in that, truly your blog provide some useful information and I would like to share your blog in my friends circle so keep sharing.
    Regards,
    Node JS training in chennai

    ReplyDelete