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

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

import sys
import rr
import time
import os
import fmc_adc_test_suite
from ptsexcept import *

import csr


"""
test00: Load firmware and test mezzanine presence line.
For test suite boards with 6ch adcs this test is required to be run first
"""

def main (default_directory='.'):
    path_fpga_loader = '../firmwares/fpga_loader';
    path_firmware = '../firmwares/TestSuite_6ch_ref.bin';
    firmware_loader = os.path.join(default_directory, path_fpga_loader)
    bitstream = os.path.join(default_directory, path_firmware)
    os.system( firmware_loader + ' ' + bitstream)
    time.sleep(2);

    # Objects declaration
    spec = rr.Gennum()
    fmc = fmc_adc_test_suite.CFmcAdc100ks(spec)

    # Check bitsteam type
    bitstream_type = fmc.bitstream_type()
    print('bitstream type:%.8X') % bitstream_type
    if(bitstream_type == 0xFFFFFFFF):
        raise PtsCritical ("Firmware not properly loaded.")
   	print "Pts Critical - firmware not loaded properly"
    if(bitstream_type != 0x1):
        raise PtsCritical ("Wrong bitstream type.")
	print "Pts Critical - wrong bitstream"

    # Dump carrier CSR to log
    print("PCB version    : %d") % ( fmc.pcb_version() ) # used to be a mask here
    print("Carrier type   : %d") % ( fmc.carrier_type()) # and here
    print("Bitstream type : 0x%.8X") % (fmc.bitstream_type())
    print("Bitstream date : 0x%.8X") % (fmc.bitstream_date())
    print("Status         : 0x%.8X") % (fmc.carrier_csr_sta())
    print("Control        : 0x%.8X") % (fmc.carrier_csr_ctl())



    # Check mezzanine presence flag
    status = fmc.check_mez_present()
    print('carrier csr :%.8X') % status
    if(status & 0x1):
    	print "Pts Critical - mez not pres"
        raise PtsCritical ("Mezzanine not present or PRSNT_M2C_L faulty.")
	


if __name__ == '__main__' :
    main()
