Hannan Satopay
Published © GPL3+

Smart Home using ARTIK Cloud

Control and monitor home appliances through ARTIK Cloud and mobile app using Intel Edison as the base connection for devices and sensors.

IntermediateFull instructions provided2 hours990
Smart Home using ARTIK Cloud

Things used in this project

Hardware components

Grove starter kit plus for Intel Edison
Seeed Studio Grove starter kit plus for Intel Edison
A relay is used to control the home appliances. LCD is used to display the readings. Light intensity sensor is used to measure the ambient light. A Temperature sensor is used to measure the room temperature. Other sensors can also be used to measure various parameters. A shield is also used for interconnection between the Intel Edison board and the sensors.
×1

Software apps and online services

ARTIK Cloud for IoT
Samsung ARTIK Cloud for IoT
Control and monitor your devices through ARTIK Cloud
Android Studio
Android Studio
To create the android application
Intel XDK IOT Edition

Story

Read more

Code

Smart Home code

JavaScript
The code is to be loaded into the Intel Edison to connect it to the Samsung Artrik Cloud and make it work like a Smart Home.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "<Device ID here>"; //Enter the device ID here
var device_token = "<Device token here>"; //Enter the device token here

var WebSocket = require('ws');
var isWebSocketReady = false;
var ws = null;
var mraa = require('mraa'); //Low Level Skeleton Library for IO Communication on GNU/Linux platforms
var lcd = require('./lcd'); // Required to interface with LCD

// Define variables for IO pins connected to board
var relay = new mraa.Gpio(7); //Define a relay connected to D7 pin on the Grove Shield
relay.dir(mraa.DIR_OUT); //Make the relay pin as output pin
var statusLED = new mraa.Gpio(3); //Define a LED connected to D3 pin on the Grove Shield
statusLED.dir(mraa.DIR_OUT); //Make the LED pin as output pin
var roomtemp = new mraa.Aio(0); // Measure the temperature with sensor connected to A0 pin on the Grove Shield
var intlight = new mraa.Aio(1); // Measure the light intensity with sensor connected to A1 pin on the Grove Shield
var relayState = 0; // The state of the relay
var display = new lcd.LCD(0);

/**
 * Gets the current time in millis
 */
function getTimeMillis(){
    return parseInt(Date.now().toString());
}

/**
 * Create a /websocket connection
 */
function start() {
    //Create the WebSocket connection
    isWebSocketReady = false;
    ws = new WebSocket(webSocketUrl);
    ws.on('open', function() {
        console.log("WebSocket connection is open ....");
        register(); //If the websocket connect is available the function is called to register on the Artik Cloud
    });
    ws.on('message', function(data) {
         handleRcvMsg(data); //The function is called and received data from the cloud is passed on to be processed
    });
    ws.on('close', function() {
        console.log("WebSocket connection is closed ....");
    });
}

/**
 * Sends a register message to /websocket endpoint
 */
function register(){
    console.log("Registering device on the WebSocket connection");
    try{
        var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}'; //The format to register the device on the Artik Cloud
        console.log('Sending register message ' + registerMessage + '\n');
        ws.send(registerMessage, {mask: true});
        isWebSocketReady = true;
    }
    catch (e) {
        console.error('Failed to register messages. Error in registering message: ' + e.toString());
       
    }    
}

//Handle the received message from the Artik Cloud
function handleRcvMsg(msg){
    var msgObj = JSON.parse(msg);
    if (msgObj.type != "action") return; //Early return;

    var actions = msgObj.data.actions; //From the data received get the received actions
    var actionName = actions[0].name; //assume that there is only one action in actions
    console.log("The received action is " + actionName);
    var newState;
    if (actionName.toLowerCase() == "seton") {
        newState = 1; //If the received action is to 'seton' then switch on the relay
    }
    else if (actionName.toLowerCase() == "setoff") {
        newState = 0; //If the received action is to 'setoff' then switch off the relay
    } else {
        console.log('Do nothing since receiving unrecognized action ' + actionName);
        return;
    }
    togglerelay(newState); //The function is called to toggle the relay based on the passed state
}

function togglerelay(value) {
     
        relayState = value;
        relay.write(value);
        console.log('togglerelay: wrote ' + value + ' to pin #' + relay);
        sendRelayStateToArtikCloud(); //Call the function to send the relay state data to Artik Cloud
    }

//Send relay state data to the Artik Cloud
function sendRelayStateToArtikCloud(){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
              "state": relayState /* Here the 'state' of the relay is set to the variable relayState. Note that the word 'state' should match exactly with the Artik Cloud Device manifest */
            };
        var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
        console.log('Sending payload ' + payload + '\n'); //Format to send data to the Artik Cloud
        ws.send(payload, {mask: true});
    } catch (e) {
        console.error('Error in sending a message: ' + e.toString() +'\n');
        
    }    
}

//After a delay read the value from the input pin and calculate the temperature
setInterval(function () {

        var a = roomtemp.read();
        var resistance = (1023 - a) * 10000 / a; 
        var celsius_temperature = 1 / (Math.log(resistance / 10000) / 3975 + 1 / 298.15) - 273.15;
        console.log("Celsius Temperature: " + celsius_temperature);
        sendRoomTempToArtikCloud(celsius_temperature); //Call the function and pass on the temperature value to be sent to the Artik Cloud
        display.setCursor(0, 0);
    
        display.write('Temperature:'+ celsius_temperature);
      }, 15000);

//Send the room temperature data to the Artik Cloud
function sendRoomTempToArtikCloud(temp){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
            "currentTemp": temp
        };
        var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
       
        ws.send(payload, {mask: true});
    } catch (e) {
        console.error('Error in sending a message: ' + e.toString());
    }   
   
}

//After a delay read the light intensity value from the input pin
setInterval(function () {

        var b = intlight.read();
        console.log("Light Intensity: " + b);
        sendLightIntensityToArtikCloud(b);
        display.setCursor(1, 0);
        if(b<100){
          display.write('Light Int:0'+b); //LCD had some problem displaying two figures correctly so this is the work around
        }
        else{
          display.write('Light Int:'+b);  
        }
        
      }, 15000);

//Send the light intensity data to the Artik Cloud
function sendLightIntensityToArtikCloud(lightint){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
            "currentlightint": lightint
        };
        var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
       
        ws.send(payload, {mask: true});
    } catch (e) {
        console.error('Error in sending a message: ' + e.toString());
        
    }   
}


/**
 * All start here
 */

start();

Smart Home Complete files

Smart Home Complete files to understand the working. Download/Clone from the following link, unzip it to view

Credits

Hannan Satopay

Hannan Satopay

3 projects • 7 followers
I am doing electronics engineering and I am interested in both hardware and software development.

Comments