#! /usr/bin/env python
#
# This is a script to let the rotational stage randomly
# walk and measure the repeatability of the requested angle
#
# Mar-17-2015

from pylab import *
import ezca, time

ezca = ezca.Ezca()

# a function to spit out a random angle
# between +90 and -90 deg
def rand_angle():
        #vec = [-25.4, 0, 20] #min power, mid power, max power angle
        vec = [-90, -85, -80, -75, -70, -65, -60, -55, -50, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90] #37 elements 
	request = vec #90.0 * 2.0*( rand(1)-0.5 )
	return request

# a function to move the rotational stage
# with the angle specified
def move_rs (ang):
	ezca['PSL-ROTATIONSTAGE_ANGLE_REQUEST'] = ang
	time.sleep(0.1)
	ezca['PSL-ROTATIONSTAGE_COMMAND'] = 4
	return 

# a function to check if the RS is busy 
def is_busy():
	state = ezca['PSL-ROTATIONSTAGE_STATE_BUSY']
	if state == 1:
		busy = True
	else:
		busy = False
	return busy	


#############################################
#  m a i n                                  #
#############################################
if __name__=="__main__":

	Nsample = 37 # number of measurements

	# open a fresh file
        filename = 'PSL_rotStageCalib.txt'
	fp = open(filename, 'w')

	# loop over the proccess by Nsample times
	for jj in range(Nsample):

		# if busy, do not do anything
		while is_busy() == True:
			time.sleep(0.5)
		
		# move the rotaional stage
		req = rand_angle()
		move_rs(req[jj])
		time.sleep(0.5)

		# if busy, do not do anything
		while is_busy() == True:
			time.sleep(1.0)

		# make a measurement
		time.sleep(1.0)
		measured_ang = ezca['PSL-ROTATIONSTAGE_RS_ENC_COUNT_VALUE_DEG']
		measured_pwr = ezca['PSL-PERISCOPE_A_DC_POWERMON']
		calculated_pwr = ezca['PSL-ROTATIONSTAGE_POWER_CALC']

		# record the values
		print "%dth measurement: %e  %e %e %e"%(jj+1, req[jj], measured_ang, measured_pwr, calculated_pwr )
		fp.write("%e %e %e %e\n"%(req[jj], measured_ang, measured_pwr, calculated_pwr))
		fp.flush()
		time.sleep(1)

	# once it is done, close the file
	fp.close()

