#!/usr/bin/python

# this Python application turns a Raspberry Pi into a security camera system
# it requires that you have a Pi camera installed and an Apache web server running on your Pi

# Written by Mike Haldas
# Detailed documentation about this project here: http://www.cctvcamerapros.com/RPi-Camera-Alarm-MMS
# Email me at mike@cctvcamerapros.net if you have questions
# You can also reach me @haldas on twitter or +Mike Haldas on Google+
# If you make any improvements to this code or use it in a cool way, please let me know

import time
import picamera
import RPi.GPIO as GPIO
from twilio.rest import TwilioRestClient

# define the GPIO port you will use for the door sensor
SENSOR = 19

# number of seconds to delay between alarm and snapshot
# number of seconds to wait for the person to enter the room after triggering the sensor
DELAY = 0
#setup GPIO using Broadcom SOC channel numbering
GPIO.setmode(GPIO.BCM)

# set to pull-up (normally closed position for a door sensor)
GPIO.setup(SENSOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# put your Twilio credentials here
ACCOUNT_SID = "ADD_Twilio_AccountSID_HERE"
AUTH_TOKEN = "ADD_Twilio_AuthToken_HERE"

# make sure to use format with +1 for USA #s. E.G +12463338910
TO_PHONE = "ADD_PHONE_#_TO_SEND_TO_HERE"
FROM_PHONE = "ADD_TWillio_ASSIGNED_#_HERE"

# text message to send with photo
TXT_MSG = "Door Alarm Triggered!"

# host or IP address of Raspberry Pi: port number. E.G 50.184.192.93:80 or domain.com:9000
HOSTNAME = "mydomain.com:9000"

# we are using the default apache document root. Make sure to leave the trailing slash on the end!
APACHE_DOC_ROOT = "/var/www/"

# name and dimentsions of snapshot image
IMG = "snap.jpg"
IMG_WIDTH = 800
IMG_HEIGHT = 600

# initalize the Twilio client
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

try:
        # setup an indefinite loop that looks for the door sensor to be opened
        while True:

                GPIO.wait_for_edge(SENSOR, GPIO.RISING)
                print("Door Opened!\n")
                time.sleep(DELAY)
                with picamera.PiCamera() as camera:
                        camera.resolution = (IMG_WIDTH, IMG_HEIGHT)
                        camera.capture(APACHE_DOC_ROOT + IMG)

                client.messages.create(
                        to=TO_PHONE,
                        from_=FROM_PHONE,
                        body=TXT_MSG,
                        media_url="http://" + HOSTNAME + "/" + IMG,
                )
finally:
        GPIO.cleanup() # ensures a clean exit