Syed Sanoor
Published © GPL3+

Home Smart Home

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

IntermediateFull instructions provided111,766
Home Smart Home

Things used in this project

Story

Read more

Schematics

Arduino RF Transmitter

Transmit radio signal from arduino

Xbee transmit without shield

Transmit radio signal via Xbee from arduino without shield

Arduino RF Transmitter

Transmit radio signals from arduino

Code

MediaTekRx

C/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 server

JavaScript
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.cs

C#
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.cs

C#
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.cs

C#
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.cs

C#
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.cs

C#
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.cs

C#
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.cs

C#
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.cs

C#
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.cs

C#
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

Credits

Syed Sanoor

Syed Sanoor

3 projects • 98 followers
Developer

Comments