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

from ptsexcept import *

import fmc_adc
from PAGE.Agilent33250A import *
from PAGE.SineWaveform import *

"""
test06: Test trigger input

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

USB_DEVICE = "/dev/ttyUSB0"
RS232_BAUD = 57600

NB_CHANNELS = 4
PRE_TRIG_SAMPLES = 500
POST_TRIG_SAMPLES = 500
NB_SHOTS = 1
TIMEOUT = 1

def main (default_directory='.'):

    """
    path_fpga_loader = '../../../gnurabbit/user/fpga_loader';
    path_firmware = '../firmwares/spec_fmcadc100m14b4cha.bin';

    firmware_loader = os.path.join(default_directory, path_fpga_loader)
    bitstream = os.path.join(default_directory, path_firmware)
    print firmware_loader + ' ' + bitstream
    os.system( firmware_loader + ' ' + bitstream )

    time.sleep(2);
    """

    # Objects declaration
    spec = rr.Gennum() # bind to the SPEC board
    fmc = fmc_adc.CFmcAdc100Ms(spec)
    gen = Agilent33250A(device=USB_DEVICE, bauds=RS232_BAUD)
    sine = SineWaveform()

    # Set sine params
    sine.frequency = 1E3
    sine.amplitude = 1
    sine.dc = 0

    # Set AWG and turn it ON
    gen.connect()
    gen.output = True
    gen.play(sine)

    # Disconnect all inputs
    for i in range(1, NB_CHANNELS+1):
        fmc.set_input_range(i, "OPEN")

    # Set trigger
    # hw trig, rising edge, external, sw disable, no delay
    fmc.set_trig_config(1, 0, 1, 1, 0, 0, 0)

    # Set acquisition
    fmc.set_pre_trig_samples(PRE_TRIG_SAMPLES)
    fmc.set_post_trig_samples(POST_TRIG_SAMPLES)
    fmc.set_shots(NB_SHOTS)

    # Start acquisition
    fmc.stop_acq()
    print('Acquisition FSM state : %s (should be IDLE)') % fmc.get_acq_fsm_state()
    fmc.start_acq()
    time.sleep(TIMEOUT)

    # Switch AWG OFF
    gen.output = False
    gen.close()

    # Check if the trigger has been received
    if('WAIT_TRIG' == fmc.get_acq_fsm_state()):
        print('Acquisition FSM state : %s') % fmc.get_acq_fsm_state()
        raise PtsError('External trigger input is not working')
    else:
        print('The external trigger input is working fine.')


if __name__ == '__main__' :
    main()
