import btle, sys, select
from time import sleep
from Tkinter import *

class MyDelegate(btle.DefaultDelegate):
    def __init__(self, params=None):
        btle.DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
    	print data

def input_with_timeout(prompt, timeout):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    ready, _, _ = select.select([sys.stdin], [],[], timeout)
    if ready:
        return sys.stdin.readline().rstrip('\n') # expect stdin to be line-buffered
        
def sendMessage(timeout):
	line = input_with_timeout("", timeout)
	if line != None:
		global char
		char.write(line)

def quit():
	# Stop magnets
	sendButton(9)
	
	# Disconnect from bluetooth
	global conn
	if conn != None:
		conn.disconnect()
		
	# Close GUI
	global root
	if root != None:
		root.destroy()
		
	# Exit
	sys.exit()

def connect():
	# Set up bluetooth connection
	address = "60:64:05:d1:43:ed"
	addrType = "public"
	uuid = "0000ffe0-0000-1000-8000-00805f9b34fb"
	global conn
	conn = btle.Peripheral(address, addrType)

	conn.setDelegate(MyDelegate())
	service = conn.getServiceByUUID(uuid)
	
	global char
	char = service.getCharacteristics()[0]
	# char.write("Connected")

def sendButton(command):
	global buttons
	global activated
	
	if command != 9: # did not receive stop command
		# Update activated and remove old button
		if len(activated) > 0 and activated[0] == 9:
			buttons[activated.pop(0)].config(relief=RAISED)
		
		while len(activated) >= 1:
			buttons[activated.pop(0)].config(relief=RAISED)
		
		# Sink new button
		buttons[command].config(relief=SUNKEN)
		activated.append(command)
	else:
		for motor in activated:
			buttons[motor].config(relief=RAISED)
		activated = [9]
	# Send command over BLE
	if char != None:
		char.write(str(len(activated)));
		for motor in activated:
			char.write(str(motor));

def setUI():
	global root
	global buttons
	
	root = Tk()
	root.title('HTMAA Magbot')

	widget_quit = Button(root, text="Quit", command=quit, height=2, width=6)
	widget_quit.grid(row=0, column=1)

	buttons = []
	b = Button(root, text="1", command=lambda: sendButton(0), height=2, width=2)
	b.grid(row=1, column=0)
	buttons.append(b)
	
	b = Button(root, text="2", command=lambda: sendButton(1), height=2, width=2)
	b.grid(row=1, column=1)
	buttons.append(b)
	
	b = Button(root, text="3", command=lambda: sendButton(2), height=2, width=2)
	b.grid(row=1, column=2)
	buttons.append(b)
	
	b = Button(root, text="4", command=lambda: sendButton(3), height=2, width=2)
	b.grid(row=2, column=0)
	buttons.append(b)
	
	b = Button(root, text="5", command=lambda: sendButton(4), height=2, width=2)
	b.grid(row=2, column=1)
	buttons.append(b)
	
	b = Button(root, text="6", command=lambda: sendButton(5), height=2, width=2)
	b.grid(row=2, column=2)
	buttons.append(b)
	
	b = Button(root, text="7", command=lambda: sendButton(6), height=2, width=2)
	b.grid(row=3, column=0)
	buttons.append(b)
	
	b = Button(root, text="8", command=lambda: sendButton(7), height=2, width=2)
	b.grid(row=3, column=1)
	buttons.append(b)
	
	b = Button(root, text="9", command=lambda: sendButton(8), height=2, width=2)
	b.grid(row=3, column=2)
	buttons.append(b)
	
	b = Button(root, text="Stop", command=lambda: sendButton(9), height=2, width=6, fg="white", bg="red")
	b.grid(row=4, column=1)
	buttons.append(b)
	root.mainloop()

def terminal():
	print "Started terminal, press 'Ctrl+C' to quit"
	try:	
		while True:
		    conn.waitForNotifications(1.0)
		    sendMessage(1.0)
	finally:
		conn.disconnect()

conn = None
char = None
root = None
activated = []
buttons = []
try:
	connect()
	setUI()
	#terminal()
except KeyboardInterrupt:
	quit()
