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

"""
test04: Test Si570 programmable oscillator

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

SI570_ADDR = 0x55
SI570_RFREQ = 42
SI570_N1 = 7
SI570_HS_DIV = 2

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)

    # Scan i2c bus
    periph_addr = fmc.i2c_scan()

    # Check that the EEPROM is detected on the I2C bus
    if(0 == len(periph_addr)):
        raise PtsError('No peripheral detected on I2C bus')
    else:
        if(1 != len(periph_addr)):
            raise PtsError('Signal integrity problem detected on I2C bus, %d devices detected instead of 1'%(len(periph_addr)))
        else:
            if(SI570_ADDR != periph_addr[0]):
                raise PtsError('Wrong device mounted on I2C bus, address is:0x%.2X expected:0x%.2X'%(periph_addr[0],SI570_ADDR))

    # Get Si570 configuration
    si570_config = fmc.get_si570_config()
    print("\nPrint Si570 configuration")
    print("RFREQ  : %3.28f") % si570_config[0]
    print("N1     : %d") % si570_config[1]
    print("HS_DIV : %d") % si570_config[2]

    # Check Si570 configuration
    if(int(si570_config[0]) != SI570_RFREQ):
        raise PtsError('Si570 bad reference frequency configured or wrong part is mounted')
    if(si570_config[1] != SI570_N1):
        raise PtsError('Si570 CLKOUT output divider is badly configured or wrong part is mounted')
    if(si570_config[2] != SI570_HS_DIV):
        raise PtsError('Si570 DCO high speed divider is badly configured or wrong part is mounted')


if __name__ == '__main__' :
    main()
