#!   ./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 *
from fmc_adc import *


"""
test02: Test interrupts
"""

def main (default_directory='.'):

    # Constants declaration
    LUN = 0
    TEST_NB = 2
    FMC_ADC_BITSTREAM = '../../../../../firmwares/svec_fmcadc100m14b4cha.bin'
    FMC_ADC_BITSTREAM = os.path.join(default_directory, FMC_ADC_BITSTREAM)
    EXPECTED_BITSTREAM_TYPE = 0x0
    NB_CHANNELS = 4
    EEPROM_ADDR = 0x50
    SI570_ADDR = 0x55
    TEST_PATTERN = 0x6A1


    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"

    # Load FMC ADC firmware
    ask = 'N'
    while ((ask != "Y") and (ask != "N")) :
        ask = raw_input("Do you want to load the firmware: %s? [y,n]"%(FMC_ADC_BITSTREAM))
        ask = ask.upper()
        print " "

    if (ask == "Y"):
        print "Loading FMC ADC firmware: %s\n" % FMC_ADC_BITSTREAM
        bus.vv_init()
        ret = bus.vv_load(FMC_ADC_BITSTREAM, 1)
        print('')
        time.sleep(2)
    else:
        bus.vv_open()

    # 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)

    # Test carrier periherals
    print('\n-------------------------------------------------------------')
    print('[Carrier]')
    carrier.print_unique_id()
    carrier.print_temp()

    # Mezzanines object declaration (FmcAdc100m14b4cha board specific part)
    fmc = []
    for i in range(2):
        try:
            print('\n-------------------------------------------------------------')
            print('[FMC slot %d]'%(i+1))
            mezz_offset = 0x2000+i*0x4000
            print('Mezzanine offset: 0x%08X'%(mezz_offset))
            fmc.append(CFmcAdc100m(bus, mezz_offset))
        except FmcAdc100mOperationError as e:
            raise PtsCritical("Mezzanine %d init failed, test stopped: %s" % (i+1, e))

    # Test mezzanines peripherals
    error = ['','']
    for i in range(2):
        try:
            print('\n-------------------------------------------------------------')
            print('[FMC slot %d]'%(i+1))

            # Disable and clear all interrupts
            carrier.set_irq_en_mask(0x0)
            ret = carrier.get_irq_status()
            carrier.clear_interrupt(ret)

            # Enable trigger interrupt
            carrier.print_irq_controller_regs()
            print('Enable trigger interrupt')
            carrier.set_irq_trig_mask(i, 1)
            carrier.print_irq_controller_regs()

            # Acquisition setup
            # hw trig, rising edge, external, sw disable, no delay
            print('')
            for j in range(100):
                fmc[i].set_trig_config(1, 0, 1, 1, 1, 0, 0)
                fmc[i].set_pre_trig_samples(500)
                fmc[i].set_post_trig_samples(500)
                fmc[i].set_shots(1)
                fmc[i].stop_acq()
                print "%d: Acquisition FSM state : %s (should be IDLE)" % (j,fmc[i].get_acq_fsm_state())
                fmc[i].start_acq()
                #time.sleep(3)

                print "Wait for trigger."

                # Wait from interrupt
                ret = bus.vv_irqwait()
                print('[irq wait] irq source reg = 0x%.8X'%ret)

                ret = carrier.get_irq_status()
                print('irq status = 0x%.8X'%ret)

                time.sleep(1)
                ret = carrier.clear_interrupt(ret)
                print('Clear interrupt, irq status = 0x%.8X'%ret)
                #carrier.print_irq_controller_regs()
                time.sleep(1)

            # Disable trigger interrupt
            print('Disable trigger interrupt')
            carrier.set_irq_trig_mask(i, 0)
            carrier.print_irq_controller_regs()


        except FmcAdc100mOperationError as e:
            raise PtsError("Mezzanine %d onewire test failed: %s" % (i+1, e))

    print('')
    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)

    if(error[0] != ''):
        raise PtsError('[FMC slot 1]' + error[0])
    if(error[1] != ''):
        raise PtsError('[FMC slot 2]' + error[1])

    bus.vv_close()


if __name__ == '__main__' :
    main()
