#
# hello.HC-SR501.py
#
# HC-SR501 motion detectorr hello-world
#    hello.HC-SR501.py serial_port
#
# Neil Gershenfeld 11/16/15
# (c) Massachusetts Institute of Technology 2015
#
# This work may be reproduced, modified, distributed,
# performed, and displayed for any purpose. Copyright is
# retained and must be preserved. The work is provided
# as is; no warranty is provided, and users accept all 
# liability.
#

from Tkinter import *
import serial
import winsound, sys
from PIL import ImageTk, Image

WINDOW = 200 # window size
path = "farage.jpg"

def idle(parent,canvas):
   global filt,eps
   #
   # idle routine
   #
   char = ser.read()
   if (char == '1'):
      x = 1
      text = 'motion'
      canvas.itemconfigure("rect",fill="#ffff1a")
      canvas.itemconfigure("text",text="banana")
      beep(sys.argv[1])
      #sound added to the if 
      
   else:
      x = 0
      text = 'off'
      canvas.itemconfigure("rect",fill="#0000b0")
      canvas.itemconfigure("text",text="No Banana")
   canvas.update()
   parent.after_idle(idle,parent,canvas)

def beep(sound):
    winsound.PlaySound(soundfile, winsound.SND_FILENAME)
    #what kind of sound file to play 

#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: hello.HC-SR501.py serial_port"
   sys.exit()
port = sys.argv[1]
#
# open serial port
#
ser = serial.Serial(port,9600)
ser.setDTR()
ser.flush()
#
# set up GUI
#
root = Tk()
root.title('hello.HC-SR501.py (q to exit)')
root.bind('q','exit')
soundfile = "c:/Windows/Media/tada.wav" #location of the soundfile
img = ImageTk.PhotoImage(Image.open(path)) #the image 
canvas = Canvas(root, width=2*WINDOW, height=WINDOW, background='white')
canvas.create_text(.5*WINDOW,.5*WINDOW,text="read",font=("Courier", 24),tags="text",fill="#0000b0")
canvas.create_rectangle(WINDOW,0,2*WINDOW,WINDOW, tags='rect', fill='#7a0099')
canvas.pack()
#
# start idle loop
#
root.after(100,idle,root,canvas)
root.mainloop()
