Project tutorial
Home Smart Home

Home Smart Home © GPL3+

Smart home system using MediaTek Linkit, Xbee, Arduino, Orange PI and Azure

  • 82,421 views
  • 11 comments
  • 215 respects

Components and supplies

Apps and online services

About this project

Introduction

Let's see what we need to set up a smart home system using MediaTek Linkit. Since there are lot of experts here to guide you on the hardware hookup to read the sensor data, I will concentrate on creating apis and setting up ultra low cost $15 local server to capture all your sensor data. Optionally, I log the data to azure.

Setup

The sensors transmit there data via radio signals using xbee or any low cost transceiver to the MediaTek LinkIt. The MediaTek linkIt receives all the raw sensor data, packages it into json object using adruinojson library and makes a POST request to the local server. The local server hosts then nodejs web application and receives all the sensor data as json objects.

The local server is being used as pre-processor and adds the utc time and signature. Any data validation, conversion and filtration can be processed here. The local server logs all the data to cloud service in our case azure storage services. Alternatively, MediaTek linkIt can directly post the json objects to azure storage services. I setup a local server just to prove that a $15 pc can be as powerful enough to handle our data. we can log our data into any no-sql db even in our local server completely elimination the need for external cloud storage. I leave all this upto you guys.

Demo

Data logging demo

Prerequisite

I assume that you know how to read sensor data using sensors and microcontroller like arduino or mediaTek. To limit the scope of this project I am going to assume that the sensor data are available to MediaTek Link It. You can use low cast radio transceiver or Xbee to transmit and receive the radio signals from sensors attached to microcontoller like MediaTek. Beginners can use the MediaTek linkIt groove starter kit to read the external environment data like temperature, humidity, light etc.

Json Json Json

Json has become the de facto standard for iot and its been widely adopted. Having said about the prerequisite, lets begin by modeling our sensor data. The main purpose is to capture as many data you can and pass it to the server. The server can do all heavey lifting works like analytics, data conversion, machine learning etc. 

The 'desired' json object will be the desired state of the sensor data. For example when we record the temperature, the desired value of 24 means we need to sync the value to the cloud with the value of 24. Our clients like web app or mobile app will be updated to this value.

When we want to turn on a light we say, the desired state as on. It means the light is turned on or will be turned on. All our client applications will use this state to reflect the changes to the user. I mean, the icon in our web app will be turned on or off.

This is not a international standard, I just came up with this. So, please feel free to use your own convenient format.

Temperature

{
 "deviceid" : "iot/myhome/livingroom/thermostat"
"desired" : { "temperature" : "24", "humidity": "80"},
 "timeutc": "2015-11-23T00:41:48.824Z",
 "singedBy" : "localserver"
}

Microphone

{
 "deviceid" : "iot/myhome/livingroom/mic"
"desired" : {"intensity" : "66"},
 "timeutc": "2015-11-23T00:41:48.824Z",
 "singedBy" : "localserver"
}

Distance

{
 "deviceid" : "iot/myhome/livingroom/obstacle"
"desired" : {"proximity" : "150"},
 "timeutc": "2015-01-01",
 "singedBy" : "localserver"
}

PIR

{
 "deviceid" : "iot/myhome/livingroom/pir"
"desired" : {"motion start" : "2500", "motion end" : "5345"},
 "timeutc": "2015-11-23T00:41:48.824Z",
 "singedBy" : "localserver"
}

GPS

{

"deviceid" : "iot/mydevice/location"

"desired" : {"lat" : "25.5", "long" : "32.2"},

"timeutc": "2015-11-23T00:41:48.824Z",

"singedBy" : "localserver"

}

Moisture

{

"deviceid" : "

/iot/myhome/garden/moisture"

"desired" : {"moisture": "20"},

"timeutc": "2015-11-23T00:41:48.824Z",

"singedBy" : "localserver"

}

Gas

{

"deviceid" : " /iot/myhome/kitchen/gas"

"desired" : {"leak": "No"},

"timeutc": "2015-11-23T00:41:48.824Z",

"singedBy" : "localserver"

}

Light

{

"deviceid" : " /iot/myhome/livingroom/light"

"desired" : {"intensity": "60"},

"timeutc": "2015-11-23T00:41:48.824Z",

"singedBy" : "localserver"

}

Or use this,

Living Room

{

"deviceid" : "/iot/myhome/livingroom"

"desired" : { "temperature" : "25", 

                     "humidity" : "80", 

                     "window": "open", 

                      "door": "closed", 

                     "light": "80", 

                      "noise":"low"}

}

Bed Room

{

"deviceid" : "/iot/myhome/bedroom"

"desired" : { "temperature" : "24", 

                    "humidity" : "70", 

                    "window": "closed", 

                    "door": "closed", 

                    "light": "80", 

                    "ac":"on"

                    "noise":"low"}

}

MediaTek - Receiver 

Please refer the ino file attached to the software section to log the data into local server. The sensor data are simulated, you can pass in the actual reading to respective json object

Local Server

Local server adds a overhead but will be verify helpful in many ways. We can make use of local server as a pre-processor for out iot data. Data can be filtered, time stamped and signed

A tiny PC and nodejs is an excellent choice for local server. We can choose any tiny pc like raspberry pi, odriod, banana pi, beagle bone etc. I have choosen orange pi ($15) for this project.

Setup

Raspberry pi 2 or Orange Pi with any flavour of linux os that supports nodejs 5. I have chosen orange pi with arch linux for arm7. Installed nodejs and npm. Download my iotapp from github and navigate to /your/local/path/iotapp and run npm install. The basic expressjs app starts to listen on your port 3000.

Browse to your-local-ip:3000 to check if the default expressjs view is rendered. I have created these apis to post the sensor data

/iot/myhome/livingroom/thermostat - Temperature api

/iot/myhome/livingroom/mic - Sound api

/iot/myhome/livingroom/pir - Presence sensor api

/iot/myhome/livingroom/distance - Distance sensor api

/iot/myhome/mydevice/location - gps tracker api

/iot/myhome/garden/moisture - soil moisture sensor api

/iot/myhome/kitchen/gas - gas leak sensor api

/iot/myhome/livingroom/light - light sensor api

/iot/myhome/livingroom - other api for living room

/iot/myhome/bedroom - other api for bed room


To setup local server. Clone the source code iotapp from my github. Modify the index.js to put your cloud ip address or domain name where aspnet5 application is hosted in azure

Remote Server

Publishing data to the cloud has become popular now a days. We can purchase subscription from iot data provide like amazon, azure,spark fun, pubnub, initial state and many other. I have choosen azure for this demo. Data analytics, data mining and machine learning algorithm can be developed to process our data.

Download the iotwebapp from my github. I created it using visual studio 2015 targeting asp.net5. These apis were setup to post the iot data. The api logs the iot in the azure storage tables

The deviceid parameter can be set to identify if the sensor location.

These api's have been setup, 

api/iot/myhome/thermostat - asp.net5 web api to log all the thermostat data 

api/iot/myhome/microphone- asp.net5 web api to log all the microphone data

api/iot/myhome/pir - asp.net5 web api to log all the pir data

api/iot/myhome/distance - asp.net5 web api to log all the distance sensor data

api/iot/myhome/device/location - asp.net5 web api to log the gps data

api/iot/myhome/moisture - asp.net5 web api to log the moisture sensor data

api/iot/myhome/gas - asp.net5 web api to log the gas sensor data

api/iot/myhome/light - asp.net5 web api to log all the light sensor data

api/iot/myhome/livingroom - asp.net5 web api to log all the living room attributes/ sensor data. we can use this one api to push all the sensor values.

api/iot/myhome/bedroom - same as above, i have created one to log the details for my bedroom 

To setup remote server. Clone the source code iotwebapp from my github. Create a azure storage table. Modify the IoTController.cs and put your azure storage table account name and key. Use this domain name or ip in the local server

Conclusion

There are lot of areas to be refactored in the code. Please feel free to modify and let me know if you get struck.

Code

MediaTekRxC/C++
Media Tek as receiver. Sketch to local data to local server
/*
  Web client

 This sketch connects to a website 
 using Wi-Fi functionality on MediaTek LinkIt platform.

 Change the macro WIFI_AP, WIFI_PASSWORD, WIFI_AUTH and SITE_URL accordingly.

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 modified 20 Aug 2014
 by MediaTek Inc.
 */

#include <LTask.h>
#include <LWiFi.h>
#include <LWiFiClient.h>
#include <ArduinoJson.h>

#define WIFI_AP "your ap"
#define WIFI_PASSWORD "your password"
#define WIFI_AUTH LWIFI_WPA  // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP.
#define SITE_URL "your ip" //your nodejs or azure ip address or domain name

LWiFiClient c;



void setup()
{

  LWiFi.begin();
  Serial.begin(115200);



  // keep retrying until connected to AP
  Serial.println("Connecting to AP");
  while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
  {
    delay(1000);
  }

  // keep retrying until connected to website
  Serial.println("Connecting to WebSite");
  while (0 == c.connect(SITE_URL, 3000))
  {
    Serial.println("Re-Connecting to WebSite");
    delay(1000);
  }

}

boolean disconnectedMsg = false;

void loop()
{
  // Make sure we are connected, and dump the response content to Serial
  while (!c)
  {
    Serial.println(" Server disconnected..");  
    // keep retrying until connected to website
    Serial.println("Connecting to WebSite");
    while (0 == c.connect(SITE_URL, 3000))
    {
      Serial.println("Re-Connecting to WebSite");
      delay(1000);    
    }
  }

  Serial.println(" Reading temperature..");
  updateTemperature();
  delay(3000);
  Serial.println("Detecting sound..");
  updateSound();
  delay(3000);
  Serial.println("Detecting person movement..");
  updatePIR();
  delay(3000);
  Serial.println("Detecting obstacle..");
  updateDistance();
  delay(3000);
  Serial.println("Updating device location..");
  updateGPSTracker();
  delay(3000);
  Serial.println("Calculating soil moisture..");
  updateMoisture();
  delay(3000);
  Serial.println("Detecting gas leakage..");
  updateGasLeak();
  delay(3000);
  Serial.println("Recording light intensity..");
  updateLightIntensity();
  delay(3000);
  updateLivingroomAttributes();
  delay(3000);
  updateBedroomAttributes();
  delay(3000);
}

void writeToConsole()
{
   // Make sure we are connected, and dump the response content to Serial
  while (c)
  {
    int v = c.read();
    if (v != -1)
    {
      Serial.print((char)v);
    }
  }

  Serial.println();
  Serial.println(" Server disconnected..");  
  // keep retrying until connected to website
  Serial.println("Connecting to WebSite");
  while (0 == c.connect(SITE_URL, 3000))
  {
      Serial.println("Re-Connecting to WebSite");
      delay(1000);    
   }
 }

void updatePIR()
{
  long unsigned int s;
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  JsonObject& desired = root.createNestedObject("desired");

  root["deviceid"] = "/iot/myhome/livingroom/pir";
  //assume default unit ms
  desired["motionstart"] = String(random(0,1000));
  desired["motionend"]= String(random(1000,10000));

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/livingroom/pir HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

   //logic to detect slow server response and post the request again without waiting for dead response
  s = millis();
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);
    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }
  }

 Serial.println("Calling write to console..");
 writeToConsole();
  }
void updateDistance()
{
  long unsigned int s;
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  JsonObject& desired = root.createNestedObject("desired");

  root["deviceid"] = "/iot/myhome/livingroom/distancesensor";
  //assume default unit cm
  desired["obstacle"]=String(random(50,450));

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/livingroom/distance HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);
    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }
  }

 Serial.println("Calling write to console..");
 writeToConsole();
  
  }

void updateGPSTracker()
{
  long unsigned int s;
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  JsonObject& desired = root.createNestedObject("desired");

  root["deviceid"] = "/iot/mydevice";
  desired["lat"] =String(random(20,25));
  desired["long"]=String(random(22,27));

  String len = String(root.measureLength());
  
  c.println("POST /iot/mydevice/location HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();
}
void updateMoisture()
{
  long unsigned int s;
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  JsonObject& desired = root.createNestedObject("desired");

   root["deviceid"] = "/iot/myhome/garden/moisture";
  //assume default unit
  desired["moisture"] = String(random(40,60));

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/garden/moisture HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();
  
}

void updateGasLeak()
{
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  
  JsonObject& desired = root.createNestedObject("desired");

  desired["leak"] = "no";
  root["deviceid"] = "/iot/myhome/kitchen/gas";
  
  long unsigned int s;

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/kitchen/gas HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();

  }

void updateLightIntensity()
{
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  

  JsonObject& desired = root.createNestedObject("desired");

  desired["intensity"] = "80";
  root["deviceid"] = "/iot/myhome/livingroom/light";
  
  long unsigned int s;

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/livingroom/light HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();

  }

void updateLivingroomAttributes()
{
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

   root["deviceid"] = "/iot/myhome/livingroom";
  

  JsonObject& desired = root.createNestedObject("desired");

  //Alternative api for loggin living room attributes all at once
  desired["window"] = "open";
  desired["door"] = "closed";
  desired["ac"] = "off";
  desired["temperature"] = String(random(24,28));
  desired["humidity"] = String(random(60,65));


  long unsigned int s;

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/livingroom HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();


  
  } 

void updateBedroomAttributes()
{
   DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  root["deviceid"] = "/iot/myhome/bedroom";

  JsonObject& desired = root.createNestedObject("desired");

 //Alternative api for loggin living room attributes all at once
  desired["window"] = "open";
  desired["door"] = "closed";
  desired["ac"] = "off";
  desired["temperature"] = String(random(22,23));
  desired["humidity"] = String(random(75,80));

  long unsigned int s;

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/bedroom HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();

  
  }  
void updateSound()
{
  long unsigned int s;
  long unsigned int e;
  
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  JsonObject& desired = root.createNestedObject("desired");
  desired["intensity"] = String(random(40,80));
  root["deviceid"] = "/iot/myhome/livingroom/mic";
  root["timeutc"] = "";
  root["signedby"]="";

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/livingroom/mic HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);
    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }
  }

 Serial.println("Calling write to console..");
 writeToConsole();
}
void updateTemperature()
{

  long unsigned int s;
  long unsigned int e;
  
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  JsonObject& desired = root.createNestedObject("desired");
  desired["temperature"] = String(random(20,40));
  desired["humidity"]= String(random(60,80));

  root["deviceid"] = "/iot/myhome/livingroom/thermostat";
  root["timeutc"] = "";
  root["signedby"]="";

  String len = String(root.measureLength());
  
  c.println("POST /iot/myhome/livingroom/thermostat HTTP/1.1");
  c.println("Host: " SITE_URL);
  c.println("Content-Type: application/json");
  c.println("Cache-Control: no-cache");
  c.print("Content-Length: ");
  c.println(len); 
  c.println("Connection: close");
  c.println();
  root.printTo(c);

  root.printTo(Serial);

  s = millis();
  
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);

    if((millis() - s > 3000))
    {
      Serial.println();
      Serial.println("Server not responding..");
      break;
    }

    
  }

  Serial.println("Calling write to console..");
  writeToConsole();
   
}
nodejs - local serverJavaScript
The index.js which has the routes to receive the data from Media Tek
var express = require('express');
var router = express.Router();
var buf = require('buffer');
var request = require("request");

//replace your-ip-or-domain-name with your actual ip address or domain name
//example iot.azurewebsites.com
//example yourdomainname.com
//example 47.12.67.16

// accept POST request on the homepage
router.post('/iot/myhome/livingroom/thermostat', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/livingroom/thermostat',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });




  res.send('Living room temperature recorded');
});

// accept POST request mic
router.post('/iot/myhome/livingroom/mic', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/livingroom/microphone',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Living room sound intensity recorded');
});

// accept POST request pir
router.post('/iot/myhome/livingroom/pir', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/livingroom/pir',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Living room pir movement recorded');
});

// accept POST request distance
router.post('/iot/myhome/livingroom/distance', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/livingroom/distance',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Living room obstacle recorded');
});

// accept POST request gps
router.post('/iot/mydevice/location', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/mydevice/location/gps',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('device location recorded');
});

// accept POST request moisture
router.post('/iot/myhome/garden/moisture', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/garden/moisture',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Garden moisture level recorded');
});

// accept POST request gas
router.post('/iot/myhome/kitchen/gas', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/kitchen/gas',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Gas leak information recorded');
});

// accept POST request light
router.post('/iot/myhome/livingroom/light', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/livingroom/light',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Light intensity recorded');
});

// accept POST request livingroom
router.post('/iot/myhome/livingroom', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/room/livingroom',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Livingroom attributes recorded');
});

// accept POST request bedroom
router.post('/iot/myhome/bedroom', function (req, res) {
  var state = req.body;
  state.timeutc = new Date();
  state.signedby = "orangepi";
  console.log(state);

  var options = { method: 'POST',
    url: 'http://your-ip-or-domain-name/api/iot/myhome/room/bedroom',
    headers:
     {
       'cache-control': 'no-cache',
       'content-type': 'application/json' },
    body:state,
    json: true };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
  });


  res.send('Bedroom attributes recorded');
});

// accept PUT request at /user
router.put('/user', function (req, res) {
  res.send('Got a PUT request at /user');
});

// accept DELETE request at /user
//router.delete('/user', function (req, res) {
//  res.send('Got a DELETE request at /user');
//});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
ThermoStatController.csC#
api to log temperature data to the cloud
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/livingroom/[Controller]")]
    public class ThermoStatController : IoTController
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Post([FromBody]IotTemperature iotTemperature)
        {

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotTemperature.PartitionKey = "thermostat";
            iotTemperature.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotTemperature);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Temperature data logged to azure cloud..");

        }
    }

    public class IotTemperature : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }

        
        public string state {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string temperature { get; set; }
            public string humidity { get; set; }

        }

    }


}
PIRController.csC#
api to log presence sensor data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/livingroom/[Controller]")]
    public class PIRController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotPIR iotPIR)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotPIR.PartitionKey = "pir";
            iotPIR.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotPIR);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("PIR data logged to azure cloud..");
        }
    }


    public class IotPIR : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string motionstart { get; set; }
            
            public string motionend { get; set; }

        }

    }
}
MoistureController.csC#
api to log soil moisture data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/garden/[Controller]")]
    public class MoistureController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotMoisture iotMoisture)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotMoisture.PartitionKey = "moisture";
            iotMoisture.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotMoisture);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Moisture data logged to azure cloud..");
        }
    }


    public class IotMoisture : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string moisture { get; set; }
        

        }

    }
}
LivingRoomController.csC#
api to log all living room sensor data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/room/[controller]")]
    public class LivingRoomController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotLivingRoom iotLivingRoom)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotLivingRoom.PartitionKey = "livingroom";
            iotLivingRoom.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotLivingRoom);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Living room attributes logged to azure cloud..");
        }
    }

    public class IotLivingRoom : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string window { get; set; }
            public string door { get; set; }
            public string ac { get; set; }
            public string temperature { get; set; }
            public string humidity { get; set; }


        }

    }
}
LightController.csC#
api to log light sensor data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/livingroom/[Controller]")]
    public class LightController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotLight iotLight)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotLight.PartitionKey = "light";
            iotLight.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotLight);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Light intensity logged to azure cloud..");
        }
    }


    public class IotLight : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string intensity { get; set; }
        

        }

    }
}
GPSController.csC#
api to log gps data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/mydevice/location/[Controller]")]
    public class GPSController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotGPS iotGPS)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotGPS.PartitionKey = "gps";
            iotGPS.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotGPS);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("GPS data logged to azure cloud..");
        }
    }


    public class IotGPS : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string lat { get; set; }
            [JsonProperty("long")]
            public string longitude { get; set; }

        }

    }
}
GasController.csC#
api to log gas leakage data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/kitchen/[Controller]")]
    public class GasController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotGas iotGas)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotGas.PartitionKey = "gas";
            iotGas.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotGas);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Gas leak information logged to azure cloud..");
        }
    }


    public class IotGas : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string leak { get; set; }
        

        }

    }
}
DistanceController.csC#
api to log ultrasonic distance sensor data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/livingroom/[Controller]")]
    public class DistanceController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotDistance iotDistance)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotDistance.PartitionKey = "distance";
            iotDistance.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotDistance);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Obstacle data logged to azure cloud..");
        }
    }


    public class IotDistance : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string obstacle { get; set; }

        }

    }
}
BedRoomController.csC#
api to log all bedroom sensor data to azure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace iotwebapp.Controllers
{
    [Route("api/iot/myhome/room/[controller]")]
    public class BedRoomController : IoTController
    {
        [HttpPost]
        public IActionResult Post([FromBody]IotBedRoom iotBedRoom)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("iot");

            iotBedRoom.PartitionKey = "bedroom";
            iotBedRoom.RowKey = Guid.NewGuid().ToString();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(iotBedRoom);
            // Execute the insert operation.
            table.Execute(insertOperation);

            return Ok("Bed room attributes logged to azure cloud..");
        }
    }

    public class IotBedRoom : TableEntity
    {
        public string deviceid { get; set; }
        public string timeutc { get; set; }
        public string signedby { get; set; }


        public string state
        {
            get
            {
                return JsonConvert.SerializeObject(this.desired);
            }

            set {; }
        }
        public Desired desired { get; set; }
        public class Desired
        {
            public string window { get; set; }
            public string door { get; set; }
            public string ac { get; set; }
            public string temperature { get; set; }
            public string humidity { get; set; }


        }

    }
}
Media Tek Smart home - Source code for data logging
source code for nodejsapp, aspnet5 and mediatek receiver ino

Schematics

Arduino RF Transmitter
Transmit radio signal from arduino
Rftransmitterschematic large
Xbee transmit without shield
Transmit radio signal via Xbee from arduino without shield
Xbeesender1
Arduino RF Transmitter
Transmit radio signals from arduino
Rftransmitterschematic large

Comments

Similar projects you might like

Home Automation Using Raspberry Pi 2 And Windows 10 IoT

Project tutorial by Anurag S. Vasanwala

  • 297,269 views
  • 98 comments
  • 706 respects

WARAN - Home Automation

Project tutorial by Arjun Ganesan

  • 30,089 views
  • 13 comments
  • 77 respects

Home Automation system using Raspberry Pi

Project tutorial by Christian Kratky

  • 127,562 views
  • 34 comments
  • 404 respects

Vertical Hydroponic Farm

Project in progress by Paul Langdon

  • 55,392 views
  • 21 comments
  • 290 respects

Smart Wardrobe

Project in progress by Tan See Youu

  • 18,852 views
  • 8 comments
  • 46 respects

Alexa Based Smart Home Monitoring

Project tutorial by Adithya TG

  • 16,639 views
  • 19 comments
  • 47 respects
Add projectSign up / Login