Monday, September 14, 2015

Controlling lights using Raspberry Pi, and relays thru Bluemix IoTF.



With the Lord's festival (remover of obstacles ) coming up, I thought of how to use Bluemix's IoTF  for this occasion, so that I can demonstrate the ability of Bluemix , Raspberry Pi to control some standard lights controlled by a 240V power outlet.

My Objectives were
- Use Relays and control lighting of an idol of Lord Ganesha from Bluemix IoTF.
- Demonstrate how I can publish / subscribe commands from a device ( Raspberry Pi) to Bluemix IoTF, and likewise Pub/Sub from Bluemix to my app ( i.e my laptop )
i.e Showcase a command from the application ( i.e my laptop ) sending a "enable lights " to Bluemix IoTF,
- Simulate a temperature sensor sitting on my device and sending the data across to Bluemix IoTF and if temperature was above a certain threshold - turn the lights on, and turn off when temperature fell below threshold.
- Show how we can control the command to ON / OFF  from a web interface.
( at this point - I have not published my IP address to the general public,  so my web server runs local and one can access it by running http://127.0.0.1/get.html )


Here are some snapshots :












The code used was :
Client side on the device was a simple C Program - which subscribes to the IoTF and listens to any commands.

App side -i.e my laptop, was a Node.js which sends commands to turn on / off depending on instructions from Bluemix IoTF or the device.
In the below example, the application receives data from the IoTF and acts by sending some commands.

applicaton.on("deviceEvent", function (deviceType, deviceId, eventType, format, payload) {

    console.log("Device Event from :: "+deviceType+" : "+deviceId+" of event "+eventType+" with payload : "+payload);
    var json = JSON.parse(payload);
    console.log ("temperature is " +json.d.temp );

    if ( json.d.temp > 10) {
                console.log ("since temp is > 10, CRITICAL ");
                //payload = '{ "numOfTimes" : 1 }';
                //applicaton.publishDeviceCommand(deviceType, deviceId, "blink", "json",payload);

                payload ="critical";
                console.log ("sending payload " + payload );
                applicaton.publishDeviceCommand(deviceType, deviceId, "blink", "string",payload);

    } else {
                console.log ("since temp is < 10, SAFE");
                //payload = '{ "numOfTimes" : 0 }';
                //applicaton.publishDeviceCommand(deviceType, deviceId, "blink", "json",payload);

                payload = "safe"
                console.log ("sending payload " + payload );
                applicaton.publishDeviceCommand(deviceType, deviceId, "blink", "string",payload);


    }

No comments:

Post a Comment