Ahmed El-Hinidy
Published

Home Management System - Control your home from a website

Control your home from any place in the world using a website.

IntermediateFull instructions provided64,127
Home Management System - Control your home from a website

Things used in this project

Hardware components

1Sheeld
1Sheeld
×1
Arduino UNO
Arduino UNO
×1
Temperature sensor
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1

Software apps and online services

Heroku
Mongolab

Story

Read more

Schematics

Wiring

Code

Untitled file

Arduino
/*

Internet Shield Example

This example shows an application on 1Sheeld's internet shield.

By using this example, you can get response of certain GET request and 
print it all out on the terminal shield 64 bytes by 64 bytes.
 
OPTIONAL:
To reduce the library compiled size and limit its memory usage, you
can specify which shields you want to include in your sketch by
defining CUSTOM_SETTINGS and the shields respective INCLUDE_ define. 

*/

#define CUSTOM_SETTINGS
#define INCLUDE_INTERNET_SHIELD
#define INCLUDE_TERMINAL_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD
#define INCLUDE_TEXT_TO_SPEECH_SHIELD

/* Include 1Sheeld library. */
#include <OneSheeld.h>

/* Create an Http request with 1Sheeld website's url. */
/* It's important to be created here as a global object. */
HttpRequest GetControl("WebsitePath/api/GetControl");
HttpRequest SetSensors("WebsitePath/api/SetSensors/Temperature/");  
/* Set an LED on pin 13.*/
int LightsPin = 11;
int DoorLockPin = 12;
int WindowsPin = 13;
int DistanceSensorPin = A0;
int PIRSensorPin = 7;
bool Flag = true;
bool Flag2 = false;
bool Flag3=true;
struct ControlParameters
{
  char Lights;
  char DoorLock;
  char Windows;
};

ControlParameters CP;

void setup() 
{
  /* Start communication. */
  OneSheeld.begin();
  //oneSheeldRequest.addHeader("User-Agent","angular");
  /* LED pin mode is output. */
  pinMode(LightsPin,OUTPUT);
  pinMode(DoorLockPin,OUTPUT);
  pinMode(WindowsPin,OUTPUT);
  pinMode(DistanceSensorPin,INPUT);
  pinMode(PIRSensorPin,INPUT); 
  /* Subscribe to success callback for the request. */
  GetControl.setOnSuccess(&onSuccess);
  SetSensors.setOnSuccess(&onSuccess2);
  /* Subscribe to failure callback for the request. */
  GetControl.setOnFailure(&onFailure);
  /* Subscribe to start callback for the request. */
  GetControl.setOnStart(&onStart);
  /* Subscribe to finish callback for the request. */
  GetControl.setOnFinish(&onFinish);
  /* Sunbscribe to setOnNextResponseBytesUpdate to be notified once the bytes is updated in the response object. */
  GetControl.getResponse().setOnNextResponseBytesUpdate(&onBytesUpdate);
  /* Subscribe to response errors. */
  GetControl.getResponse().setOnError(&onError);
  GetControl.getResponse().setOnJsonResponse(&GetControlResponse);
  /* Perform a GET request using the Internet shield. */  
}

void loop()
{
  if(Flag==true)
  {
    Flag=false;
    Internet.performGet(GetControl);
  }
  else if(Flag2==true)
  {
    Flag2=false;
    String URL="WebsitePath/api/SetSensors/Temperature/"+ReadDistanceSensor();
    SetSensors.setUrl(URL.c_str());
    Internet.performGet(SetSensors);
  }
  else if(Flag3==true)
  {
    Flag3=false;
    String URL="WebsitePath/api/SetSensors/PIR/"+ReadPIRSensor();
    SetSensors.setUrl(URL.c_str());
    Internet.performGet(SetSensors);
  }
}

void onSuccess(HttpResponse &response)
{
  char *Temp=response.getBytes();
  Terminal.println(Temp);
  CP.Lights=Temp[0];
  CP.DoorLock=Temp[1];
  CP.Windows=Temp[2];
  Control(CP.Lights-'0',CP.DoorLock-'0',CP.Windows-'0');
  Terminal.println("-----------");
  Flag2=true;
}

void onSuccess2(HttpResponse &response)
{
  static int FlagNumber=2;
  if(FlagNumber==2)
  {
    FlagNumber=3;
    Flag3=true;
  }
  else
  {
    FlagNumber=2;
    Flag=true;
  }
}

void GetControlResponse(JsonKeyChain& chain,char value [])
{ 
}

void onFailure(HttpResponse &response)
{
  /* Print out the status code of failure.*/
  Terminal.println(response.getStatusCode());
  /* Print out the data failure.*/
  Terminal.println(response.getBytes());
}

void onStart()
{
  /* Turn on the LED when the request is started. */
  //digitalWrite(13,HIGH);
}

void onFinish()
{
  /* Turn off the LED when the request has finished. */
  //digitalWrite(13,LOW);
}

void onBytesUpdate(HttpResponse &response)
{
  
  /* Print out the data on the terminal. */
  //Terminal.println(response.getBytes());
  /* Check if the reponse is sent till the last byte. */
  //if(!response.isSentFully())
  //  {       
  //    /* Ask for the next 64 bytes. */
  //    response.getNextBytes();
  //  }
}

void onError(int errorNumber)
{
  /* Print out error Number.*/
  Terminal.print("Error:");
  switch(errorNumber)
  {
    case INDEX_OUT_OF_BOUNDS: Terminal.println("INDEX_OUT_OF_BOUNDS");break;
    case RESPONSE_CAN_NOT_BE_FOUND: Terminal.println("RESPONSE_CAN_NOT_BE_FOUND");break;
    case HEADER_CAN_NOT_BE_FOUND: Terminal.println("HEADER_CAN_NOT_BE_FOUND");break;
    case NO_ENOUGH_BYTES: Terminal.println("NO_ENOUGH_BYTES");break;
    case REQUEST_HAS_NO_RESPONSE: Terminal.println("REQUEST_HAS_NO_RESPONSE");break;
    case SIZE_OF_REQUEST_CAN_NOT_BE_ZERO: Terminal.println("SIZE_OF_REQUEST_CAN_NOT_BE_ZERO");break;
    case UNSUPPORTED_HTTP_ENTITY: Terminal.println("UNSUPPORTED_HTTP_ENTITY");break;
    case JSON_KEYCHAIN_IS_WRONG: Terminal.println("JSON_KEYCHAIN_IS_WRONG");break;
  }
}

void Control(int Lights, int DoorLock, int Windows)
{
  int Parameters[3]={Lights,DoorLock,Windows};
  for(int i=11;i<=13;i++)
  {
    if(Parameters[i-11])
    {
      digitalWrite(i,HIGH);
    }
    else
    {
      digitalWrite(i,LOW);
    }
  }
}

String ReadDistanceSensor()
{
  String StrS(6787 / (analogRead(DistanceSensorPin) - 3) - 4);  
  return StrS;
}

String ReadPIRSensor()
{
  if(digitalRead(PIRSensorPin)==HIGH)
  {
    return "1";
  }
  else
  {
    return "0";
  }
}

ControlService.js

JavaScript
put inside folder "js"
(function () {
    var $ControlService = function ($http) {
        var SetControl = function (Lights, DoorLock, Windows) {
            $http.get("<<Insert hosting/website domain or local host>>/api/SetControl/Lights/" + Lights);
            $http.get("<<Insert hosting/website domain or local host>>/api/SetControl/DoorLock/" + DoorLock);
            $http.get("<<Insert hosting/website domain or local host>>/api/SetControl/Windows/" + Windows);
        };
        var GetControl = function () {
            return $http.get("<<Insert hosting/website domain or local host>>/api/GetControl/").then(function (response) {
                return response.data;
            });
        };
        return {
            SetControl: SetControl,
            GetControl: GetControl
        };
    };
    //Get the Module
    var App = angular.module("HMS");
    //Register the Service
    App.factory('$ControlService', $ControlService);
} ());

index.js

JavaScript
var express = require('express');
var cors = require('cors');
var app = express();
var path = require('path');

app.use(express.static(__dirname + '/'));
app.use(cors());
var mongoose = require('mongoose');
mongoose.connect("<<insert Database link from the MongoLab website>>");

var HMSSchema = mongoose.Schema({ Lights: String, DoorLock: String, Windows: String, Temperature: String, PIR: String });
var HMS = mongoose.model('MyHome', HMSSchema);

  //Upload and run the file or run it on local server
  //for the first time with the next line uncommented
  //then comment it and reupload the file again
  
//var MyHome = new HMS({Lights:'0',DoorLock:'0',Windows:'0',Temperature:'27',PIR:'0'});

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  //Upload and run the file or run it on local server
  //for the first time with the next line uncommented
  //then comment it and reupload the file again
  //MyHome.save(function(err,MyHome){if(err)return console.error(err);});
});

app.set('port', (process.env.PORT || 5000));

//Get Control Value "Lights,DoorLock,Windows"
app.get('/api/GetControl', function(req, res) {
    var HMS1 = HMS.find(function(err,HMS1){
        var tmpHMS=HMS1[0];
        res.send(tmpHMS.Lights+tmpHMS.DoorLock+tmpHMS.Windows);
    });
});

//Set Lights
app.get('/api/SetControl/Lights/:Lights', function (req, res) {
    var HMS1 = HMS.find(function (err, HMS1) {
        var tmpHMS = HMS1[0];
        tmpHMS.Lights = req.params.Lights;
        tmpHMS.save(function (err, tmpHMS) { if (err) return console.error(err); });
        res.send({ "NewLIGHTS": tmpHMS.Lights });
    });
});

//Set DoorLock
app.get('/api/SetControl/DoorLock/:DoorLock', function (req, res) {
    var HMS1 = HMS.find(function (err, HMS1) {
        var tmpHMS = HMS1[0];
        tmpHMS.DoorLock = req.params.DoorLock;
        tmpHMS.save(function (err, tmpHMS) { if (err) return console.error(err); });
        res.send({ "NewDOORLOCK": tmpHMS.DoorLock });
    });
});

//Set Windows
app.get('/api/SetControl/Windows/:Windows', function (req, res) {
    var HMS1 = HMS.find(function (err, HMS1) {
        var tmpHMS = HMS1[0];
        tmpHMS.Windows = req.params.Windows;
        tmpHMS.save(function (err, tmpHMS) { if (err) return console.error(err); });
        res.send({ "NewWINDOWS": tmpHMS.Windows });
    });
});

//Get Sensors Reading "Temperature,PIR"
app.get('/api/GetSensors', function (req, res) {
    var HMS1 = HMS.find(function (err, HMS1) {
        var tmpHMS = HMS1[0];
        res.send({ "PIR": tmpHMS.PIR, "Temperature": tmpHMS.Temperature });
    });
});

//Set Temperature
app.get('/api/SetSensors/Temperature/:Temperature', function (req, res) {
    var HMS1 = HMS.find(function (err, HMS1) {
        var tmpHMS = HMS1[0];
        tmpHMS.Temperature = req.params.Temperature;
        tmpHMS.save(function (err, tmpHMS) { if (err) return console.error(err); });
        res.send({ "NewTMP": tmpHMS.Temperature });
    });
});

//Set PIR
app.get('/api/SetSensors/PIR/:PIRState', function (req, res) {
    var HMS1 = HMS.find(function (err, HMS1) {
        var tmpHMS = HMS1[0];
        tmpHMS.PIR = req.params.PIRState;
        tmpHMS.save(function (err, tmpHMS) { if (err) return console.error(err); });
        res.send({ "NewPIRState": tmpHMS.PIR });
    });
});

app.listen(app.get('port'), function () {
    console.log('Node app is running on port', app.get('port'));
});

index.html

HTML
<!doctype html>
<html ng-app ="HMS">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="js/plugins.js"></script>
  <script src="js/script.js"></script>
  <script src="js/GetSensorsService.js"></script>
  <script src="js/ControlService.js"></script>
</head>
<body ng-controller="HMSController">
  <div id="Controls">
      <form id="HMSControl">
          <h1>HMS Control Parameters</h1>
          <h3>Lights</h3>
          <select ng-model="Lights">
              <option value="1">ON</option>
              <option value="0">OFF</option>
          </select>
          <h3>DoorLock</h3>
          <select ng-model="DoorLock">
              <option value="1">Opened</option>
              <option value="0">Closed</option>
          </select>
          <h3>Windows</h3>
          <select ng-model="Windows">
              <option value="1">Opened</option>
              <option value="0">Closed</option>
          </select>
          <input type="button" value="Submit" ng-click="DO()">
      </form>
  </div>
  <div id="Sensors">
      <h1>HMS State</h1>
      <h2>Update in {{SecondsToUpdate}} seconds</h2>
      <h3>Distance: {{SensorsTemperature}} cm</h3>
      <h3>Is the room empty?: {{SensorsPIR}}</h3>
      <h3>Lights: {{ControlLights}}</h3>
      <h3>DoorLock: {{ControlDoorLock}}</h3>
      <h3>Windows: {{ControlWindows}}</h3>
  </div>
</body>
</html>

package.json

JSON
{
  "name": "Home Management System",
  "version": "0.1.4",
  "description": "Control your home from a website",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "engines": {
    "node": "0.12.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/heroku/node-js-getting-started"
  },
  "keywords": [
    "node",
    "heroku",
    "express"
  ],
  "license": "MIT"
}

app.json

JSON
{
  "name": "Home Management System",
  "description": "Control your home from a website!",
  "keywords": ["node", "express", "angular", "Arduino"]
}

script.js

JavaScript
put inside folder "js"
(function () {
    //1-Create Module
    var App = angular.module("HMS", []);
    //Create Controller
    var HMSController = function ($scope, $http, $interval, $GetSensorsService, $ControlService) {
        $scope.SensorsTemperature = "";
        $scope.SensorsTemperature = "";
        $scope.ControlLights = "";
        $scope.ControlDoorLock = "";
        $scope.ControlWindows = "";
        $scope.SecondsToUpdate = 5;
        var DecrementSecondsToUpdate = function () {
            $scope.SecondsToUpdate -= 1;
            if ($scope.SecondsToUpdate === 0) {
                $scope.SecondsToUpdate = 5;
                $scope.UPDATE();
            }
        };
        var StartUpdating = function () {
            $scope.UPDATE();
            $interval(DecrementSecondsToUpdate, 1000);
        }
        $scope.DO = function () {
            $ControlService.SetControl($scope.Lights, $scope.DoorLock, $scope.Windows);
        };
        $scope.UPDATE = function () {
            $GetSensorsService.GetSensorsReadings().then(function (SensorsReadings) {
                $scope.SensorsTemperature = SensorsReadings.Temperature;
                if (SensorsReadings.PIR == "0")
                    $scope.SensorsPIR = "Empty";
                else
                    $scope.SensorsPIR = "Not Empty";
            });
            $ControlService.GetControl().then(function (ControlParameters) {
                if (ControlParameters[0] == "0")
                    $scope.ControlLights = "OFF";
                else
                    $scope.ControlLights = "ON";
                if (ControlParameters[1] == "0")
                    $scope.ControlDoorLock = "Closed";
                else
                    $scope.ControlDoorLock = "Opened";
                if (ControlParameters[2] == "0")
                    $scope.ControlWindows = "Closed";
                else
                    $scope.ControlWindows = "Opened";
            })
        };
        StartUpdating();
    };
    //Register Controller
    App.controller("HMSController", HMSController);
} ());

plugins.js

JavaScript
put inside folder "js"
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};

// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());


// place any jQuery/helper plugins in here, instead of separate, slower script files.

GetSensorsService.js

JavaScript
put inside folder "js"
(function () {

    //Create the Service
    var $GetSensorsService = function ($http) {
        var GetSensorsReadings = function () {
            return $http.get("<<Insert hosting/website domain or local host>>/api/GetSensors/").then(function (response) {
                return response.data;
            });
        };
        return {
            GetSensorsReadings: GetSensorsReadings
        };
    };

    //Get the Module
    var App = angular.module("HMS");
    //Register the Service
    App.factory("$GetSensorsService", $GetSensorsService);
} ());

Arduino Sketch

Credits

Ahmed El-Hinidy

Ahmed El-Hinidy

2 projects • 31 followers
Computer Engineer. Embedded Systems and Web Development enthusiast !

Comments