# Project#6 - Security System Emailer
# Information - In this project we're going to continuously query the RPInoRPI for motion sensor data.
# If the RPInoRPI reads
# back that movement has beeb detected since out last ping, then an email will be sent.
# Watch this video for more information on how to send emails with python:  https://www.youtube.com/watch?v=g_j6ILT-X0k
from email.message import EmailMessage # included library that assists with sending emails
import ssl # For security when sending emails
import smtplib  # For the actual email sending
import serial
import time
import time    # The 'time' module is included with pycharm and allows for us to create delays.
import serial  # The 'serial' or 'pyserial' module needs to be imported.  See the project video for more info.
from playsound import playsound   # You're going to need to import this package, as mycharm won't have it by default.
# What you need to do now is create a sound bite on your phone in MP3 format that says" Who turned out the lights?"
# or any other sound bite that you want to play.  It doesn't matter, really. This is just a tutorial!
# Check this link out.  You can create text-to-speech MP3 audio files here: http://www.fromtexttospeech.com/

try:  # Try to establish communication with the RPInoRPI board.  if successful, only the 'try:' will be executed
    MCU = serial.Serial(port='COM10', baudrate=115200, timeout=0.01)  # Timeout = 0.01.  More on this later.
    time.sleep(5)  # Wait 5 seconds.
except:  # If communication with the RPInoRPI could not be established, then perform the following instead:
    print('System Locked - Cannot communicate with MCU.  Close this program, then reconnect to MCU and restart program')
    while True:  # Forever loop.  Close the program and start again.  Check connection to the RPInoRPI
        pass  # Do nothing

def send_the_email(x):  # This function acts to send the email
    email_sender = 'capnwow123@gmail.com'  # This is my personal email address that I created for this project.
    # You will need to use the video linked above in this code to make your own email address compatible with python
    email_password = 'qumppeakvn5tarih'      # This is my password.  You'll need to add your own here with quotations
    email_receiver = 'pat123.com'  # This is the email address that you'll be sending to.
    subject = 'I sent you this email using python.  Motion has been detected'  # This is the subject line body
    body = "Motion has been detected " + str(x) + ' times since the program started.' # The body of the email
    email = EmailMessage()        # The following lines of code set up the email and send it
    email['From'] = email_sender
    email['To'] = email_receiver
    email['Subject'] = subject
    email.set_content(body)       # Just a required command

    context = ssl.create_default_context()  # add in security

    with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:  # Get ready to send the email
        smtp.login(email_sender, email_password)                            # Login
        smtp.sendmail(email_sender, email_receiver, email.as_string())      # Send the email


# This is the start of the code
counter = 0  # Create a variable named counter and set it to 0
data = 0     # Do the same for a variable named 'data'
while True:  # Execute the following forever until you stop the program
    data = MCU.readline()  # Wait for a response from the MCU, and store the returned value in 'data
    data = str(data)
    #print(data)
    if data == "b'5'":
        #print(data)
        counter = counter + 1
        print('Motion has been detected ' + str(counter) + ' times!')
        send_the_email(counter)
        time.sleep(1)
