#!   /usr/bin/env	python
#    coding: utf8

# Copyright CERN, 2011
# Author: Ross Millar <ross.millar@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

## TEST FOR VCXO
import sys
import os
import os.path
import rr
import random
import time
import spi
import csr
import i2c
import gn4124
import fmc_adc_test_suite
from pylab import *
from ptsexcept import *

"""
Test Suite test 1:

Counts 2^31 clock ticks on the mez clock, in terms of the system clock.
Writes a new value to the DAC, which in turn alters the mez clock
Counts 2^31 clock ticks on the mez clock again
Compares the 2 resuls to see if the mez clock has changed appropriately

"""

def mean(numberList):
	if len(numberList)==0:
		return int('nan')
	
	intnums = [int(x) for x in numberList]
	return sum(intnums)/len(numberList)



def main(default_directory='.') :
     
    # Objects declaration
    spec = rr.Gennum() 
    fmc = fmc_adc_test_suite.CFmcAdc100ks(spec)
      
    # Reset DAC register  	- Set VCXO to lowest frequency
    fmc.spi_dac_write(0x0000)      
    
    # Number of sys clock ticks for counter on mezzanine clock to complete count
    result = fmc.clock_comparison()     
    time.sleep(.1)
    
    fmc.spi_dac_write(0xFFFF)
    time.sleep(.1)
    
    # Number of sys clock ticks for counter on mezzanine clock to complete count
    result_1 = fmc.clock_comparison()
        
    print "VCXO @ lowest frequency - Number of sys clock ticks for mez clock count : %d" %result
    print "VCXO @ highest frequency - Number of sys clock ticks for mez clock count : %d" %result_1
   
    
    if (result - result_1) >10:
    	print "DAC and VCXO fully working"
    else:
    	fmc.spi_dac_write(0x0000)
    	dac_low_val = fmc.do_small_acq(15) # decide on channel order in test suite firmware
    	time.sleep(0.1)
    	fmc.spi_dac_write(0xFFFF)
    	time.sleep(0.1)
    	dac_high_val = fmc.do_small_acq(15)
    	print "Value with DAC low ",dac_low_val
    	print "Value with DAC high ",dac_high_val
    	
     	if mean(dac_low_val)+1000 < mean(dac_high_val):
    		print "DAC appears operational however VCXO frequency didnt change as expected"
    		print "Potential connection problem between DAC Vout and VCXO Vctrl Pin"	
    		raise PtsError("VCXO not working, DAC operational, test connection between DAC output and VCXO input")
    	else:
    		print "DAC not working"
    		print "VCXO pullability untested"
    		raise PtsError("DAC not working - Check solder connection")
    	
    	
if __name__ == '__main__':
	main()    
    
