import serial # http://pyserial.sourceforge.net/ , Version: 2.7
import autopy3 # http://autopy.org , Version: 0.51
import io

max_x =1919
max_y = 1079
min_xy = 10

while True:
    with serial.Serial('COM9', 115200,parity=serial.PARITY_EVEN) as ser:
        #read padded data recieved from MB headtracker and slice
        xy = ser.read(9)          

        #sliced into X and Y
        y=xy[4:8]
        x=xy[:4]

        #Try to ensure it stays on screen and
        #doesn't die
        try:      
            y=int(y)
            if y>=max_y:
                y=max_y
            if y<=min_xy:
                y=min_xy        
            
            x=int(x)
            if x>max_x:
                x=max_x
            if x<=min_xy:
                x=min_xy
                
            #move the pointer
            autopy3.mouse.move(x,y)
            xy=str(xy)
            #check for button click (A = left click)
            if(xy[10])=="1":
                #print(xy[10])
                autopy3.mouse.click()
            #print(line)
        except:
            pass

