import RPi.GPIO as GPIO
import smbus
import time
GPIO.setmode(GPIO.BCM)
LED1=26
LED2=19
MOTIONin=21
GPIO.setup(LED1,GPIO.OUT)
GPIO.setup(LED2,GPIO.OUT)
GPIO.setup(MOTIONin, GPIO.IN)
arr=[0,0,0,0,0,0,0,0,0,0]
# Get I2C bus
bus = smbus.SMBus(1)

# TSL2561 address, 0x39(57)
# Select control register, 0x00(00) with command register, 0x80(128)
#		0x03(03)	Power ON mode
bus.write_byte_data(0x39, 0x00 | 0x80, 0x03)
# TSL2561 address, 0x39(57)
# Select timing register, 0x01(01) with command register, 0x80(128)
#		0x02(02)	Nominal integration time = 402ms
bus.write_byte_data(0x39, 0x01 | 0x80, 0x02)

time.sleep(0.5)
while True:
# Read data back from 0x0C(12) with command register, 0x80(128), 2 bytes
# ch0 LSB, ch0 MSB
    data = bus.read_i2c_block_data(0x39, 0x0C | 0x80, 2)

# Read data back from 0x0E(14) with command register, 0x80(128), 2 bytes
# ch1 LSB, ch1 MSB
    data1 = bus.read_i2c_block_data(0x39, 0x0E | 0x80, 2)

# Convert the data
    ch0 = data[1] * 256 + data[0]
    ch1 = data1[1] * 256 + data1[0]

# Output data to screen
    #print "Full Spectrum(IR + Visible) :%d lux" %ch0
    #print "Infrared Value :%d lux" %ch1
    print "Visible Value :%d lux" %(ch0 - ch1)
    print " "

    #motion
    i=GPIO.input(MOTIONin)
    for j in range(0,len(arr)-1):
        arr[j]=arr[j+1]
    arr[9]=i
    sum1=sum(arr)
    print arr
       
    #LED
    if sum1>=5:               #When output from motion sensor is HIGH
            if ch0-ch1<25:
                print "Motion detected. Street Lamps are switched ON"
                GPIO.output(LED1,1)
                GPIO.output(LED2,1)
                time.sleep(10)
            else:
                print"Motion detected. Natural light level is above threshold."
                GPIO.output(LED1,0)
                GPIO.output(LED2,0)
    elif sum1<6:                 #When output from motion sensor is LOW
        print "No motion detected. Street Lamps are switched OFF."
        if ch0-ch1>25:
            GPIO.output(LED1,0)
            GPIO.output(LED2,0)
    print " "
    print " "
    
    time.sleep(1)
