#!/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 *
from keyb import *

import rr
import os

"""
test02: Check fmc-dio-5chttl-board ports as output (port driver working, connector connectivity and LVDS to LVCMOS IC working)
Conditions: fmc-dio-5chttl-board presence line working
User intervention required: Yes
Procedure details:
- Load firmware.
- Test mezzanine presence line.
- Oscillate state of fmc-dio-5chttl-board ports
"""

class test02:
   def __init__(self, spec):
      """ check FMC PRESENT-pin state """
      try:
         self.dio = CFmcDio(spec, 0x80000, False)
      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 osc_ports(self):
      """ Oscillate state of fmc-dio-5chttl-board ports """
      for lemon in range(5): # Enable output of all ports and set them to 0
         self.dio.set_out(lemon,0)
         self.dio.set_dir(lemon,1)
      ans=""
      lemon=0
      while ans != "Y" and ans != "N":
         time.sleep(0.05)
         self.dio.set_out((lemon-1)%5,0)
         self.dio.set_out(lemon,1)
         lemon=(lemon+1)%5
         if kbhit():
            ans=raw_input().upper()
            if ans <> "Y" and ans <> "N":
               print "The valid inputs are only Y or N and Enter"
      for lemon in range(5): # Disable output of all ports
         self.dio.set_out(lemon, 0)
         self.dio.set_dir(lemon, 0)
      return ans

   def test_port_out(self):
      """ Port (LEMO 00 connectors) oscillation check """
      tmp_stdout = sys.stdout
      sys.stdout = sys.__stdout__
      tmp_stdin = sys.stdin
      sys.stdin = sys.__stdin__
      print "Connect the testing LEDs to the LEMO 00 connectors of the fmc-dio-5chttla-board ports (120ohm serial resistor included)"
      print "¿Are all the connected testing LEDs blinking alternately?"
      print "Press Y/N and Enter"
      for lemon in range(5): # Disable all termination resistors
         self.dio.set_term(lemon, 0)
      ans=self.osc_ports()
#      purgestdin()
      raw_input("Disconnect the red LEDs from the fmc-dio-5chttla-board ports (in order to perform further tests) and press Enter")
      sys.stdout = tmp_stdout
      sys.stdin = tmp_stdin
      print "The user reported {} operation of board-port outputs".format("a correct" if ans=="Y" else "an incorrect")
      if ans == "N":
         emsg="TSTERR01: Operation of fmc-dio-5chttla-board ports as output failed"
         print emsg
      else:
         emsg=None # test completed successfully
      return emsg

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"

   print "Checking fmc-dio-5chttla board presence"
   test=test02(spec)

   print "\nChecking connectivity of board ports"
   emsg=test.test_port_out()

   print "\nEnd of Test"
   print "RESULT: [{}]".format("FAIL" if emsg else "OK")
   if emsg:
      raise PtsError(emsg)

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

