import time
import picamera
import RPi.GPIO as GPIO

import smtplib
import mimetypes

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64

# inicializacion para lectura tecla salida
import os, sys
import tty
from select import select

class NotTTYException(Exception): pass

class TerminalFile:
    def __init__(self,infile):
        if not infile.isatty():
            raise NotTTYException()
        self.file=infile

        #prepare for getch
        self.save_attr=tty.tcgetattr(self.file)
        newattr=self.save_attr[:]
        newattr[3] &= ~tty.ECHO & ~tty.ICANON
        tty.tcsetattr(self.file, tty.TCSANOW, newattr)

    def __del__(self):
        #restoring stdin
        import tty  #required this import here
        tty.tcsetattr(self.file, tty.TCSADRAIN, self.save_attr)

    def getch(self):
        if select([self.file],[],[],0)[0]:
            c=self.file.read(1)
        else:
            c=''
        return c


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

sensor=17
contador=0

GPIO.setup(sensor,GPIO.IN,GPIO.PUD_DOWN)

# s es la var para guardar tecla
s=TerminalFile(sys.stdin)

# Establecemos conexion con el servidor smtp de gmail
mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login("sender mail","password mail account")

print "ALARMA ACTIVA, q to quit..."

while ( s.getch()!="q"):
	GPIO.wait_for_edge(sensor, GPIO.RISING)

	#Tomamos una foto
	with picamera.PiCamera() as camera:
		camera.start_preview()
		time.sleep(1)				 #aqui se puede probar para que quede bien
		camera.capture('myimage.jpg')
    		camera.stop_preview()


	# Construimos un mensaje Multipart, con un texto y una imagen adjunta
	mensaje = MIMEMultipart()	
	mensaje['From']="sender mail"
	mensaje['To']="receiver mail "
	mensaje['Subject']="Alarma detecta intruso"
	# Adjuntamos el texto
	mensaje.attach(MIMEText("""Imagen Capturada por Alarma"""))

	# Adjuntamos la imagen
	file = open("myimage.jpg", "rb")
	contenido = MIMEImage(file.read())
	contenido.add_header('Content-Disposition', 'attachment; filename = "myimage.jpg"')
	mensaje.attach(contenido)


	# Enviamos el correo, con los campos from y to.
	mailServer.sendmail("sender mail",
        	        "receiver mail",
               		 mensaje.as_string())

# Cierre de la conexion
mailServer.close()

GPIO.cleanup()

print "--ALARMA CERRADA --"
