#-----------------------------------#
#	    Doorknob                #
#	     Alarm                  #
#           Project                 #
#-----------------------------------#

# Based on boblemarin's capacitive touch project --> https://bitbucket.org/boblemarin/raspberrypi-capacitive-sensor/src/

import time
import RPi.GPIO as GPIO
from SimpleCV import Camera
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

wc = Camera()

timeout = 10000
total = 0
DEBUG = 1
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

def CapRead(inPin, outPin):
	total = 0
	
	GPIO.setup(outPin, GPIO.OUT)
	GPIO.output(outPin, GPIO.LOW)

	GPIO.setup(inPin, GPIO.OUT)
	GPIO.output(inPin, GPIO.LOW)
	GPIO.setup(inPin, GPIO.IN)

	GPIO.output(outPin, GPIO.HIGH)
	
	while(GPIO.input(inPin) == GPIO.LOW and total < timeout):
		total+=1
	
	if (total > timeout):
		return -2

	GPIO.setup(inPin, GPIO.OUT)
	GPIO.output(inPin, GPIO.HIGH)
	GPIO.setup(inPin, GPIO.IN)
	
	GPIO.output(outPin, GPIO.LOW)

	while(GPIO.input(inPin)==GPIO.HIGH and total < timeout):
		total+=1

	if(total >= timeout):
		return -2
	else:
		return total

while True: 
	total = 0
	for j in range(0, 10):
		total+=CapRead(18, 17);
	
	if total > 60:
		img = wc.getImage()
		img.save("intruder.png")
		
		mail = smtplib.SMTP('smtp.gmail.com:587')
		mail.starttls()
		mail.login("youremail@gmail.com", "yourpassword")

		msg = MIMEMultipart()
		msg['Subject'] = 'ALERT!'
		msg.preamble = 'Dectected suspicious activity in your home'

		fp = open('intruder.png', 'rb')
		img = MIMEImage(fp.read())
		fp.close()
		msg.attach(img)
		
		mail.sendmail("youremail@gmail.com", "recipientemail@gmail.com", msg.as_string())
		mail.quit()
		sleep(10)

GPIO.cleanup()
