#!/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

import sys
import rr
import random
import time
import spi
import csr
import i2c
import gn4124
import fmc_adc_test_suite
import cp210x_gpio
#from pylab import *
#from ptsexcept import *
import fcntl, struct, termios, os
import time
import array



class cp210x_gpio:
	def __init__(self, usb_number):
		self.fd = open('/dev/ttyUSB' + str(usb_number), 'wb')

	def gpio_set(self, mask):
		fcntl.ioctl(self.fd.fileno(), 0x8001, mask)

	def gpio_get(self):
		f = array.array('I', [0])
		ret = fcntl.ioctl(self.fd.fileno(), 0x8000, f, 1)
		return f[0]

"""
Test the analog inputs to the ADC

"""

def main (default_directory='.'):
	
	# Object Declaration
	spec = rr.Gennum() # bind to the SPEC board
	fmc = fmc_adc_test_suite.CFmcAdc100ks(spec)
	gpio = cp210x_gpio(0)
	
	# All inputs high
	#force_inputs = sim_function(12)
		
	
	gpio.gpio_set(0xF)
	split_channels = []
	average = []
	error_cnt =0
	average =  fmc.do_acq(1, "camera_link" ,"Y",10,10,0)
	

	for element in range(len(average)):
		if average[element] <100: # Change from 5 to something more reasonable
			print "\nError: Pin voltage lower than expected on pin %d "%element
			print "Details: Expected value was ~5 "
			print "Details: Received value was %d \n"%average[element]
			error_cnt = error_cnt+1 
		else:	
			print "Voltage on pin %d was as expected"%(element+1)
					
	
	for i in range(11):
		print "Setting Channel %d low ..."%(i+1)
	      	# Set Addr on GPIOs in the test box
		gpio.gpio_set((i) & 0xF)
		
		# Do an acquisiton, return the average voltage on each channel
		average =  fmc.do_acq(1, "camera_link" ,"Y",10,10,0)
		for k in range(11):
						 
			# if channel doesnt equal the input with ~ 0V on input
			if k!=i:
				if average[k] <= 1000:
					print "Error: channel value not as expected on channel %d\n"%(k+1)
					print "Error: Expected V high of _____, found value of %d" %average[k]
					print "Error: Possiblity of Channel %d shorted to ground"%(k+1)
					error_cnt =error_cnt+1
			elif i == k:
				if average[k] >=50:
					print "Error: Expected V low of ~0 V on input, found value of %d"%average[i]
					print "Error: Possibility of Pin %d shorted to an adjacent pin"%(k+1) 
					error_cnt =error_cnt +1
					
	if error_cnt==0:
		print "No Errors, All input pins fully functional"
	else:
		raise PtsError("ADC Analogue input Test Failed - See Log for reason of failure")
		print "test failed - see log for details"
			
							
if __name__ == '__main__':
    main()        
    
