#!   /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

# Import system modules
import sys
import time
import os

# Add common modules and libraries location to path
sys.path.append('../../../')
sys.path.append('../../../gnurabbit/python/')
sys.path.append('../../../common/')

# Import common modules
from ptsexcept import *
import rr

# Import specific modules
from fmc_adc_spec import *
from fmc_adc import *
from numpy import *
from pylab import *
from ctypes import *
from calibr_box import *
from cp210x_eeprom import *
import find_usb_tty
from PAGE.Agilent33250A import *
from PAGE.SineWaveform import *


"""
test28: Long term test

1) Configure acquisition with random params
2) Configure waveform generator to generate a sine wave within the acquisition params
3) Perform acquisition
4) Fit acquired waveform to a sine wave and check that it's within boundaries
"""

##################################################
# Constants declaration
##################################################

TEST_NB = 28

# Gateware
FMC_ADC_BITSTREAM = '../firmwares/spec-fmc-adc-v1.0.bin'
FMC_ADC_BITSTREAM = os.path.join(default_directory, FMC_ADC_BITSTREAM)
EXPECTED_BITSTREAM_TYPE = 0x0

# Calibration box
BOX_USB_VENDOR_ID = 0x10c4 # Cygnal Integrated Products, Inc.
BOX_USB_PRODUCT_ID = 0xea60 # CP210x Composite Device
BOX_SET_SLEEP = 0.01

# Agilent AWG
AWG_USB_VENDOR_ID = 0x0403 # Future Technology Devices International, Ltd
AWG_USB_PRODUCT_ID = 0x6001 # FT232 USB-Serial (UART) IC
AWG_BAUD = 57600
AWG_SET_SLEEP = 0.3

# fmc-adc mezzanine
NB_CHANNELS = 4
SSR_SET_SLEEP = 0.05
DAC_SET_SLEEP = 0.01 # in [s]

SAMPLE_WIDTH = 2 # bytes
MEMORY_SIZE = 2^28/(NB_CHANNELS * SAMPLE_WIDTH) # samples
MULTISHOT_MAX_SIZE = 2^11 # samples

MIN_PRE_TRIG_SAMPLES = 0
MAX_PRE_TRIG_SAMPLES = 2^25
MIN_POST_TRIG_SAMPLES = 0
MAX_POST_TRIG_SAMPLES = 2^25
MIN_NB_SHOTS = 1
MAX_NB_SHOTS = 


ACQ_TIMEOUT = 10




def hex2signed(value):
    if(value & 0x8000):
        return -((~value & 0xFFFF) + 1)
    else:
        return value


def acq_config(fmc):
    print "Initialise FMC board\n"
    # Set trigger
    fmc.set_soft_trig()
    # Set acquisition
    fmc.set_pre_trig_samples(PRE_TRIG_SAMPLES)
    fmc.set_post_trig_samples(POST_TRIG_SAMPLES)
    fmc.set_shots(NB_SHOTS)


def acq_channels(fmc, carrier):
    # Make sure no acquisition is running
    fmc.stop_acq()
    # Start acquisition
    fmc.start_acq()
    time.sleep(0.01)
    # Trigger
    fmc.sw_trig()
    # Wait end of acquisition
    timeout = 0
    while('IDLE' != fmc.get_acq_fsm_state()):
        time.sleep(.1)
        timeout += 1
        if(ACQ_TIMEOUT < timeout):
            print "Acquisition timeout. Missing trigger?."
            print "Acq FSm state: %s"%fmc.get_acq_fsm_state()
            return 1
    # Retrieve data trough DMA
    trig_pos = fmc.get_trig_pos()
    print("Trigger position: 0x%8X" % trig_pos)
    #carrier.print_irq_controller_regs()
    # Enable "DMA done" interrupt
    carrier.set_irq_en_mask(0x1)
    #carrier.print_irq_controller_regs()
    raw_input("hit any key to start dma.")
    # Read ACQ_LENGTH samples after the trigger for all channels
    #channels_data = carrier.get_data((trig_pos<<3), ACQ_LENGTH*8)
    channels_data = carrier.get_data(0, ACQ_LENGTH*8)
    #for carrier_addr in range(0,10*4096, 4096):
    #    channels_data = carrier.get_data(carrier_addr, 0x1000)
    # Disable "DMA done" iinterrupt
    carrier.set_irq_en_mask(0x0)
    channels_data = [hex2signed(item) for item in channels_data]
    return channels_data


def acq_mean(acq_data):
    mean_d = []
    for channel in range(1,NB_CHANNELS+1):
        # calculate mean value for each channel
        mean_d.append(mean(acq_data[channel-1::4]))
    return mean_d



def main (default_directory='.'):


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

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

    # Load FMC ADC firmware
    print "Loading FMC ADC firmware: %s\n" % FMC_ADC_BITSTREAM
    spec.load_firmware(FMC_ADC_BITSTREAM)
    time.sleep(2)

    # Carrier object declaration (SPEC board specific part)
    # Used to check that the firmware is loaded.
    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)


    try:

        # Others objects declaration
        usb_tty = find_usb_tty.CttyUSB()
        awg_tty = usb_tty.find_usb_tty(AWG_USB_VENDOR_ID, AWG_USB_PRODUCT_ID)
        box_tty = usb_tty.find_usb_tty(BOX_USB_VENDOR_ID, BOX_USB_PRODUCT_ID)
        gen = Agilent33250A(device=awg_tty[0], bauds=AWG_BAUD)
        sine = SineWaveform()
        box = calibr_box.CCalibr_box(box_tty[0])





        # Configuration
        acq_config(fmc)

        error = 0

        # All inputs in calibration mode
        for i in range(1, NB_CHANNELS+1):
            fmc.set_input_range(i, "CAL")

        # Disable test pattern (just in case)
        fmc.testpat_dis()


        # Acquire and read channels
        print("Acquire and read all channels.")
        acq_data = acq_channels(fmc, carrier)
        print("Read done.")
        acq_data_mean = acq_mean(acq_data)
        for i in range(len(acq_data_mean)):
            print "ADC channel %d mean value:%d" % (i+1, acq_data_mean[i])

        # Reset offset DACs
        fmc.dc_offset_reset()
        time.sleep(DAC_SET_SLEEP)

    except(FmcAdc100mSpecOperationError, FmcAdc100mOperationError) as e:
        raise PtsError("Test failed: %s" % e)


    print ""
    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)

    # Check if an error occured during offset DAC test
    if(error != 0):
        raise PtsError('An error occured during offset DAC test, check log for details.')


if __name__ == '__main__' :
    main()
