#!   ./python
#    coding: utf8

# Copyright CERN, 2013
# Author: Matthieu Cattin <matthieu.cattin@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

# Import system modules
import sys
import time
import os

# Add common modules and libraries location to path
sys.path.append('../../../')
sys.path.append('../../../common/')
sys.path.append('../../../../svec_pts/ubuntu/pts/pyts/')

# Import common modules
from ptsexcept import *
from rr2vv import *

# Import specific modules
from fmc_adc_svec import *


"""
test00: Load firmware, verify firmware type and test mezzanine presence line.
"""

def main (default_directory='.'):

    # Constants declaration
    LUN = 0
    TEST_NB = 0
    FMC_ADC_BITSTREAM = '../../../../../firmwares/svec_fmcadc100m14b4cha.bin'
    FMC_ADC_BITSTREAM = os.path.join(default_directory, FMC_ADC_BITSTREAM)
    EXPECTED_BITSTREAM_TYPE = 0x0


    start_test_time = time.time()
    print "\n================================================================================"
    print "==> [SVEC] Test%02d start\n" % TEST_NB

    # SVEC object declaration
    print "Loading hardware access library and opening device.\n"
    bus = VME_rr_compatible(LUN)
    print "Initialising device.\n"
    bus.vv_init()

    # Load FMC ADC firmware
    print "Loading FMC ADC firmware: %s\n" % FMC_ADC_BITSTREAM
    ret = bus.vv_load(FMC_ADC_BITSTREAM, 1)
    print('')
    time.sleep(2)

    # Carrier object declaration (SPEC board specific part)
    try:
        carrier = CFmcAdc100mSvec(bus, EXPECTED_BITSTREAM_TYPE)
    except FmcAdc100mSvecOperationError as e:
        raise PtsCritical("Carrier init failed, test stopped: %s" % e)

    # Print bitsteam type
    carrier_type = carrier.get_carrier_type()
    print('Carrier type:0x%.8X') % carrier_type
    if carrier_type == 2:
        print "Carrier type OK.\n"
    else:
        raise PtsCritical("Unexpected carrier type!\n")

    # Print carrier CSR registers
    carrier.print_csr()

    print "==> End of test%02d" % TEST_NB
    print "================================================================================"
    end_test_time = time.time()
    print "[SVEC] Test%02d elapsed time: %.2f seconds\n" % (TEST_NB, end_test_time-start_test_time)

    bus.vv_close()


if __name__ == '__main__' :
    main()
