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

"""
test05: Test LTC2174 ADC

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

TEST_PATTERN = 0x3A5
NB_CHANNELS = 4

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)

    # Set and enable test pattern
    fmc.testpat_en(TEST_PATTERN)

    # Read and check test pattern
    pattern = fmc.get_testpat()
    if(TEST_PATTERN != pattern):
        raise PtsError('Cannot access LTC2174 ADC through SPI')

    # Print LTC2174 configuration
    fmc.print_adc_regs()

    # Check that SerDes are synchronised
    if(0 == fmc.get_serdes_sync_stat()):
        raise PtsError('SerDes are not synchronised')

    # Read channels current data register
    for i in range(1,NB_CHANNELS+1):
        adc_value = fmc.get_current_adc_value(i)
        print('ADC channel %d value:0x%.4X') % (i, (adc_value>>2))
        if(TEST_PATTERN != (adc_value>>2)):
            raise PtsError('Data read from LTC2174 ADC are wrong for channel %d'%i)


if __name__ == '__main__' :
    main()
