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


"""
test03: Test mezzanine front-panel LEDs

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


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)

    # Standard in/out temporary redirection
    tmp_stdout = sys.stdout;
    sys.stdout = sys.__stdout__;
    tmp_stdin = sys.stdin;
    sys.stdin = sys.__stdin__;

    # Initialize error variable, disable triggers and make sure no acquisition is running
    error = [0, 0]
    fmc.set_trig_config(1, 0, 0, 0, 0, 0, 0)
    fmc.stop_acq()

    ############################################################################
    # Test LEDs ON
    fmc.trig_led(1)
    fmc.acq_led(1)

    ask = "";
    while ((ask != "Y") and (ask != "N")) :
	print "-------------------------------------------------------------"
    	ask = raw_input("Are the front panel LEDs (TRIG and ACQ) switched ON? [y,n]")
	ask = ask.upper()
	#print "-------------------------------------------------------------"
        print " "

    if (ask == "N"):
        # LED ON fail
        error[0] += 1

    ############################################################################
    # Test LEDs OFF
    fmc.trig_led(0)
    fmc.acq_led(0)

    ask = "";
    while ((ask != "Y") and (ask != "N")) :
	print "-------------------------------------------------------------"
    	ask = raw_input("Are the front panel LEDs (TRIG and ACQ) switched OFF? [y,n]")
	ask = ask.upper()
	#print "-------------------------------------------------------------"
        print " "

    if (ask == "N"):
        # LED OFF fail
        error[0] += 1

    # Standard in/out redirection
    sys.stdout = tmp_stdout;
    sys.stdin = tmp_stdin;

    # Check if an error occured during LED test
    if (error != [0]*2):
        if(error[0] != 0):
            print("One or both LEDs not switching ON. Check for soldering or connection problem, grounded control line.")
        if(error[1] != 0):
            print("One or both LEDs not switching OFF. Check for short-cut.")
        raise PtsError('An error occured during LEDs test, check log for details.')
    else:
        print('LEDs are working ok.')


if __name__ == '__main__' :
    main()
