#! /usr/bin/env	python
# coding: utf8
# Copyright CERN, 2011
# Author: Ross Millar <ross.millar@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

import sys
import rr
import random
import time
import spi
import csr
import i2c
import gn4124
import fmc_adc_test_suite	
#from pylab import *
from ptsexcept import *

import os








"""
EEPROM test, tests if you can write and then read a result from the EEPROM on the mezzanine
"""
    
def main (default_directory='.'):

#    path_fpga_loader = '../firmwares/fpga_loader';
#    path_firmware = '../firmwares/TestSuite.bin'; 	
#    firmware_loader = os.path.join(default_directory, path_fpga_loader)
#    bitstream = os.path.join(default_directory, path_firmware)
#    os.system( firmware_loader + ' ' + bitstream)
#    time.sleep(2);

  # Objects declaration
    spec = rr.Gennum() 
    fmc = fmc_adc_test_suite.CFmcAdc100ks(spec)     
    
    EEPROM_ADDR = 0x50
    EEPROM_ADDR_FOUND = fmc.sys_i2c_scan()
    
    if(len(EEPROM_ADDR_FOUND) == 0):
       raise PtsError('No peripheral detected on system management I2C bus')
    else:
    	if(len(EEPROM_ADDR_FOUND) != 1):
           raise PtsError('Signal integrity problem detected on system management I2C bus, %d devices detected instead of 1'%(len(EEPROM_ADDR_FOUND)))
    	else:
    	    if(EEPROM_ADDR != EEPROM_ADDR_FOUND[0]):
            	raise PtsError('Wrong device mounted on system management I2C bus, address is:0x%.2X expected:0x%.2X'%(EEPROM_ADDR_FOUND[0],EEPROM_ADDR))
    
    addr    = 	0x10
    wr_data = 	[0x11,0x22,0x33,0x44]    
    rd_data = []
    
    print('Write data at EEPROM address:0x%.2X')%addr
    print wr_data	
    
    fmc.sys_i2c_eeprom_write(addr, wr_data)
    time.sleep(.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.')
        print"EEPROM Device fully functional"




if __name__ == '__main__' :
	main()    
