# Import the library serial to talk to serial and time to use timers
import serial, time
#Import graphics module
from graphics import *

# Try to connect to the port
try:
    mySerial = serial.Serial('COM4', 9600, timeout=5) #timeout is how long it will look for new data before giving up
except:
    print('Failed to connect')
    exit()
#Draw some starting graphics
win = GraphWin("CNC input", 300, 200)
win.setBackground('white')
lc = Circle(Point(100,150), 40)
rc = Circle(Point(200,150), 40)
l = Text(Point(100,150), "LEFT")
r = Text(Point(200,150), "RIGHT")
s = Text(Point(150,80), "STOPPED")
top = Text(Point(150,20), "STEPPER MOTOR DIRECTION")
lc.draw(win)
rc.draw(win)
l.draw(win)
r.draw(win)
s.draw(win)
top.draw(win)

# Read data and print it to terminal... until you stop the program
while 1:
    c = mySerial.readline() # read one line at a time
    c = c.decode() #Turn it into a string I can work with Source: https://stackoverflow.com/questions/6224052/what-is-the-difference-between-a-string-and-a-byte-string
    if c.find('L') > -1: #Look for our letter in the string, I send them with a newline command as well
        #print('LEFT')
        lc.setFill('blue')
        rc.setFill('white')
        s.setTextColor('white')
    elif c.find('S') > -1:
        #print('STOP')
        lc.setFill('white')
        rc.setFill('white')
        s.setTextColor('black')
    elif c.find('R') > -1:
        #print('RIGHT')
        rc.setFill('blue')
        lc.setFill('white')
        s.setTextColor('white')
#flushInput empties the input buffer to ensures we only read the latest data.
    mySerial.flushInput()
#    line = controller.readline()
#    print(line)
