# Project#4 - Who turned out the lights?
# Information - In this project, we're going to query the RPInoRPI over and over until the RPI reports back that the...
# Lights have turned off.  At which point, the PC will play a sound bite of your choice.
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 pycharm 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='COM4', 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

# Remember this function?  Yeah, we're going to be using it in most programs.
def slicer(value): # This function takes the returned value from the RPInoRPI and formats it.
    # What do I mean? The RPInoRPI returns values that look like this: b'5'.
    # So what?  So we need to change that string value into a number for comparison.
    value = value.replace('b','')  # We've received value, which looks like b'5'.  Replace 'b' with nothing.
    # value does from looking like b'5' to '5'
    value = value.replace("'",'')  # Remove all ' from value.  Now we're left with 5
    if value != '':                # if the new slicer value is nothing (''), then ignore the following line
        value = int(value)         # At this point value is still a string. int changes it into a comparable number
    return value # This is the end of this function.  The original value was an unusable string.  Now a usable number!


# This function serves to send a request to the MCU and wait for returned data
def write_read(x):
    MCU.write(bytes(x, 'utf-8'))  # Unicode Transformation Format - 8 bits.  Write an 8-bit value to the MCU
    global data                   # Set as a global varible
    data = MCU.readline()  # Wait for a response from the MCU, and store the returned value in 'data'
    return data   # Return the data to the main code

# Main Code
x = 0  # Create a variable named x and set it to 0
while True:  # Run the following code until you close the program (loop forever)
    x = '5' # Set x to '5', whcih is 53 ASCII. Sending this will instruct the RPInoRPI to return a light value of 0 or 1
    # Where 1 is lights on, and 0 is lights off.
    value = write_read(x)    # call the write_read function and send 'x' along with it. We can only send string data
    print('Returned Value = ' + str(value))  # Concatenate the string + the string version of 'value' together and print
    value = slicer(str(value))  # Less complicated than it looks.  send 'value' to the slicer function in string form
    print('New number after slicer function = ' + str(value)) # Print the sliced string>number
    if value == 0:              # If the newly sliced value is 0, then lights are off. If so, do the following:
        print('Who Turned Out The Lights?!')  # If said number is 5, print this to the shell.
        playsound('C:\\Users\\engin\\soundbites\\lights.mp3')  # Have your PC play this sound bite
    else:
        print('The lights are on, baby cakes!')  # Otherwise, just print this to the shell
    time.sleep(1)


# This is the end of the fourth project.  We built mainly on project#2 for this project.
# We changed the timeout when connecting to the RPInoRPI to 0.01 and the delay after that line to 5 seconds.
# Why did we do this?  The first send/receive transaction may not work properly.  We'll just ignore it.
# In project 2 we have some timing concessions to ensure that the first communication was not list in the darkness.
# For this project, we don't care.  The first transaction will be a throwaway if it returns b'', and not b'0' ir b'1'
# Anyhow, now you know how to play MP3 sound bites from your computer.  I hope that you had fun with this project!