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

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

# Import system modules
import sys
import time
import os

# Import specific modules
from fmc_adc_spec import *
from fmc_adc import *

# Import common modules
from ptsexcept import *
import rr


"""
test36: Test SDB records

Note: Requires test00.py to run first to load the gateware!
"""

def main (default_directory='.'):

    # Constants declaration
    TEST_NB = 36
    #FMC_ADC_ADDR = '1a39:0004/1a39:0004@000B:0000'
    FMC_ADC_BITSTREAM = '../gatewares/spec_fmcadc100m14b4cha.bin'
    FMC_ADC_BITSTREAM = os.path.join(default_directory, FMC_ADC_BITSTREAM)
    EXPECTED_BITSTREAM_TYPE = 0x1


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

    # SPEC object declaration
    print "Loading hardware access library and opening device.\n"
    spec = rr.Gennum()

    # Bind SPEC object to FMC ADC card
    #for name, value in spec.parse_addr(FMC_ADC_ADDR).iteritems():
    #    print "%9s:0x%04X"%(name, value)

    #spec.bind(FMC_ADC_ADDR)

    # Load FMC ADC gateware
    #print "Loading FMC ADC gateware: %s\n" % FMC_ADC_BITSTREAM
    #if(os.path.isfile(FMC_ADC_BITSTREAM)):
    #    spec.load_gateware(FMC_ADC_BITSTREAM)
    #    time.sleep(2)
    #else:
    #    raise PtsCritical("Gateware file \"%s\" is missing, test stopped." % FMC_ADC_BITSTREAM)

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

    # Mezzanine object declaration (FmcAdc100m14b4cha board specific part)
    try:
        fmc = CFmcAdc100m(spec)
    except FmcAdc100mOperationError as e:
        raise PtsCritical("Mezzanine 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 == 1:
        print "Carrier type OK.\n"

    # Dump carrier's sdb fields
    print("\n\n\n")
    print("=====================================================")
    print("======== CARRIER SDB")
    carrier.sdb_dump()

    # Dump mezzanine's sdb fields
    print("\n\n\n")
    print("=====================================================")
    print("======== MEZZANINE SDB")
    fmc.sdb_dump()

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


if __name__ == '__main__' :
    main()
