#!/usr/bin/python
#
# To send a gcode file to Arduino Gcode interpreter:  python nc2serial.py < mygcode.nc
#
# This script reads the lines from stdin and writes them to port_id using pySerial module
# After each line it waits until it gets one of the predefined responses from the port
#
# port_id examlpes: "COM1" on Windows, "/dev/ttyUSB0" on Linux
#
 
import serial,sys,time
# for windows
port_id = "COM5"

# For OSX
#port_id = "dev/tty.usbserial-A7006R7r"

# for GNU Lnux
#port_id = "/dev/ttyUSB0"

baud = 38400

if (len(sys.argv) > 1):
	filename=sys.argv[1]
else:
	print "Error : Need a gcode file"
	x = raw_input("Press Enter")
	sys.exit(2)
	
ser = serial.Serial(port=port_id, baudrate=baud, timeout=3)
#time.sleep(2)

print "FLUSHING..."
while True:
    response = ''
    response = ser.readline()
    print response.strip('\n')
    if response is '':
        break

print "MILLING..."		
for line in open(filename, 'r'):
    ser.write(line)
    print line.strip('\n')
    while True:
        response = ser.readline()
        print response
        if response.strip() in ['ok','start','error: Unsupported statement']:
            break
ser.close()
x = raw_input("Press Enter")