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

# Copyright Seven Solutions S.L., 2012
# Author: Richard Carrillo <rcarrillo(AT)sevensols.com>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org
# Website: http://www.sevensols.com
# Version: 0.1 (Last modifications: 1/4/2012)


from ptsexcept import *
from dio_fmc import *

import rr
import os

"""
test05: Check termination resistors of fmc-dio-5chttl-board ports
Conditions: fmc-dio-5chttl-board ports work as outputs (test02 passed), I2C bus works (test00 passed) and
 fmc-dio-5chttl-board ports work as inputs (DAC, LVDS comparator) (test03 passed)
User intervention required: No
Procedure details:
- Load firmware.
- Test mezzanine presence line.
- Check the voltage of all ports (be means of the DAC) when port output set to 1, output enable set to 0
   and termination resistor enabled
"""

class test05:
   def __init__(self, spec):
      """ check FMC PRESENT-pin state """
      try:
         self.dio = CFmcDio(spec, 0x80000, True)
      except CFmcDioError as e:
         err_msg="While fmc-dio-5chttla initialization: "+str(e)
         if e.bus_name == "FMC":
            raise PtsCritical(err_msg) # Critical error: the fmc-dio-5chttl-board is apparently not present
         else:
            raise PtsError(err_msg) # Non-critical error: further tests could be performed successfully

   def test_port_term(self):
      """ Port (LEMO 00 connectors) termination-resistor enable check """
      print "Ensure that nothing is connected to the fmc-dio-5chttla-board ports"
      print "(Termination resistors enabled, port outputs enabled)"
      port_th=[]
      port_warnlow=[]
      port_warnhigh=[]
      for lemon in range(5):
         self.dio.set_term(lemon, 1) # Enable termination resistor
         self.dio.set_dir(lemon,1) # Enable port output
         self.dio.set_out(lemon,1) # Set port output value to 1
         try:
            th1=self.dio.find_port_voltage(lemon,2.95,3.02)  # Find the voltage (threshold)
         except CFmcDioError as e:
            raise PtsError("While setting CDAC5578 channel value: "+str(e))
         self.dio.set_dir(lemon,0) # Disable port output
         self.dio.set_out(lemon,0) # Set port output value to 0
         self.dio.set_term(lemon, 0) # Disable termination resistor
         if th1>3.1:
            th1_warn="Warning: Strangely-high value "
            port_warnhigh.append(lemon)
         elif th1<2.9:
            th1_warn="Warning: Strangely-low value "
            port_warnlow.append(lemon)
         else:
            th1_warn="OK"
         print "Port {} apparent input voltage: {:.3f}V {}".format(lemon,th1,th1_warn)
         port_th.insert(lemon,th1)
      port_err=[]
      for lemon in range(len(port_th)):
         if port_th[lemon]>3.2 or port_th[lemon]<2.8: # normal operating conditions
            port_err.append(lemon)
      if port_err: # Some errors were detected
         ret_error=["E","TSTERR04: Proper voltage reading not obtained in ports: {} when termination resistors enabled".format(port_err)]
         print ret_error[1]
      else:
         if port_warnlow or port_warnhigh: # Some warning were generated
            warn_msg=""	
            if port_warnlow:
               warn_msg=warn_msg+"TSTWRN03: Strangely-low voltage value obtained in ports: {} when termination resistors enabled. ".format(port_warnlow)
            if port_warnhigh:
               warn_msg=warn_msg+"TSTWRN04: Strangely-high voltage value obtained in ports: {} when termination resistors enabled. ".format(port_warnhigh)
            ret_error=["W",warn_msg]
         else:
            ret_error=None
      return ret_error

def main(default_directory="."):
   # Configure the FPGA using the program fpga_loader
   path_fpga_loader = '../firmwares/fpga_loader'
   path_firmware = '../firmwares/spec_top.bin'
   firmware_loader = os.path.join(default_directory, path_fpga_loader)
   bitstream = os.path.join(default_directory, path_firmware)
   print "Loading firmware: %s" % (firmware_loader + ' ' + bitstream)
   os.system( firmware_loader + ' ' + bitstream )

   # Load board library and open the corresponding device
   print "Loading hardware access library and opening device\n"
   spec = rr.Gennum()

   print "Test Start"

   init_test_time = time.time()
   print "Configuring and checking fmc-dio-5chttla devices"
   test=test05(spec)

   print "\nChecking output-enable circuits of board ports"
   ret_error=test.test_port_term()

   end_test_time = time.time()
   print "\nEnd of Test"
   print "RESULT: [{}]".format("FAIL" if ret_error and ret_error[0]=="E" else ("OK with warnings" if ret_error and ret_error[0]=="W" else "OK"))
   print 'Test05 elapsed time: {:.2f} seconds'.format(end_test_time-init_test_time)
   if ret_error:
      if ret_error[0]=="W": # Warning message returned by test funciton
         raise PtsWarning(ret_error[1])
      else:  # Error message returned by test funciton
         raise PtsError(ret_error[1])

if __name__ == "__main__":
    main(".")

