from PyChipsUser import *
from FmcTluI2c import *

import sys
import time

#boardIpAddr = "192.168.200.16"
boardIpAddr = "192.168.200.32"
boardPortNum = 50001

addrTable = AddressTable("./aida_mini_tlu_addr_map.txt")

board = ChipsBusUdp(addrTable, boardIpAddr, boardPortNum)

# Check the bus for I2C devices
boardi2c = FmcTluI2c(board)

boardFirmware = board.read("FirmwareId")
print "Firmware version = " , hex(boardFirmware)

print "Scanning I2C bus:"
scanResults = boardi2c.i2c_scan()
print scanResults

boardId = boardi2c.get_serial_number()
print "FMC-TLU serial number = " , boardId

resetClocks = 0
resetSerdes = 0

# set DACs to -200mV
print "Setting all threshold DAC to -50mV "
boardi2c.set_threshold_voltage(7, -0.050)

clockStatus = board.read("LogicClocksCSR")
print "Clock status = " , hex(clockStatus)

if resetClocks:
    print "Resetting clocks"
    board.write("LogicRst", 1 )

    clockStatus = board.read("LogicClocksCSR")
    print "Clock status after reset = " , hex(clockStatus)

#print "Setting PLL input to ext. clk"
#board.write("LogicRst", 0 )
#clockStatus = board.read("LogicClocksCSR")
#print "Clock status = " , hex(clockStatus)


inputStatus = board.read("SerdesRstR")
print "Input status = " , hex(inputStatus)

if resetSerdes:
    board.write("SerdesRst", 0x00000003 )
    inputStatus = board.read("SerdesRst")
    print "Input status during reset = " , hex(inputStatus)

    board.write("SerdesRst", 0x00000000 )
    inputStatus = board.read("SerdesRst")
    print "Input status after reset = " , hex(inputStatus)

    board.write("SerdesRst", 0x00000004 )
    inputStatus = board.read("SerdesRst")
    print "Input status during calibration = " , hex(inputStatus)

    board.write("SerdesRst", 0x00000000 )
    inputStatus = board.read("SerdesRst")
    print "Input status after calibration = " , hex(inputStatus)


# Look at status of input IODELAYs
numLoops = 100

oldCount = [0,0,0,0]
sleepTime = 1.0

for iLoop in range(0,numLoops):

    inputStatus = board.read("SerdesRstR")
    print "Input status = " , hex(inputStatus)

    count0 = board.read("ThrCount0R")
    rate0 = (count0 - oldCount[0])/sleepTime
    oldCount[0] = count0
    print " Count , rate 0 = " , count0 , rate0

    count1 = board.read("ThrCount1R")
    rate1 = (count1 - oldCount[1])/sleepTime
    oldCount[1] = count1
    print " Count , rate 1 = " , count1 , rate1

    count2 = board.read("ThrCount2R")
    rate2 = (count2 - oldCount[2])/sleepTime
    oldCount[2] = count2
    print " Count , rate 2 = " , count2 ,rate2

    count3 = board.read("ThrCount3R")
    rate3 = (count3 - oldCount[3])/sleepTime
    oldCount[3] = count3
    print " Count ,rate 3 = " , count3 ,rate3

    print "\n\n"

    time.sleep(sleepTime)


