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

"""
test01: Check fmc-dio-5chttl-board LEDs (LED and LED circuit working)
Conditions: None
User intervention required: Yes
Procedure details:
- Load firmware
- Test mezzanine presence line
- Blink fmc-dio-5chttl-board LEDs
"""

class test01:
   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 test_LEDs(self):
      """ LED-blink Check  """
      tmp_stdout = sys.stdout
      sys.stdout = sys.__stdout__
      tmp_stdin = sys.stdin
      sys.stdin = sys.__stdin__
      print "¿Are the two fmc-dio-5chttla-board LEDs blinking alternately?"
      print "Press Y/N and Enter"
      ans=""
      while ans != "Y" and ans != "N":
         for nled in range(2):
            self.dio.set_led(nled,nled)
         time.sleep(0.2)
         for nled in range(2):
            self.dio.set_led(nled,1-nled)
         time.sleep(0.2)
         if kbhit():
            ans=raw_input().upper()
            if ans <> "Y" and ans <> "N":
               print "The valid inputs are only Y or N and Enter"
      sys.stdout = tmp_stdout
      sys.stdin = tmp_stdin
#      purgestdin()
      for nled in range(2):
         self.dio.set_led(nled,0)
      print "The user reported {} operation of board LEDs".format("a correct" if ans=="Y" else "an incorrect")
      if ans == "N":
         emsg="TSTERR00: Operation of fmc-dio-5chttla-board LEDs 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=test01(spec)

   print "\nChecking LEDs"
   emsg=test.test_LEDs()

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

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

