# TouchsensorGUI.py
# recieves the touched sensors and display them
# the code is adapted from Neil's work
#
# Modified By Mohamed Kamel
# Fab Academy 2016
# 
# Neil Gershenfeld
# CBA MIT 10/24/09
#
# (c) Massachusetts Institute of Technology 2009
# Permission granted for experimental and personal use;
# license for commercial sale available from MIT
#

# 

from Tkinter import *
import serial

lastByte = 0

WINDOW = 800 # window size

squaresNumber = 4

tsquare = WINDOW / (squaresNumber + (squaresNumber - 1) + 2) #square size

tsquareColor = '#d6d6c2'
tsquareColor_active = '#000033'
backgroundColor = '#7a7a52'

def idle(parent,canvas):
   #
   # idle routine
   #
   global tsquareColor
   global tsquareColor_active

   ser.flush()
   sbyte = ord(ser.read())
   touchSensors = [(sbyte & 1,'rect1'), ((sbyte & 2) >> 1, 'rect2'), ((sbyte & 4) >> 2, 'rect3'), ((sbyte & 8) >> 3, 'rect4')]
   for x, n in touchSensors:
        if x == 1:
           canvas.itemconfigure(n, fill=tsquareColor_active)
        else:
           canvas.itemconfigure(n, fill=tsquareColor)

   canvas.update()

   parent.after_idle(idle,parent,canvas)

#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: TouchsensorGUI.py serial_port"
   sys.exit()
port = sys.argv[1]
#
# open serial port
#
ser = serial.Serial(port,9600)
ser.setDTR()
#
# set up GUI
#
root = Tk()
root.title('TouchsensorGUI.py (q to exit)')
root.bind('q','exit')
canvas = Canvas(root, width=WINDOW, height=.4*WINDOW, background=backgroundColor)

canvas.create_rectangle(tsquare , ((0.4*WINDOW)-tsquare)/2.0,2*tsquare,((0.4*WINDOW)- tsquare)/2.0+tsquare,tags='rect1',fill=tsquareColor)
cLast = canvas.coords("rect1")

canvas.create_rectangle(cLast[2] + tsquare, cLast[1], cLast[2] + 2*tsquare, cLast[3],tags='rect2', fill=tsquareColor)
cLast = canvas.coords("rect2")

canvas.create_rectangle(cLast[2] + tsquare, cLast[1], cLast[2] + 2*tsquare, cLast[3], tags='rect3', fill=tsquareColor)
cLast = canvas.coords("rect3")

canvas.create_rectangle(cLast[2] + tsquare, cLast[1], cLast[2] + 2*tsquare, cLast[3], tags='rect4', fill=tsquareColor)
canvas.pack()
cLast = canvas.coords("rect4")
#
# start idle loop
#
root.after(100,idle,root,canvas)
root.mainloop()
