#
# mbta.interface.py
#
# send integer values to mbta board
#
# Caroline Jaffe
# MIT Media Lab 12/2/2015
#
# (c) Massachusetts Institute of Technology 2010
# Permission granted for experimental and personal use;
# license for commercial sale available from MIT
#

from Tkinter import *
import serial

bit_delay = 103
#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: mbta.interface.py serial_port"
   sys.exit()
port = sys.argv[1]
#
# open serial port
#
ser = serial.Serial(port,9600)
ser.setDTR()
# 
# callback function
#
def show_entry_fields():
   txt = e.get()
   print("LED ID: %s" % (txt))
   try:
      val = int(txt)  
      if (val > 0 and val <= 30):
         print("valid number, sending!")
         ser.write(txt[0])
         if (val >= 10): #only send second char if there are 2 digits
            root.after(bit_delay, ser.write, txt[1])
         root.after(2*bit_delay, ser.write, 'x')
      else: 
         print("Not a valid input , please try again!")
   except ValueError:
      print("Not a numerical input, please try again!")
#
# set up GUI
#
root = Tk()
root.title('mbta.interface.py (q to exit)')
root.bind('q','exit')
label = Label(root, text="Enter LED ID here:")
label.pack()
e = Entry(root, bd =5)

e.pack()

b1 = Button(root, text='Send to Board', command=show_entry_fields)
b2 = Button(root, text='Quit', command=root.quit)
b1.pack()
b2.pack()
#
# start main loop
#
root.mainloop()