
# daqHardReset          
# daqSoftReset          
# daqRefreshState       
# daqSetDefaults        
# daqLoadSettings       file
# daqSaveSettings       file
# daqOpenData           file
# daqCloseData          
# daqSetRunParameters   rate count
# daqSetRunState        state
# daqGetRunState        
# daqResetCounters      
# daqSendCommand        command
# daqReadStatus         
# daqGetStatus          
# daqReadConfig         
# daqVerifyConfig       
# daqSetConfig          variable arg
# daqGetConfig          variable
# daqGetSystemStatus    
# daqGetUserStatus      
# daqGetError           
# daqSendXml            xml_string
# daqDisableTimeout
# daqOpen               system id

#--- imports ---#
import pythonDaq
import time
import os
import sys
import getopt

# Set some default values
run_number = -1
half_module_number = -1
svt_test = False
filter_enabled = False

# Read in the command line arguments
options, remainder = getopt.getopt(sys.argv[1:], 'r:m:sfh', ['run_number=',
							   'half-module=',
							   'svt',
							   'enable-filter',
							   'help',
							  ])

# Parse the command line arguments
for opt, arg in options:
	if opt in ('-r', '--run_number'):
		run_number = arg
 	elif opt in ('-m', '--half-module'):
		half_module_number = arg
	elif opt in ('-s', '--svt'):
		svt_test = True
	elif opt in ('-f', '--enable-filter'):
		filter_enabled = True	
	elif opt in ('-h', '--help'):
		print "\nUsage: run_calibration.py <arguments>"
		print "Arguments: "
		print "\t-r, --run_number: Run number"
		print "\t-m, --half_module: Half module number to test"
		print "\t-s, --svt: Specifies the device to be tested is the SVT"
		print "\t-f, --enable-filter: Enable FIR filter"
		print "\n"
		sys.exit(0)

# Check whether the SVT or a half module is being tested. If neither 
# is specified, exit
if not(svt_test) and half_module_number == -1:
	 print "Please specify whether the SVT or a half module is being tested"
	 sys.exit(0)

# If a user indicates that both the SVT and a half module are being
# tested, warn the user and exit
if svt_test and half_module_number > -1:
	print "Both the SVT and a half module were specified to be tested. Exiting ..."
	sys.exit(0)

# If the run number isn't specified, warn the user that the default value of
# -1 will be used
if run_number == -1:  
	print "Warning: Run number was not specified, using -1"

pythonDaq.daqOpen("hps",1);

print "Starting calibration run ... "

# Configure the DAQ
pythonDaq.daqHardReset()
if svt_test:
#	pythonDaq.daqLoadSettings('/u1/software/daq/config/local_defaults_test.xml') 
	pythonDaq.daqLoadSettings('/u1/software/daq/config/local_defaults.xml') 
	pythonDaq.daqLoadSettings('/u1/software/daq/config/coda_groupC.xml')
	pythonDaq.daqSetConfig("cntrlFpga:TholdEnable", "False")
	pythonDaq.daqSetConfig("cntrlFpga:FiltEnable",  "False") 
	if filter_enabled:
		 pythonDaq.daqSetConfig("cntrlFpga:FiltEnable",  "True")
		 print "Filter has been enabled" 
else:
	pythonDaq.daqLoadSettings('/u1/software/daq/config/devboard.xml');
	pythonDaq.daqSetConfig("cntrlFpga:AdcClkInvert", "False");
#pythonDaq.daqLoadSettings('/u1/software/daq/config/devboard_new.xml');

pythonDaq.daqSoftReset();
pythonDaq.daqSetRunParameters("10Hz",2000);

#pythonDaq.daqSetConfig("cntrlFpga:hybrid:apv25:Ical", str(22))
 
data_path = os.environ['BASE'] 
if svt_test:
	data_path += 'data/SVT2014/full/' + run_number + '/data/calibrations/'
	dut = "svt"
else: 
	data_path += 'data/SVT2014/half_module/'
	data_path += half_module_n + '/' + run_number + '/data/calibrations/' 
	dut = 'halfmodule'
os.system('mkdir -p '+ data_path);

print 'Saving output to '  + data_path

# Close any existing open files
pythonDaq.daqCloseData();

pythonDaq.daqSetConfig("cntrlFpga:hybrid:apv25:CalibInhibit","True")
pythonDaq.daqSetConfig("cntrlFpga:ApvTrigType", "DoubleTrig" )
pythonDaq.daqSetConfig("cntrlFpga:hybrid:apv25:CalGroup","0")
file_path = data_path + dut + '_baseline_dtrig.bin'
print("Running baseline (DoubleTrig)")

os.system('rm -f '+file_path)
pythonDaq.daqSetConfig('DataFile',file_path)
pythonDaq.daqSendCommand('OpenDataFile','')
pythonDaq.daqSetRunState('Running')
while pythonDaq.daqGetRunState() == "Running":
      time.sleep(1)
      print "Running ..."

pythonDaq.daqCloseData()
print "Run " + str(iter) + " complete!"


