#!/usr/bin/python
#	HAL userspace component to interface with Arduino,  
#	Open file for writing data
#	
#		Collect serial data from Arduino each second
#		Collect position from HAL component axis.N.pos-relative
#   Close file and Serialwhen RS-274D program ends
#		 (M2) halui.program.is-running == FALSE

#    Copyright (C) 2012 Mark Center

#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#inialize serial port and open file
import serial
import hal
import time

def pollArduino():
	ser.write("RQ\n")  #Request  data
	str = ser.readline()
	if len(str) == 0:
		print "Arduino is not responding!\n"
	else:
		return str
		
PORT = "/dev/ttyACM0"

#open serial for handshake
ser = serial.Serial(PORT, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1)

ser.open()

#generate a unique filename based on time
f = open('data_' + str(int(time.time()))+'.csv','w')

#write header
f.write('xpos, ypos, ain, sp, delT\n')

#create component pins for HAL
h = hal.component("datarecord")
# h.newpin("poll", hal.HAL_BIT, hal.HAL_IO) // NGC does not poll
h.newpin("record", hal.HAL_BIT, hal.HAL_IN)
h.newpin("xpos", hal.HAL_S32, hal.HAL_OUT)
h.newpin("ypos", hal.HAL_S32, hal.HAL_OUT)
h.newpin("sp", hal.HAL_S32, hal.HAL_OUT)
h.ready()

try:
	basetime = time.time()	
	while 1:
		delT = time.time() - basetime
		if h['record'] == 1:
			ain = pollArduino()
			f.write(str( h['xpos']) +","+ str(h['ypos'])+','+str(ain)+','+str(h['sp'])+','+str(delT)+'\n')
		time.sleep(1)

except (KeyboardInterrupt,):
    raise SystemExit, 0
			
			




