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

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

from ptsexcept import *
from dio_fmc import *

import rr
import os


"""
test00: Check fmc-dio-5chttl-board presence
Conditions: None
User intervention required: No
Procedure details:
- Load firmware
- Test mezzanine presence line.
"""

class test00:
   def __init__(self, spec):
      """ Initialize the board, check PRESENT pin state """
      self.dio = CFmcDio(spec, 0x80000, False, False, False) # Do not init any I2C or OneWire device

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 "Test00 Start"

   init_test_time = time.time()
   print "Checking fmc-dio-5chttla board presence"
   try:
      test=test00(spec)
   except CFmcDioError as e:
      test_error=e
      print str(test_error)
   else:
      test_error=None

   end_test_time = time.time()
   print "\nEnd of Test00"

   print "RESULT: [{}]".format("FAIL" if test_error else "OK")
   print 'Test00 elapsed time: {:.2f} seconds'.format(end_test_time-init_test_time)
   if test_error:
      err_msg="While fmc-dio-5chttla initialization: "+str(test_error)
      if test_error.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

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

