#!   /usr/bin/env   python

# Copyright Creotech SA, 2015
# Author: Marek Guminski <marek.guminski@creotech.pl>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org


import sys
import time
import os
import csr


from spec import *
from ptsexcept import *

from utilFunctions import *


import calibr_box
import find_usb_tty
import calibration_box_connections

from spec_identification import *



# Quick test designed to ensure that communication with carrier is possible

"""
test00: 
    load firmware
    check communication with SPEC board
    check if correct gateware is programmed
    check FMC presence
"""


UIDEL = 1;
FIRMWARE_PATH = '/../gateware/syn/spec_top.bin'
INPUT_TIMEOUT  = 30;
AUTOMATION = True

def test_sdbid(dut):
        
    if (dut.sdbid != dut.SDB_SIG ):
        print "SDB signature mismatch!";
        print 'expected SDB: %x' % dut.SDB_SIG;
        print 'found SDB: %x' % dut.sdbid;
        raise PtsCritical("SDB signature mismatch! Communication or programming of SPEC might have failed.");
    else:
        print "SDB Sig matched";

    
def test_gwid(dut):        
        
    if (dut.gwid != dut.GW_ID ):
        print 'expected ID: %x' % dut.GW_ID;
        print 'found ID: %x' % dut.gwid;
        raise PtsCritical('GW ID mismatch! Wrong firmware might have been programmed on SPEC.');
    else:
        print "GW identifier matched";

def test_communication(dut ):
        
        dut.ledr( 0 );
        dut.ledg( 0 );
        
        print >> sys.__stdout__, "Please verify if both SPEC LEDs are off [y/n]"
        tmp = yesnoquestion("", INPUT_TIMEOUT )
        
        
        if( tmp == 0 ):
            raise PtsError('SPEC communication failure. LEDs didn\'t turn off');
        if( tmp == -1 ):
            raise PtsError('User didn\'t verify SPEC LED control test');
        
        
        dut.ledr( 1 );
        dut.ledg( 1 );
        print >> sys.__stdout__, "Please verify if Both SPEC LEDs are on [y/n]"
        tmp = yesnoquestion("", INPUT_TIMEOUT );
        if( tmp == 0 ):
            raise PtsError('SPEC communication failure. LED didn\'t turn on')
        if( tmp == -1 ):
            raise PtsError('User didn\'t verify SPEC LED control test');

        print 'SPEC communication test (LED) was successful';

  
def verify_fmc_present(dut):
    if (not dut.fmc_present):
        raise PtsCritical('FMC card was not detected. Either FmcDac600m12b1chadds is not connected to FMC port or PRSNT_M2C_L line is not connected to GND on FMC board.')
    else:
        print 'FMC card detected'
     

def main (card=None, default_directory='.',suite=None):
  
    specid = spec_identification()[0];
    if specid < 0 :
        raise PtsCritical("Bus number of FmcDac600m12b1chadds was not found")

    if AUTOMATION:
        BOX_USB_VENDOR_ID = 0x10c4 # Cygnal Integrated Products, Inc.
        BOX_USB_DEVICE_ID = 0xea60 # CP210x Composite Device

        print("Looking for calibration box")

        box_tty = find_usb_tty.CttyUSB().find_usb_tty(BOX_USB_VENDOR_ID, BOX_USB_DEVICE_ID)

        if len( box_tty ) < 1:
            raise PtsCritical( "Can't find calibration box. Make sure that it is connected, and that CP210x driver was correctly mounted");
        
        # print("Calibration Box device: %s" % box_tty[0])
        box = calibr_box.CCalibr_box(box_tty[0])
    
        box.select_trigger_loopback(0)
        box.select_output(calibration_box_connections.connections['ref_clk'])
        
    else:
        box = 0;
  
    carrier=spec( FIRMWARE_PATH, specid, True );
    
#     Verification whether communication with SPEC is possible and if firmware is correct
#     SDB magic number verification
    test_sdbid(carrier)

#     gateware ID verification
    test_gwid(carrier)
    
#     check if writing is possible by LED blinking 
    test_communication(carrier )

#     verify FMC presence (fmc_present pin)
    verify_fmc_present(carrier)
    
       
    return 0
        
if __name__ == '__main__' :
    main()

