CJA3D
Published © CC BY-SA

IoT Command Center - Using Samsung ARTIK Cloud

IoT Command center allows you to monitor your home using the ARTIK cloud and automate your Hue light.

IntermediateWork in progress10 hours4,832
IoT Command Center - Using Samsung ARTIK Cloud

Things used in this project

Hardware components

Arduino Yun
Arduino Yun
×1
Grove starter kit plus for Intel Edison
Seeed Studio Grove starter kit plus for Intel Edison
×1
Philips hue
Philips hue
×1
Raspberry Pi 1 Model A+
Raspberry Pi 1 Model A+
×1
Servos (Tower Pro MG996R)
×1
Seeed Studio Grove - Air Quality Sensor
×1
Pebble Watch
Pebble Watch
×1

Software apps and online services

ARTIK Cloud for IoT
Samsung ARTIK Cloud for IoT

Hand tools and fabrication machines

3D Printer (generic)
3D Printer (generic)
Soldering iron (generic)
Soldering iron (generic)
Hot glue gun (generic)
Hot glue gun (generic)

Story

Read more

Custom parts and enclosures

IoT command center Bottom

Bottom part of the command center to House the Yun and the sensors

IoT command center Top

Top part of the command center that holds the Potentiometer and LCD

IoT Command Center Sensor Holder

Sensor Holder which will be screwed to the Top 3D printed part

Key Less Door Entry- Pi A+ Holder base

Key Less Door Entry - Pi A+ Lid

Key Less Door Entry - Servo Horn Holder

Key Less Door Entry - Door bolt Servo Holder

Schematics

IoT Command Center - with Arduino Yun

As part of the Circuit
- Air Quality sensor is connected to A0
- Potentiometer is connected to A1
- Light Sensor connected to A2
- Buzzer connected to D6
- RGB Backlight LCD connected to I2C
- Temperature and Humidity Sensor connected to I2C

Key Less Door Entry- with Raspberry Pi A+

-Connect the servo to GPIO pin number 18 on the Pi, which is a PWM pin
-To power up the servo I am using 4 AA batteries
-Also use a 1K ohms resistor to protect the GPIO pin from unexpected high current

Code

YunIoTCommandCenter

Arduino
//Create for the IoT command center project to post data to the ARTIK Cloud

#include "TH02_dev.h"
#include "Arduino.h"
#include"AirQuality.h"
#include "Wire.h" 
#include "rgb_lcd.h"
#include "Process.h"

rgb_lcd lcd;
const int colorR = 0;
const int colorG = 0;
const int colorB = 0;

const int lightPin = A2; 
const int gasPin = A0; 
const int potPin = A1; 
int potValue = 0;
AirQuality airqualitysensor;
int current_quality =-1; 
String airQualityCondition = "Not set";
//For testing only
int loops=2;//changes when sensor value is displayed.
int postArtik = 1; //set to 1 once you have determined your pot postoin
int homeon = 2;

void setup()
{  
  Bridge.begin();
  Serial.begin(9600);  
  pinMode(6, OUTPUT);
  airqualitysensor.init(14);
  delay(150);
  TH02.begin();
  delay(100);
  /* Determine TH02_dev is available or not */
  Serial.println("TH02_dev is available.\n");   
    // set up the LCD's number of columns and rows:
  lcd.begin(16, 2); 
  //lcd.setRGB(colorR, colorG, colorB); 
  // Print a message to the LCD.
  Serial.println("Sensors Intialized ....\n");
}
 

void loop()
{
  //Getting the value of the poentiometer, which will act as a dial to display the sensor values 
   potValue = analogRead(potPin);
   Serial.println("Potentiometer Value: ");   
   Serial.print(potValue);
   Serial.println("C\r\n");

   //Getting Temperature and Humidity value
    
   float temp = TH02.ReadTemperature(); 
   Serial.println("Temperature: ");   
   Serial.print(temp);
   Serial.println("C\r\n");
   
   float humidity = TH02.ReadHumidity();
   Serial.println("Humidity: ");
   Serial.print(humidity);
   Serial.println("%\r\n");
     

  //Getting value of the light sensor
  int lightValue= analogRead(lightPin);
  Serial.print(" Light Value :"); 
  Serial.print(lightValue);
  Serial.println("\r\n");
  
 
  //Getting the Air Quality sensor value
    current_quality=airqualitysensor.slope();
    Serial.println("current quality");
    Serial.println(current_quality);
    if (current_quality >= 0)// if a valid data returned.
    {
        if (current_quality==0)
           airQualityCondition = "Extreme pollution";
        else if (current_quality==1)
            airQualityCondition = "High pollution";       
        else if (current_quality==2)
            airQualityCondition = "Low pollution";
        else if (current_quality ==3)
           airQualityCondition = "Fresh air";
           
        Serial.println(airQualityCondition);
    }
   delay(200);

  //Posting values to the LCD screen based on the Pot Values
  if(potValue <200)
  {
     homeon =1;
     lcd.setCursor(0, 0);
     lcd.print("Turn ON Home");
     lcd.setCursor(0, 1);
     lcd.print("....................."); //"Humidity "+String(humidity)+"%"
     if(loops == 1){
      
      digitalWrite(6, HIGH);
      delay(analogRead(A4));
      digitalWrite(6, LOW);
      delay(analogRead(A4));
      delay(500);
      
      loops =2;
         if(postArtik==1){
            Process p;
             lcd.setCursor(0, 0);
             lcd.print("ARTIK Cloud !");
             lcd.setCursor(0, 1);
            // print the number of seconds since reset:
             lcd.print("Posting data........");
            Serial.println("Before calling the shell command");
            String cmd = "python /root/tutorial/app-send-message.py "+ String(int(temp))+String(" ")+String(int(humidity)) +String(" ")+ String(lightValue) +String(" ")+String(current_quality)+String(" ")+String(homeon);
            p.runShellCommand(cmd);
             // do nothing until the process finishes, so you get the whole output:
            while (p.running());
            
            Serial.println("After calling python program run to post to Artik Cloud");
            loops=2; //used for testing
             lcd.setCursor(0, 0);
             lcd.print("ARTIK Cloud !");
             lcd.setCursor(0, 1);
            // print the number of seconds since reset:
             lcd.print("Done .......");
          }
      digitalWrite(6, HIGH);
      delay(analogRead(A4));
      digitalWrite(6, LOW);
      delay(analogRead(A4));
      delay(500);
     }
  }
  else if(potValue >200 && potValue<400){
     loops=1;
     lcd.setCursor(0, 0);
     lcd.print("Temp "+String(temp)+"C");
     lcd.setCursor(0, 1);
     lcd.print("Humidity "+String(humidity)+"%"); //"Humidity "+String(humidity)+"%"
  }else if(potValue >400 && potValue<600){
     loops=1;
     lcd.setCursor(0, 0);
     lcd.print("Air Quality :");
     lcd.setCursor(0, 1);
     lcd.print(airQualityCondition);  //  airQualityCondition  
  }else if (potValue >600 && potValue<800){
     loops=1;
     lcd.setCursor(0, 0);
     lcd.print("Light Value:");
     lcd.setCursor(0, 1);
     lcd.print(lightValue);     //lightValue
  }else if (potValue >800){
    //Posting data to Artik Cloud by calling a python program value, and passing the sensor values as arguments
    //Currently setup to when the
     homeon =0;
     lcd.setCursor(0, 0);
     lcd.print("Turn OFF Home");
     lcd.setCursor(0, 1);
     lcd.print("...."); //"Humidity "+String(humidity)+"%"

      if(loops ==1)
      {
      //sounding the buzzer
      digitalWrite(6, HIGH);
      delay(analogRead(A1));
      digitalWrite(6, LOW);
      delay(analogRead(A1));
      delay(500);
          if(postArtik==1){
            Process p;
             lcd.setCursor(0, 0);
             lcd.print("ARTIK Cloud !");
             lcd.setCursor(0, 1);
            // print the number of seconds since reset:
             lcd.print("Posting data..");
            Serial.println("Before calling the shell command");
            String cmd = "python /root/tutorial/app-send-message.py "+ String(int(temp))+String(" ")+String(int(humidity)) +String(" ")+ String(lightValue) +String(" ")+String(current_quality)+String(" ")+String(homeon);
            p.runShellCommand(cmd);
             // do nothing until the process finishes, so you get the whole output:
            while (p.running());
            
            Serial.println("After calling python program run to post to Artik Cloud");
            loops=2; //used for testing
             lcd.setCursor(0, 0);
             lcd.print("ARTIK Cloud !");
             lcd.setCursor(0, 1);
            // print the number of seconds since reset:
             lcd.print("Done ...");
          }
       loops =2;
      //sounding the buzzer
      digitalWrite(6, HIGH);
      delay(analogRead(A1));
      digitalWrite(6, LOW);
      delay(analogRead(A1));
      delay(500);
    } 
  }
delay(1000);

}


ISR(TIMER1_OVF_vect)
{
  if(airqualitysensor.counter==61)//set 2 seconds as a detected duty
  {

      airqualitysensor.last_vol=airqualitysensor.first_vol;
      airqualitysensor.first_vol=analogRead(A0);
      airqualitysensor.counter=0;
      airqualitysensor.timer_index=1;
      PORTB=PORTB^0x20;
  }
  else
  {
    airqualitysensor.counter++;
  }
}

app-send-message.py

Python
Python code called from the ino file for the IoT command Center
#Python code which is called ino file
#Code based on code at https://github.com/artikcloud/tutorial-python-sdksample by yujingwu 
#Please git clone the repo to the Yun, and modify the device_message section
import artikcloud
from artikcloud.rest import ApiException
import sys, getopt
import time, random, json
from pprint import pprint

# SDK reference for more details
# https://github.com/artikcloud/artikcloud-python
def main(argv):

	DEFAULT_CONFIG_PATH = 'config/config.json'

	with open(DEFAULT_CONFIG_PATH, 'r') as config_file:
		config = json.load(config_file)['sampleFireSensor']
	print(config)

	# Configure Oauth2 access_token for the client application.  Here we have used
	# the device token for the configuration
	artikcloud.configuration = artikcloud.Configuration();
	artikcloud.configuration.access_token = config['deviceToken']

	# We create an instance of the Message API class which provides
	# the send_message() and get_last_normalized_messages() api call
	# for our example
	api_instance = artikcloud.MessagesApi()

	# Device_message - data that is sent to your device
	device_message = {}

	# We send random values to the 'temp' field for this FireSensor.
	# Let's send a random value between 0 and 200 for this demo.
	device_message['temp'] = sys.argv[1] ;
	device_message['humidity'] = sys.argv[3] ;
    device_message['photoresistor'] = sys.argv[2] ;
	device_message['airquality'] = sys.argv[4] ;
	# Set the 'device id' - value from your config.json file
	device_sdid = config['deviceId']

	# set your custom timestamp
	ts = None

	# Construct a Message object for your request
	data = artikcloud.Message(device_message, device_sdid, ts)

	try:
	    # Debug Print oauth settings
	    pprint(artikcloud.configuration.auth_settings())

	    # Send Message
	    api_response = api_instance.send_message(data)
	    pprint(api_response)
	except ApiException as e:
	    print "Exception when calling MessagesApi->send_message: %s\n" % e


if __name__ == "__main__":
   main(sys.argv[1:])

index.html

HTML
part of the flask App for the Key Less door entry mechanism, create a folder call templates in the webapp folder and place this file in it.
<!DOCTYPE HTML>
<html>
  <head>
    <title>Pi Door Opener</title>
  </head>
  <body>
    <form method="POST" action="">
      Please enter the password <input type="text" name="name">
      <p>	
      <input type="submit" name="buttonPress" value="Open" style = "height:50px;width:150px; color:#a7cb00; font-weight:bold;font-size: 100%">
      <input type="submit" name="buttonPress" value="Close" style = "height:50px;width:150px; color:#f00; font-weight:bold;font-size: 100%">
      </p>
    </form>
 	<div class="container" style="min-height:100% width:80%">
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
	    {% for message in messages %}
		  <div class="alert alert-warning alert-dismissible" role="alert">
			{{message}}
		  </div>
		{% endfor %}
	  {% endif %}
	{% endwith %}
	
	{% block body %}{% endblock %}
	</div>
 </body>
</html>

config.json

JSON
Modify your deviceId and deviceToken details. Create a folder called config in the webapp folder and place the file in it.
{
	"keyLessDoorEntry": {
		"deviceId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		"deviceToken": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
	}
}

doorOpen.py

Python
File to be referenced in Crontab file , this python file need to place in the webapp folder created on the PI
import os
from flask import Flask, render_template, request, flash

app = Flask(__name__)
app.secret_key = 'ImpossibleToRemember'
password = 'artikpi'

@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    if request.method == 'POST': 
	buttonHit = request.form['buttonPress']
        #print "The button hit is :" + buttonHit
        if buttonHit == 'Open' and 'name' in request.form:
		name = request.form['name']
		print "The password entered is :" + name
		if name == password:
			os.system("sudo python servo.py open")
			flash('Door is Open,Dont forget to close it .. ')
		else:
			flash('The password you have entered is wrong')		
	if buttonHit == 'Close':
		print"Close the door"
		os.system("sudo python servo.py close")
		flash('Door Closed')
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80,debug=True)

servo.py

Python
File need to be create in the webapp folder on the Pi.Also remember to install the ARTIK cloud python library before running this file individually for testing..
import RPi.GPIO as GPIO
import time
import sys
import artikcloud
from artikcloud.rest import ApiException
import sys, getopt
import time, random, json
from pprint import pprint


argVal = sys.argv[1]
print argVal

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 50)
pwm.start(7.5)

DEFAULT_CONFIG_PATH = 'config/config.json'

with open(DEFAULT_CONFIG_PATH, 'r') as config_file:
	config = json.load(config_file)['sampleFireSensor']
print(config)

	# Configure Oauth2 access_token for the client application.  Here we have used
	# the device token for the configuration
artikcloud.configuration = artikcloud.Configuration();
artikcloud.configuration.access_token = config['deviceToken']


try:
	#Reading the servo state value from the file to check if is Open/Closed
	fRead = open('servoState.txt')
        stateVal = fRead.read()
        print 'State value in file:'+ stateVal
        fRead.close()
	api_instance = artikcloud.MessagesApi()
	device_message = {}
	device_sdid = config['deviceId']
	ts = None

        if argVal == 'open' and stateVal == 'close': #Open the door
		print 'opening the servo lock'
		pwm.ChangeDutyCycle(2.5)#7.5  # turn towards 90 degree #Open 
	        fWrite = open('servoState.txt','w')
        	fWrite.write('open')
        	fWrite.close()
		device_message['doorState'] = 1;
		data = artikcloud.Message(device_message, device_sdid, ts) 
		try: 
	    	# Debug Print oauth settings
	    		pprint(artikcloud.configuration.auth_settings())
	    	# Send Message
	    		api_response = api_instance.send_message(data)
	    		pprint(api_response)
		except ApiException as e:
	    		print "Exception when calling MessagesApi->send_message: %s\n" % e
		time.sleep(1)
        elif argVal == 'close' and  stateVal == 'open': #Close the door
		pwm.ChangeDutyCycle(7.5)#2.5  # turn towards 0 degree
		time.sleep(1) # sleep 1 second
		print 'closing the servo lock'
                #pwm.ChangeDutyCycle(12.5) # turn towards 180 degree
		fWrite = open('servoState.txt','w')
        	fWrite.write('close')
        	fWrite.close()
                device_message['doorState'] = 0;
                data = artikcloud.Message(device_message, device_sdid, ts)
                try:
                # Debug Print oauth settings
                        pprint(artikcloud.configuration.auth_settings())
                # Send Message
                        api_response = api_instance.send_message(data)
                        pprint(api_response)
                except ApiException as e:
                        print "Exception when calling MessagesApi->send_message: %s\n" % e

		time.sleep(1)
        else: 
		print 'do nothing'
 
#except KeyboardInterrupt:
	pwm.stop()
	GPIO.cleanup()

except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)

Credits

CJA3D

CJA3D

10 projects • 80 followers
Tinkerer and 3D Printing enthusiast.

Comments