from decimal import Decimal
import json
import urllib
import time
import threading
import serial
import datetime
import RPi.GPIO as GPIO
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

#button setup and call
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def gpio_callback(self):
        time.sleep(0.3)
        print('Entered gpio_callback')
        open_door()
        timer = threading.Timer(60.0, glow_red)
        timer.start()
        reset_red()
        
GPIO.add_event_detect(4, GPIO.FALLING, callback=gpio_callback, bouncetime=3000)

def open_door():
    print('entered open_door')
    #open latch
    ser=serial.Serial('/dev/ttyACM0',9600,timeout=1)
    ser.reset_input_buffer()
    ser.write(b"open\n")
    time.sleep(30)
    #close latch
    ser.write(b"close\n")
    send_email("Vedant PillBox - Medication Taken")
        #green led
    #GPIO.setwarnings(False)
    #GPIO.setup(26,GPIO.OUT)
    #print( "LED on")
    #GPIO.output(26,GPIO.HIGH)
    #time.sleep(1)
    #print("LED off")
    #GPIO.output(26,GPIO.LOW)
    print('exiting open_door')

def reset_red():
    print( "Reset_red called - LED off")
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(17,GPIO.OUT)
    GPIO.output(17,GPIO.LOW)
    
def glow_red():
    print( "glow_red called")
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(17,GPIO.OUT)
    GPIO.output(17,GPIO.HIGH)
    send_email("Vedant Pillbox - LATE for Medication")
 
def send_email(msg_text): 
    fromaddr = "vedant.a006@gmail.com"
    toaddr = "vedant.a006@gmail.com; prianush@hotmail.com"
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = msg_text
    body = msg_text
    msg.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "ylxwwderuazpcsgd")
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()
    
while(True):
   time.sleep(1)
