#!   /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 csr
import fmc_adc


"""
test02: Test EEPROM

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

EEPROM_ADDR = 0x50

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 FMC system i2c bus
    periph_addr = fmc.sys_i2c_scan()

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

    # Write, read back and compare
    addr = 0x20
    wr_data = [0x55, 0xAA, 0x00, 0xFF]
    rd_data = []
    print('Write data at EEPROM address:0x%.2X')%addr
    print wr_data
    fmc.sys_i2c_eeprom_write(addr, wr_data)
    time.sleep(0.1)
    print('Read back data from EEPROM address:0x%.2X')%addr
    rd_data = fmc.sys_i2c_eeprom_read(addr, len(wr_data))
    print rd_data
    if(rd_data != wr_data):
        raise PtsError('Cannot access EEPROM at address:0x%.2X'%(EEPROM_ADDR))
    else:
        print('Data comparison OK.')


if __name__ == '__main__' :
    main()
