#!/usr/bin/env python
#
# Upload Gcode to a Cincinnati Milacron CNC lathe
# Copyright 2016 Tommy Johnson
# http://www.bobdbob.com/~tjohnson/lathe/

import time
import serial
import string

import sys

if (len(sys.argv)<2):
	print "usage: upload filename\nWill wait for the lathe to request the file, and then upload it\nMust be run before the transfer operation is started on the lathe."
	sys.exit(1)

fnam=sys.argv[1]

f=open(fnam);
pay=f.read()
f.close()

print "uploading %s  %d bytes"%(fnam, len(pay))

ser=serial.Serial("/dev/cuaU0",9600, bytesize=7, parity='E', stopbits=2);

ready=False
while(not ready):
	print "waiting..."
#	ser.write(chr(0x12))
	time.sleep(1)
	while(ser.inWaiting()):	
		c=ord(ser.read(1));
		print "0x%x"%(c)
		if (c==0x11):		# 0x11 ==  DC1
			ready=True
			break;

print "Got 0x11"   # control-Q   XON

print "sending..."

ser.write("%\n");   # start of tape, in RS-491

flow=False
count=0
while (count<len(pay)):
	c=pay[count]
	while(flow or ser.inWaiting()):	
		r=ser.read(1);
		print "got  %c 0x%x"%(r,ord(r))
		if (r==chr(0x13)):
			print "Xoff"
			flow=True
		if (r==chr(0x11)):
			print "Xon"
			flow=False

	if (not flow):
		ser.write(string.upper(c))
		count+=1
		if ((count%1024)==0):
			print "complete %f"%(100.0*count/float(len(pay)))
	time.sleep(0.001)	# important...  not sure why


print "sending EOF thing"

#ser.write(chr(0x10))		# 0x10 is abort
#time.sleep(0.01);

ser.write(chr(0x0))
time.sleep(0.01);
ser.write(chr(0x4))		# EOF marker
time.sleep(0.01);

# The lathe needs to see the DTR DSR pins high.
# Don't close the port /too/ fast.
time.sleep(1.0);

